translate

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2026 License: MIT Imports: 8 Imported by: 0

README

llm-translate

Zero-dependency Go library for bidirectional protocol translation between the Anthropic Messages API, OpenAI Chat Completions, and the OpenAI Responses API.

Features

  • Anthropic ↔ OpenAI Request & Response: Full fidelity translation of messages, tool definitions, tool results, thinking/reasoning blocks, system prompts, and multi-part vision content.
  • SSE Stream Translation: Real-time translation between OpenAI chunk deltas and Anthropic SSE events (message_start, content_block_start, content_block_delta, message_delta, message_stop).
  • OpenAI Responses ↔ Chat: Bidirectional translation for newer OpenAI Responses API backends to standard Chat completions.
  • Pure Standard Library: Zero CGO, zero external dependencies.

Installation

go get github.com/xibodev/llm-translate

Quick Start

Convert Anthropic Messages Request to OpenAI
import "github.com/xibodev/llm-translate"

openaiMessages := translate.AnthropicMessagesToOpenAI(req.Messages, req.System)
tools := translate.AnthropicToolsToOpenAI(req.Tools)
Stream OpenAI Chunks as Anthropic SSE
translate.OpenAIStreamToAnthropicSSE(chunksIter, "claude-3-5-sonnet", func(sseEvent string) {
    w.Write([]byte(sseEvent))
    w.(http.Flusher).Flush()
})

License

MIT

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

Constants

This section is empty.

Variables

This section is empty.

Functions

func AnthropicMessagesToOpenAI

func AnthropicMessagesToOpenAI(messages []any, system any) []map[string]any

AnthropicMessagesToOpenAI converts Anthropic messages + system into OpenAI messages.

func AnthropicRequestToOpenAI

func AnthropicRequestToOpenAI(payload map[string]any) ([]map[string]any, map[string]any, []string)

AnthropicRequestToOpenAI strictly converts the Messages core profile. The returned paths name every value that an OpenAI Chat target would lose.

func AnthropicResponseToOpenAI

func AnthropicResponseToOpenAI(response map[string]any, model string) map[string]any

AnthropicResponseToOpenAI converts a non-streaming Anthropic Message to an OpenAI completion.

func AnthropicSSEToOpenAIChunks

func AnthropicSSEToOpenAIChunks(lines func() (string, bool), model string, emit func(string))

AnthropicSSEToOpenAIChunks translates Anthropic SSE data lines into OpenAI chat.completion.chunk JSON strings, invoking emit for each.

func AnthropicStopReasonToOpenAI

func AnthropicStopReasonToOpenAI(reason any) string

AnthropicStopReasonToOpenAI maps an Anthropic stop_reason to an OpenAI finish_reason.

func AnthropicToolChoiceToOpenAI

func AnthropicToolChoiceToOpenAI(choice map[string]any) any

AnthropicToolChoiceToOpenAI converts Anthropic tool_choice to OpenAI's.

func AnthropicToolsToOpenAI

func AnthropicToolsToOpenAI(tools []any) []any

AnthropicToolsToOpenAI converts Anthropic tools to OpenAI function tools.

func ChatResponseToResponses

func ChatResponseToResponses(model string, chat map[string]any) map[string]any

ChatResponseToResponses converts the gateway's internal Chat Completions result back into the public Responses API envelope.

func ChatResponseToResponsesWithRequest

func ChatResponseToResponsesWithRequest(
	model string, chat map[string]any, request map[string]any,
) map[string]any

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 FailedResponseEnvelope(
	model, id, code, message string, request map[string]any,
) map[string]any

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

func OpenAIFinishReasonToAnthropic(reason any) string

OpenAIFinishReasonToAnthropic maps an OpenAI finish_reason to Anthropic stop_reason.

func OpenAIMessagesToAnthropic

func OpenAIMessagesToAnthropic(messages []map[string]any) (string, []map[string]any)

OpenAIMessagesToAnthropic splits an OpenAI message list into Anthropic (system, messages).

func OpenAIResponseToAnthropic

func OpenAIResponseToAnthropic(response map[string]any, model string) map[string]any

OpenAIResponseToAnthropic converts a non-streaming OpenAI completion to an Anthropic Message.

func OpenAIStreamToAnthropicSSE

func OpenAIStreamToAnthropicSSE(chunks func() (string, bool), model string, emit func(string))

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

func OpenAIToolsToAnthropic(tools []any) []any

OpenAIToolsToAnthropic converts OpenAI tools to Anthropic tool shape.

func PreferredEndpoint

func PreferredEndpoint(supportedEndpoints []string) string

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

func RejectMaterialLoss(report Report) error

RejectMaterialLoss returns an error containing every material loss in the report.

func ResponsesRequestToChat

func ResponsesRequestToChat(
	payload map[string]any,
) ([]map[string]any, map[string]any, error)

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

func ResponsesToChat(model string, resp map[string]any) map[string]any

ResponsesToChat converts a Responses API object into a chat.completion.

func ResponsesToChatChunks

func ResponsesToChatChunks(model string, resp map[string]any) []string

ResponsesToChatChunks renders a (buffered) Responses reply as a small sequence of chat.completion.chunk payloads for the streaming code path.

Types

type AnthropicMessages added in v0.2.0

type AnthropicMessages struct {
	System   string
	Messages []map[string]any
}

AnthropicMessages is the two-part request value returned by Anthropic conversions.

type ConversionResult added in v0.2.0

type ConversionResult[T any] struct {
	Value  T      `json:"value"`
	Report Report `json:"report"`
}

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.

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.

const (
	LossUnsupported  LossClass = "unsupported"
	LossDropped      LossClass = "dropped"
	LossApproximated LossClass = "approximated"
	LossRenamed      LossClass = "renamed"
)

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

type OpenAIChatRequest struct {
	Messages []map[string]any
	Keywords map[string]any
}

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.

func NewReport added in v0.2.0

func NewReport(losses ...Loss) Report

NewReport normalizes ordering and removes duplicate losses.

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.

func (Report) HasMaterialLoss added in v0.2.0

func (r Report) HasMaterialLoss() bool

HasMaterialLoss reports whether conversion changed or omitted material semantics.

Jump to

Keyboard shortcuts

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