anthropicapi

package
v0.1.64 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 29, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package anthropicapi translates the Anthropic Messages API dialect to and from GoModel's canonical chat types. It is an ingress concern: it accepts the Anthropic wire format from clients and renders responses back in that format, independent of which provider ultimately serves the request.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EncodeBatchResults added in v0.1.53

func EncodeBatchResults(results *core.BatchResultsResponse) ([]byte, error)

EncodeBatchResults renders canonical batch results as the Anthropic results JSONL stream. Successful items are converted from the chat shape to the Anthropic Messages shape; failed items carry the Anthropic error envelope; canceled/expired items map to their dedicated result types.

func EstimateChatInputTokens added in v0.1.53

func EstimateChatInputTokens(req *core.ChatRequest) int

EstimateChatInputTokens returns the same chars/4 heuristic for a canonical chat request. It seeds the stream converter's message_start usage, where the Anthropic contract expects input tokens before the upstream has reported any.

func EstimateInputTokens

func EstimateInputTokens(req *MessagesRequest) int

EstimateInputTokens returns a provider-agnostic heuristic estimate of the input token count for a Messages request (roughly characters / 4). It is an approximation, not a tokenizer-exact count.

func GatewayBatchID added in v0.1.53

func GatewayBatchID(messageBatchID string) string

GatewayBatchID maps an Anthropic msgbatch_ ID back to the gateway form.

func MessageBatchID added in v0.1.53

func MessageBatchID(gatewayID string) string

MessageBatchID renders a gateway batch ID in the Anthropic msgbatch_ form.

func NewStreamConverter

func NewStreamConverter(body io.ReadCloser, model string, inputTokensEstimate int) io.ReadCloser

NewStreamConverter wraps an OpenAI-style chat completion SSE stream and emits the equivalent Anthropic Messages SSE event sequence. The returned reader owns body and closes it on Close.

inputTokensEstimate seeds message_start's usage.input_tokens: the Anthropic contract reports input tokens at stream start, but the OpenAI upstream only delivers usage in the final chunk, so a heuristic estimate is the best available value there. The authoritative usage still arrives in message_delta, which SDK accumulators prefer.

func ToBatchRequest added in v0.1.53

func ToBatchRequest(req *BatchCreateRequest) (*core.BatchRequest, error)

ToBatchRequest translates an Anthropic Message Batches create body into the canonical batch request. Each item's Messages params are translated to a canonical chat request, so the batch routes to any provider with native batch support, not only Anthropic.

func ToChatRequest

func ToChatRequest(req *MessagesRequest) (*core.ChatRequest, error)

ToChatRequest translates an Anthropic Messages request into the canonical chat request. The translation is provider-agnostic: the resulting request runs through the standard chat-completions pipeline.

Types

type BatchCreateItem added in v0.1.53

type BatchCreateItem struct {
	CustomID string          `json:"custom_id"`
	Params   json.RawMessage `json:"params" swaggertype:"object"`
}

BatchCreateItem is one request of an Anthropic Message Batch. Params is a full Messages API request body.

type BatchCreateRequest added in v0.1.53

type BatchCreateRequest struct {
	Requests []BatchCreateItem `json:"requests"`
}

BatchCreateRequest is the Anthropic POST /v1/messages/batches body.

func DecodeBatchCreateRequest added in v0.1.53

func DecodeBatchCreateRequest(body []byte) (*BatchCreateRequest, error)

DecodeBatchCreateRequest parses an Anthropic Message Batches create body, rejecting trailing bytes with the same discipline as DecodeMessagesRequest.

type ContentBlock

type ContentBlock struct {
	Type string `json:"type"`
	// text / thinking
	Text     string `json:"text,omitempty"`
	Thinking string `json:"thinking,omitempty"`
	// image
	Source *Source `json:"source,omitempty"`
	// tool_use
	ID    string          `json:"id,omitempty"`
	Name  string          `json:"name,omitempty"`
	Input json.RawMessage `json:"input,omitempty" swaggertype:"object"`
	// tool_result
	ToolUseID string          `json:"tool_use_id,omitempty"`
	Content   json.RawMessage `json:"content,omitempty" swaggertype:"object"`
	IsError   bool            `json:"is_error,omitempty"`
}

