Documentation
¶
Overview ¶
Package translate round-trips between the Anthropic Messages API and the OpenAI Chat Completions schema. The gateway speaks OpenAI natively; this is the single translator that lets Claude Code and other Anthropic clients talk to it, and lets the native Anthropic backend be called from OpenAI-shaped internals.
Faithful port of llmgw.api.anthropic_translate. JSON objects are modeled as map[string]any / []any to mirror the Python dict handling.
Index ¶
- Variables
- func AnthropicMessagesToOpenAI(messages []any, system any) []map[string]any
- func AnthropicRequestToOpenAI(payload map[string]any) ([]map[string]any, map[string]any, []string)
- func AnthropicResponseToOpenAI(response map[string]any, model string) map[string]any
- func AnthropicSSEToOpenAIChunks(lines func() (string, bool), model string, emit func(string))
- func AnthropicStopReasonToOpenAI(reason any) string
- func AnthropicToolChoiceToOpenAI(choice map[string]any) any
- func AnthropicToolsToOpenAI(tools []any) []any
- func ChatResponseToResponses(model string, chat map[string]any) map[string]any
- func ChatResponseToResponsesWithRequest(model string, chat map[string]any, request map[string]any) map[string]any
- func ChatToResponses(model string, messages []map[string]any, kw map[string]any, stream bool) map[string]any
- func FailedResponseEnvelope(model, id, code, message string, request map[string]any) map[string]any
- func NewResponseEnvelope(model, id, status string, output []any, request map[string]any) map[string]any
- func OpenAIFinishReasonToAnthropic(reason any) string
- func OpenAIMessagesToAnthropic(messages []map[string]any) (string, []map[string]any)
- func OpenAIResponseToAnthropic(response map[string]any, model string) map[string]any
- func OpenAIStreamToAnthropicSSE(chunks func() (string, bool), model string, emit func(string))
- func OpenAIToolsToAnthropic(tools []any) []any
- func PreferredEndpoint(supportedEndpoints []string) string
- func RejectMaterialLoss(report Report) error
- func ResponsesRequestToChat(payload map[string]any) ([]map[string]any, map[string]any, error)
- func ResponsesToChat(model string, resp map[string]any) map[string]any
- func ResponsesToChatChunks(model string, resp map[string]any) []string
- type AnthropicMessages
- type ConversionResult
- func AnthropicRequestToOpenAIWithReport(payload map[string]any) ConversionResult[OpenAIChatRequest]
- func AnthropicResponseToOpenAIWithReport(response map[string]any, model string) ConversionResult[map[string]any]
- func ChatResponseToResponsesWithReport(model string, chat map[string]any) ConversionResult[map[string]any]
- func ChatResponseToResponsesWithRequestAndReport(model string, chat map[string]any, request map[string]any) ConversionResult[map[string]any]
- func ChatToResponsesWithReport(model string, messages []map[string]any, kw map[string]any, stream bool) ConversionResult[map[string]any]
- func OpenAIMessagesToAnthropicWithReport(messages []map[string]any) ConversionResult[AnthropicMessages]
- func OpenAIResponseToAnthropicWithReport(response map[string]any, model string) ConversionResult[map[string]any]
- func ResponsesRequestToChatWithReport(payload map[string]any) (ConversionResult[OpenAIChatRequest], error)
- func ResponsesToChatChunksWithReport(model string, response map[string]any) ConversionResult[[]string]
- func ResponsesToChatWithReport(model string, response map[string]any) ConversionResult[map[string]any]
- type Loss
- type LossClass
- type LossSeverity
- type MaterialLossError
- type OpenAIChatRequest
- type Report
- type StreamError
- type StreamOptions
- type StreamReport
- type Usage
Constants ¶
This section is empty.
Variables ¶
var ErrStreamTruncated = errors.New("Anthropic stream ended without message_stop")
ErrStreamTruncated is the error of a source that ended without message_stop and without an error event, such as a dropped connection.
Functions ¶
func AnthropicMessagesToOpenAI ¶
AnthropicMessagesToOpenAI converts Anthropic messages + system into OpenAI messages.
func AnthropicRequestToOpenAI ¶
AnthropicRequestToOpenAI strictly converts the Messages core profile. The returned paths name every value that an OpenAI Chat target would lose.
func AnthropicResponseToOpenAI ¶
AnthropicResponseToOpenAI converts a non-streaming Anthropic Message to an OpenAI completion.
func AnthropicSSEToOpenAIChunks ¶
AnthropicSSEToOpenAIChunks translates Anthropic SSE data lines into OpenAI chat.completion.chunk JSON strings, invoking emit for each. It emits no usage and ends every stream with a finish chunk, even one that failed or was cut short; AnthropicSSEToOpenAIChunksWithOptions reports both.
func AnthropicStopReasonToOpenAI ¶
AnthropicStopReasonToOpenAI maps an Anthropic stop_reason to an OpenAI finish_reason.
func AnthropicToolChoiceToOpenAI ¶
AnthropicToolChoiceToOpenAI converts Anthropic tool_choice to OpenAI's.
func AnthropicToolsToOpenAI ¶
AnthropicToolsToOpenAI converts Anthropic tools to OpenAI function tools.
func ChatResponseToResponses ¶
ChatResponseToResponses converts the gateway's internal Chat Completions result back into the public Responses API envelope.
func ChatToResponses ¶
func ChatToResponses(model string, messages []map[string]any, kw map[string]any, stream bool) map[string]any
ChatToResponses converts a Chat Completions request body into a Responses API request body.
func FailedResponseEnvelope ¶
func NewResponseEnvelope ¶
func NewResponseEnvelope( model, id, status string, output []any, request map[string]any, ) map[string]any
NewResponseEnvelope creates the schema-complete Response shape used whenever the gateway adapts a Chat-only backend or synthesizes a terminal failure.
func OpenAIFinishReasonToAnthropic ¶
OpenAIFinishReasonToAnthropic maps an OpenAI finish_reason to Anthropic stop_reason.
func OpenAIMessagesToAnthropic ¶
OpenAIMessagesToAnthropic splits an OpenAI message list into Anthropic (system, messages). cache_control on message content parts is carried to the Anthropic blocks; cache_control on system parts needs OpenAIMessagesToAnthropicWithReport, because the system returned here is a plain string.
func OpenAIResponseToAnthropic ¶
OpenAIResponseToAnthropic converts a non-streaming OpenAI completion to an Anthropic Message.
func OpenAIStreamToAnthropicSSE ¶
OpenAIStreamToAnthropicSSE translates OpenAI SSE chunk payloads (JSON strings, data: prefix already stripped) into Anthropic SSE event blocks, invoking emit for each output event.
func OpenAIToolsToAnthropic ¶
OpenAIToolsToAnthropic converts OpenAI tools to Anthropic tool shape.
func PreferredEndpoint ¶
PreferredEndpoint decides which OpenAI-family endpoint a model should use given its published supported_surfaces. Returns "responses" only when the model advertises /responses but NOT /chat/completions; otherwise "chat" (the safe default, including when the list is empty/unknown).
func RejectMaterialLoss ¶ added in v0.2.0
RejectMaterialLoss returns an error containing every material loss in the report.
func ResponsesRequestToChat ¶
ResponsesRequestToChat converts supported Responses input/history/tools into the gateway's internal Chat representation. Built-in Responses-only tools fail explicitly instead of being silently flattened.
func ResponsesToChat ¶
ResponsesToChat converts a Responses API object into a chat.completion.
Types ¶
type AnthropicMessages ¶ added in v0.2.0
type AnthropicMessages struct {
System string
Messages []map[string]any
// SystemBlocks is set when a system or developer text part carries
// cache_control. It holds the System text as Anthropic text blocks split
// at the breakpoints, each carrying its cache_control. Send it as the
// request's system value instead of System, or the breakpoints are lost.
SystemBlocks []any `json:",omitempty"`
}
AnthropicMessages is the two-part request value returned by Anthropic conversions.
type ConversionResult ¶ added in v0.2.0
ConversionResult couples an existing conversion value to its compatibility report.
func AnthropicRequestToOpenAIWithReport ¶ added in v0.2.0
func AnthropicRequestToOpenAIWithReport(payload map[string]any) ConversionResult[OpenAIChatRequest]
AnthropicRequestToOpenAIWithReport delegates to AnthropicRequestToOpenAI and gives its incompatible paths structured material-loss semantics.
func AnthropicResponseToOpenAIWithReport ¶ added in v0.2.0
func AnthropicResponseToOpenAIWithReport(response map[string]any, model string) ConversionResult[map[string]any]
AnthropicResponseToOpenAIWithReport converts an Anthropic response with fidelity findings.
func ChatResponseToResponsesWithReport ¶ added in v0.2.0
func ChatResponseToResponsesWithReport(model string, chat map[string]any) ConversionResult[map[string]any]
ChatResponseToResponsesWithReport converts a Chat response with fidelity findings.
func ChatResponseToResponsesWithRequestAndReport ¶ added in v0.2.0
func ChatResponseToResponsesWithRequestAndReport(model string, chat map[string]any, request map[string]any) ConversionResult[map[string]any]
ChatResponseToResponsesWithRequestAndReport also uses request fields when constructing the Responses envelope.
func ChatToResponsesWithReport ¶ added in v0.2.0
func ChatToResponsesWithReport(model string, messages []map[string]any, kw map[string]any, stream bool) ConversionResult[map[string]any]
ChatToResponsesWithReport converts a Chat request and reports known fallback synthesis.
func OpenAIMessagesToAnthropicWithReport ¶ added in v0.2.0
func OpenAIMessagesToAnthropicWithReport(messages []map[string]any) ConversionResult[AnthropicMessages]
OpenAIMessagesToAnthropicWithReport converts messages and reports known normalizations performed by the existing converter. cache_control on text parts is carried, including on system parts through SystemBlocks; vendor fields Anthropic cannot represent are reported at their paths.
func OpenAIResponseToAnthropicWithReport ¶ added in v0.2.0
func OpenAIResponseToAnthropicWithReport(response map[string]any, model string) ConversionResult[map[string]any]
OpenAIResponseToAnthropicWithReport converts a Chat response with fidelity findings.
func ResponsesRequestToChatWithReport ¶ added in v0.2.0
func ResponsesRequestToChatWithReport(payload map[string]any) (ConversionResult[OpenAIChatRequest], error)
ResponsesRequestToChatWithReport preserves existing validation errors and reports unsupported top-level fields as material compatibility loss.
func ResponsesToChatChunksWithReport ¶ added in v0.2.0
func ResponsesToChatChunksWithReport(model string, response map[string]any) ConversionResult[[]string]
ResponsesToChatChunksWithReport reports that a complete response is rendered as buffered chunks rather than preserving original event boundaries.
func ResponsesToChatWithReport ¶ added in v0.2.0
func ResponsesToChatWithReport(model string, response map[string]any) ConversionResult[map[string]any]
ResponsesToChatWithReport converts a Responses object with fidelity findings.
func (ConversionResult[T]) RejectMaterialLoss ¶ added in v0.2.0
func (r ConversionResult[T]) RejectMaterialLoss() error
RejectMaterialLoss returns an error when this result contains material loss.
type Loss ¶ added in v0.2.0
type Loss struct {
Path string `json:"path"`
Class LossClass `json:"class"`
Severity LossSeverity `json:"severity"`
Detail string `json:"detail"`
}
Loss is one deterministic, machine-readable compatibility finding.
type LossClass ¶ added in v0.2.0
type LossClass string
LossClass describes how a source value differs after conversion.
type LossSeverity ¶ added in v0.2.0
type LossSeverity string
LossSeverity distinguishes fidelity failures from useful compatibility notes.
const ( LossMaterial LossSeverity = "material" LossAdvisory LossSeverity = "advisory" )
type MaterialLossError ¶ added in v0.2.0
type MaterialLossError struct {
Losses []Loss
}
MaterialLossError contains the material subset of a rejected report.
func (*MaterialLossError) Error ¶ added in v0.2.0
func (e *MaterialLossError) Error() string
type OpenAIChatRequest ¶ added in v0.2.0
OpenAIChatRequest is the two-part request value returned by Chat conversions.
type Report ¶ added in v0.2.0
type Report struct {
Losses []Loss `json:"losses,omitempty"`
}
Report describes all known compatibility losses for one conversion. Losses are sorted by path, severity, class, then detail.
func AnthropicSSEToOpenAIChunksWithReport ¶ added in v0.2.0
func AnthropicSSEToOpenAIChunksWithReport(lines func() (string, bool), model string, emit func(string)) Report
AnthropicSSEToOpenAIChunksWithReport delegates stream conversion and reports usage fields that the existing Chat chunk adapter does not emit, and the thinking blocks it drops.
func OpenAIStreamToAnthropicSSEWithReport ¶ added in v0.2.0
func OpenAIStreamToAnthropicSSEWithReport(chunks func() (string, bool), model string, emit func(string)) Report
OpenAIStreamToAnthropicSSEWithReport delegates stream conversion and reports the token estimate used when chunks do not carry usage, and the vendor fields of deltas that Anthropic events cannot carry.
func (Report) HasMaterialLoss ¶ added in v0.2.0
HasMaterialLoss reports whether conversion changed or omitted material semantics.
type StreamError ¶ added in v0.4.0
type StreamError struct {
Type string // Anthropic's error type, such as overloaded_error
Message string
}
StreamError is an error event received from an Anthropic stream, such as an overloaded_error after the response began.
func (*StreamError) Error ¶ added in v0.4.0
func (e *StreamError) Error() string
type StreamOptions ¶ added in v0.4.0
type StreamOptions struct {
// IncludeUsage emits what OpenAI sends for stream_options.include_usage:
// after the finish chunk, a chunk with empty choices and the usage of the
// whole request, and "usage": null on every other chunk. The usage chunk
// is sent only for a completed stream whose source reported usage, so it
// never carries a partial or invented count.
IncludeUsage bool
}
StreamOptions selects optional output of AnthropicSSEToOpenAIChunksWithOptions.
type StreamReport ¶ added in v0.4.0
type StreamReport struct {
// Usage holds the latest count of each kind the source reported, also
// for a stream that failed, and is zero when the source reported none.
Usage Usage
// Completed is true when message_stop arrived and no error event did.
Completed bool
// Err is nil when Completed. Otherwise it is the *StreamError of the
// first error event, or ErrStreamTruncated.
Err error
}
StreamReport tells how a translated stream ended.
func AnthropicSSEToOpenAIChunksWithOptions ¶ added in v0.4.0
func AnthropicSSEToOpenAIChunksWithOptions(lines func() (string, bool), model string, emit func(string), opts StreamOptions) *StreamReport
AnthropicSSEToOpenAIChunksWithOptions translates like AnthropicSSEToOpenAIChunks and, once lines is exhausted, returns a report that is never nil.
Without options, a completed stream gets exactly the chunks AnthropicSSEToOpenAIChunks emits; StreamOptions describes what IncludeUsage adds. Any other stream ends where its source did, without a finish chunk, so a failed or truncated answer cannot pass for a complete one. Its chunks all come from source events: when an error arrives first, nothing has been emitted and the caller can still respond with an error status.
type Usage ¶ added in v0.4.0
type Usage struct {
InputTokens int `json:"input_tokens"`
CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
CacheReadInputTokens int `json:"cache_read_input_tokens"`
OutputTokens int `json:"output_tokens"`
}
Usage holds the token counts an Anthropic stream reported. Anthropic counts cache writes and cache reads apart from InputTokens, so the Chat prompt_tokens is the sum of all three.
func (Usage) PromptTokens ¶ added in v0.4.0
PromptTokens returns the Chat prompt_tokens, which also counts the input read from or written to the cache.
func (Usage) TotalTokens ¶ added in v0.4.0
TotalTokens returns the Chat total_tokens.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package wire holds typed request, response and stream-chunk structs for the OpenAI Chat Completions, OpenAI Responses and Anthropic Messages surfaces.
|
Package wire holds typed request, response and stream-chunk structs for the OpenAI Chat Completions, OpenAI Responses and Anthropic Messages surfaces. |