ContentBlock is one element of an Anthropic message content array. The struct is a union; only the fields relevant to Type are populated.

type CountTokensResponse

type CountTokensResponse struct {
	InputTokens int `json:"input_tokens"`
}

CountTokensResponse is the Anthropic /v1/messages/count_tokens response body.

type DeletedMessageBatch added in v0.1.53

type DeletedMessageBatch struct {
	ID   string `json:"id"`
	Type string `json:"type"`
}

DeletedMessageBatch is the Anthropic DELETE /v1/messages/batches/{id} response body.

type ErrorObject

type ErrorObject struct {
	Type    string `json:"type"`
	Message string `json:"message"`
}

ErrorObject is the inner error detail of an Anthropic error envelope.

type ErrorResponse

type ErrorResponse struct {
	Type  string      `json:"type"`
	Error ErrorObject `json:"error"`
}

ErrorResponse is the Anthropic error envelope.

func ErrorFromGateway

func ErrorFromGateway(err *core.GatewayError) (int, ErrorResponse)

ErrorFromGateway converts a gateway error into an HTTP status code and the Anthropic error envelope. A nil error is reported as a generic api_error.

type Message

type Message struct {
	Role    string          `json:"role"`
	Content json.RawMessage `json:"content" swaggertype:"object"`
}

Message is a single Anthropic conversation message. Content is a string or an array of ContentBlock values.

type MessageBatch added in v0.1.53

type MessageBatch struct {
	ID                string                    `json:"id"`
	Type              string                    `json:"type"`
	ProcessingStatus  string                    `json:"processing_status"`
	RequestCounts     MessageBatchRequestCounts `json:"request_counts"`
	EndedAt           *string                   `json:"ended_at"`
	CreatedAt         string                    `json:"created_at"`
	ExpiresAt         string                    `json:"expires_at"`
	ArchivedAt        *string                   `json:"archived_at"`
	CancelInitiatedAt *string                   `json:"cancel_initiated_at"`
	ResultsURL        *string                   `json:"results_url"`
}

MessageBatch is the Anthropic message_batch object.

func FromBatchResponse added in v0.1.53

func FromBatchResponse(batch *core.BatchResponse) *MessageBatch

FromBatchResponse renders a canonical batch in the Anthropic message_batch shape.

type MessageBatchList added in v0.1.53

type MessageBatchList struct {
	Data    []MessageBatch `json:"data"`
	HasMore bool           `json:"has_more"`
	FirstID *string        `json:"first_id"`
	LastID  *string        `json:"last_id"`
}

MessageBatchList is the Anthropic GET /v1/messages/batches response body.

func FromBatchList added in v0.1.53

func FromBatchList(list *core.BatchListResponse) *MessageBatchList

FromBatchList renders a canonical batch list in the Anthropic list shape.

type MessageBatchRequestCounts added in v0.1.53

type MessageBatchRequestCounts struct {
	Processing int `json:"processing"`
	Succeeded  int `json:"succeeded"`
	Errored    int `json:"errored"`
	Canceled   int `json:"canceled"`
	Expired    int `json:"expired"`
}

MessageBatchRequestCounts tallies batch requests by status.

type MessagesRequest

type MessagesRequest struct {
	Model         string          `json:"model"`
	Messages      []Message       `json:"messages"`
	MaxTokens     int             `json:"max_tokens"`
	System        json.RawMessage `json:"system,omitempty" swaggertype:"object"`
	Metadata      *Metadata       `json:"metadata,omitempty"`
	StopSequences []string        `json:"stop_sequences,omitempty"`
	Stream        bool            `json:"stream,omitempty"`
	Temperature   *float64        `json:"temperature,omitempty"`
	TopP          *float64        `json:"top_p,omitempty"`
	TopK          *int            `json:"top_k,omitempty"`
	Tools         []Tool          `json:"tools,omitempty"`
	ToolChoice    *ToolChoice     `json:"tool_choice,omitempty"`
	Thinking      *Thinking       `json:"thinking,omitempty"`
}

MessagesRequest is the Anthropic Messages API request body. System and message content fields are polymorphic on the wire (string or array), so they are kept raw and decoded in request.go.

func DecodeMessagesRequest

func DecodeMessagesRequest(body []byte) (*MessagesRequest, error)

DecodeMessagesRequest parses an Anthropic Messages API request body.

type MessagesResponse

type MessagesResponse struct {
	ID           string                 `json:"id"`
	Type         string                 `json:"type"`
	Role         string                 `json:"role"`
	Model        string                 `json:"model"`
	Content      []ResponseContentBlock `json:"content"`
	StopReason   string                 `json:"stop_reason"`
	StopSequence *string                `json:"stop_sequence"`
	Usage        Usage                  `json:"usage"`
}

MessagesResponse is the Anthropic Messages API response body.

func FromChatResponse

func FromChatResponse(resp *core.ChatResponse) *MessagesResponse

FromChatResponse renders a canonical chat response in the Anthropic Messages response shape.

type Metadata

type Metadata struct {
	UserID string `json:"user_id,omitempty"`
}

Metadata carries the optional Anthropic request metadata object.

type ModelInfo added in v0.1.53

type ModelInfo struct {
	Type        string `json:"type"`
	ID          string `json:"id"`
	DisplayName string `json:"display_name"`
	CreatedAt   string `json:"created_at"`
}

ModelInfo is one model entry in the Anthropic models list.

type ModelsList added in v0.1.53

type ModelsList struct {
	Data    []ModelInfo `json:"data"`
	HasMore bool        `json:"has_more"`
	FirstID *string     `json:"first_id"`
	LastID  *string     `json:"last_id"`
}

ModelsList is the Anthropic /v1/models response body.

func FromModels added in v0.1.53

func FromModels(models []core.Model) *ModelsList

FromModels renders the catalog in the Anthropic models-list shape. The full catalog is returned in one page: has_more is always false, so SDK auto-pagination terminates after a single request.

type ResponseContentBlock

type ResponseContentBlock struct {
	Type     string          `json:"type"`
	Text     string          `json:"text,omitempty"`
	Thinking string          `json:"thinking,omitempty"`
	ID       string          `json:"id,omitempty"`
	Name     string          `json:"name,omitempty"`
	Input    json.RawMessage `json:"input,omitempty" swaggertype:"object"`
}

ResponseContentBlock is one element of an Anthropic response content array.

type Source

type Source struct {
	Type      string `json:"type"`
	MediaType string `json:"media_type,omitempty"`
	Data      string `json:"data,omitempty"`
	URL       string `json:"url,omitempty"`
}

Source describes an Anthropic image source (base64 inline data or a URL).

type Thinking

type Thinking struct {
	Type         string `json:"type"`
	BudgetTokens int    `json:"budget_tokens,omitempty"`
}

Thinking is the Anthropic extended-thinking configuration.

type Tool

type Tool struct {
	Type        string          `json:"type,omitempty"`
	Name        string          `json:"name"`
	Description string          `json:"description,omitempty"`
	InputSchema json.RawMessage `json:"input_schema,omitempty" swaggertype:"object"`
}

Tool is an Anthropic tool definition. A custom tool has no Type (or Type "custom"); a server/built-in tool (web search, code execution, …) carries a versioned Type and is rejected during translation — see convertTools.

type ToolChoice

type ToolChoice struct {
	Type                   string `json:"type"`
	Name                   string `json:"name,omitempty"`
	DisableParallelToolUse *bool  `json:"disable_parallel_tool_use,omitempty"`
}

ToolChoice constrains how the model selects tools.

type Usage

type Usage struct {
	InputTokens              int `json:"input_tokens"`
	OutputTokens             int `json:"output_tokens"`
	CacheCreationInputTokens int `json:"cache_creation_input_tokens,omitempty"`
	CacheReadInputTokens     int `json:"cache_read_input_tokens,omitempty"`
}

Usage reports Anthropic-style token usage.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL