translate

package
v0.7.44 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 10 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const MaxCollectedResponseBytes = 64 << 20

MaxCollectedResponseBytes bounds a non-stream native response assembled from upstream SSE. The terminal response object repeats every output item, so the cap covers the whole stream, not one event.

View Source
const MaxNativeRequestBytes = 64 << 20

MaxNativeRequestBytes bounds a /v1/responses body. Requests carry whole conversations with inline images, so the cap is generous; it exists to stop an unbounded read, not to police normal traffic.

Variables

View Source
var ErrResponsesIncomplete = errors.New("upstream responses stream ended before a terminal event")

ErrResponsesIncomplete means the upstream stream ended before any terminal event. Nothing was relayed yet, so callers may treat it as retryable.

Functions

func ContentSessionSeed added in v0.3.0

func ContentSessionSeed(req ChatRequest) string

ContentSessionSeed builds a stable conversation fingerprint from fields that stay constant across turns: model, tool definitions, the leading system/developer prefix, and the first user message. Later turns append assistant/user messages and must not change the seed, or prompt-cache affinity would break.

The fingerprint is a hash of role-tagged structured fields, including image identifiers on the first user message. An empty result means there is no user anchor; callers should leave the request on ordinary pool routing.

func ContentToString

func ContentToString(content any) string

func DecodeCustomToolName added in v0.6.0

func DecodeCustomToolName(upstreamName string) (namespace, name string, ok bool)

DecodeCustomToolName reverses EncodeCustomToolName. It returns ok=false for ordinary function tools.

func EmptyMessageIndexes added in v0.4.1

func EmptyMessageIndexes(messages []ChatMessage) []int

func EncodeCustomToolName added in v0.6.0

func EncodeCustomToolName(namespace, name string) string

EncodeCustomToolName maps a Codex custom/freeform tool onto an upstream function name. The marker keeps the round trip reversible without changing the namespace/name identity carried by CustomToolCall.

func HardenToolSchema added in v0.7.35

func HardenToolSchema(raw json.RawMessage) json.RawMessage

HardenToolSchema coerces those keywords recursively and is idempotent: a schema that is already valid is unchanged. A schema that is not an object is returned as-is. Providers that stringify parameters before this step still call it on the raw schema text.

func MessageRoles added in v0.4.1

func MessageRoles(messages []ChatMessage) []string

func NormalizeOpenAITools added in v0.5.6

func NormalizeOpenAITools(raw json.RawMessage) (json.RawMessage, error)

NormalizeOpenAITools expands Codex/Desktop namespace wrappers into plain OpenAI function tools and drops hosted shells such as mcp / web_search. Nested tools may be Responses-flat or Chat Completions shaped. Short nested names are qualified as namespace__name; already-qualified mcp__* names stay unchanged. This does not apply Devin's mcp__ upstream aliasing.

func PrefixSessionSeed added in v0.7.34

func PrefixSessionSeed(req ChatRequest) string

PrefixSessionSeed is the cache-affine part of ContentSessionSeed: model, tools and the leading system/developer prefix only. It deliberately excludes the first user message so workbuddy2api-hub-style sharding does not scatter one (key, model, system, tools) tuple across the whole account pool.

func ResponseToolNames added in v0.6.7

func ResponseToolNames(raw []byte) map[string]ResponseToolName

ResponseToolNames records namespace tool identities declared on a Responses body. The native path keeps those tools intact upstream, but the reply still has to restore a flattened name when one was produced. A body the compatibility translator cannot carry returns no names rather than an error.

func RestoreResponseToolNames added in v0.6.0

func RestoreResponseToolNames(value any, names map[string]ResponseToolName)

RestoreResponseToolNames only visits protocol containers, never user content or tool arguments. The same operation serves JSON responses and SSE events.

func ValidateChatRequest added in v0.2.42

func ValidateChatRequest(request *ChatRequest) error

Types

type AnthropicMessage added in v0.2.42

type AnthropicMessage struct {
	Role    string          `json:"role"`
	Content json.RawMessage `json:"content"`
}

type AnthropicMessagesRequest added in v0.2.42

type AnthropicMessagesRequest struct {
	Model         string             `json:"model"`
	Messages      []AnthropicMessage `json:"messages"`
	System        json.RawMessage    `json:"system,omitempty"`
	MaxTokens     json.RawMessage    `json:"max_tokens"`
	Stream        bool               `json:"stream"`
	Tools         json.RawMessage    `json:"tools,omitempty"`
	ToolChoice    json.RawMessage    `json:"tool_choice,omitempty"`
	Thinking      json.RawMessage    `json:"thinking,omitempty"`
	Temperature   json.RawMessage    `json:"temperature,omitempty"`
	TopP          json.RawMessage    `json:"top_p,omitempty"`
	StopSequences json.RawMessage    `json:"stop_sequences,omitempty"`
	OutputConfig  json.RawMessage    `json:"output_config,omitempty"`
}

AnthropicMessagesRequest is the supported subset of Anthropic's Messages API.

type ChatMessage

type ChatMessage struct {
	Role              string          `json:"role"`
	Content           any             `json:"content"`
	Name              string          `json:"name,omitempty"`
	ToolCallID        string          `json:"tool_call_id,omitempty"`
	ToolCalls         json.RawMessage `json:"tool_calls,omitempty"`
	ToolResultIsError bool            `json:"tool_result_is_error,omitempty"`
	ToolResultImages  []any           `json:"tool_result_images,omitempty"`
	ReasoningContent  string          `json:"reasoning_content,omitempty"`
}

type ChatRequest

type ChatRequest struct {
	Protocol              string          `json:"-"`
	AnthropicServerTools  []string        `json:"-"`
	Model                 string          `json:"model"`
	Messages              []ChatMessage   `json:"messages"`
	Stream                bool            `json:"stream"`
	MaxTokens             json.RawMessage `json:"max_tokens"`
	MaxCompletionTokens   json.RawMessage `json:"max_completion_tokens,omitempty"`
	Temperature           json.RawMessage `json:"temperature"`
	TopP                  json.RawMessage `json:"top_p,omitempty"`
	Stop                  json.RawMessage `json:"stop,omitempty"`
	ParallelToolCalls     *bool           `json:"parallel_tool_calls,omitempty"`
	ResponseFormat        json.RawMessage `json:"response_format,omitempty"`
	Tools                 json.RawMessage `json:"tools,omitempty"`
	ToolChoice            json.RawMessage `json:"tool_choice,omitempty"`
	IsReasoning           *bool           `json:"is_reasoning,omitempty"`
	EnableThinking        *bool           `json:"enable_thinking,omitempty"`
	EnableReasoning       *bool           `json:"enable_reasoning,omitempty"`
	Thinking              json.RawMessage `json:"thinking,omitempty"`
	ReasoningEffort       json.RawMessage `json:"reasoning_effort,omitempty"`
	ReasoningBudgetTokens json.RawMessage `json:"reasoning_budget_tokens,omitempty"`
	ContextLength         json.RawMessage `json:"context_length,omitempty"`
	MaxInputTokens        json.RawMessage `json:"max_input_tokens,omitempty"`
	IsMaxMode             *bool           `json:"is_max_mode,omitempty"`
}

func DropSystemMessages added in v0.2.12

func DropSystemMessages(req ChatRequest) ChatRequest

DropSystemMessages removes caller system/developer messages from a chat request. Provider-native upstreams with content screening reject many third-party system prompts, so accounts can opt to strip them before send.

func TranslateAnthropicMessages added in v0.2.42

func TranslateAnthropicMessages(request AnthropicMessagesRequest) (ChatRequest, error)

func TranslateResponses added in v0.2.42

func TranslateResponses(request ResponsesRequest) (ChatRequest, error)

TranslateResponses converts a Responses request into the shared chat form. Callers that relay a Responses reply must use TranslateResponsesRequest so they can restore namespaced tool names.

type CollectedResponse added in v0.6.7

type CollectedResponse struct {
	// Response is the terminal event's response object, verbatim: every
	// output item keeps its id, type, and members.
	Response     json.RawMessage
	FinishReason string
	InputTokens  *int
	OutputTokens *int
	CachedTokens *int
}

CollectedResponse is a non-stream Responses result assembled from SSE.

func CollectResponses added in v0.6.7

func CollectResponses(body io.Reader) (CollectedResponse, error)

CollectResponses reads an upstream Responses SSE body to its terminal event and returns the complete response object. It is the non-stream twin of the gateway's native relay and shares ParseResponsesEvent with it.

type NativeResponsesRequest added in v0.6.7

type NativeResponsesRequest struct {
	// contains filtered or unexported fields
}

NativeResponsesRequest is a complete, validated OpenAI Responses request as the client sent it. It owns its bytes and is logically read-only: every accessor returns data derived from, or copied out of, the original body, so per-attempt rewrites (model mapping, reasoning clamp, prompt policy) can never leak into a later failover attempt.

It is deliberately not a ChatRequest. The compatibility path derives one on demand through Compat; the native path hands the original fields to an adapter that speaks Responses upstream.

func ParseNativeResponses added in v0.6.7

func ParseNativeResponses(body []byte) (*NativeResponsesRequest, error)

ParseNativeResponses validates a Responses body without flattening it. It rejects what no path could serve (non-object bodies, trailing JSON values, a missing model or input, and server-side conversation state) and keeps every other top-level member, including ones this package does not know.

func (*NativeResponsesRequest) Body added in v0.6.7

func (r *NativeResponsesRequest) Body() []byte

Body returns the original request bytes. Callers must not retain and mutate the slice; Fields is the mutable per-attempt copy.

func (*NativeResponsesRequest) Compat added in v0.6.7

Compat derives the shared chat form for adapters without native Responses support. It may fail for input the chat form cannot carry; that failure is a statement about the compatibility path only, never about the request.

func (*NativeResponsesRequest) Fields added in v0.6.7

func (r *NativeResponsesRequest) Fields() map[string]json.RawMessage

Fields returns a private copy of the top-level members for one attempt. The map and every value slice are fresh, so the caller may rewrite them freely.

func (*NativeResponsesRequest) Model added in v0.6.7

func (r *NativeResponsesRequest) Model() string

Model is the client's model id, including any provider prefix.

func (*NativeResponsesRequest) RequestedReasoningEffort added in v0.6.7

func (r *NativeResponsesRequest) RequestedReasoningEffort() string

RequestedReasoningEffort is the client's reasoning.effort, empty when absent.

func (*NativeResponsesRequest) SessionSeed added in v0.6.7

func (r *NativeResponsesRequest) SessionSeed() string

SessionSeed is the sticky-routing anchor used when the request cannot be expressed in the chat form (the chat form's ContentSessionSeed is preferred whenever it exists, so accepted requests keep their existing affinity). It hashes only members that stay fixed across turns — model, instructions, tools, and the first user item — so appending turns never moves the seed. It is empty when there is no user item to anchor on.

func (*NativeResponsesRequest) Stream added in v0.6.7

func (r *NativeResponsesRequest) Stream() bool

Stream is the client's requested output mode, independent of how the upstream transports the response.

type RectifyResult added in v0.7.34

type RectifyResult struct {
	Applied                       bool `json:"applied"`
	RemovedThinkingBlocks         int  `json:"removed_thinking_blocks,omitempty"`
	RemovedRedactedThinkingBlocks int  `json:"removed_redacted_thinking_blocks,omitempty"`
	RemovedSignatureFields        int  `json:"removed_signature_fields,omitempty"`
	RemovedTopLevelThinking       bool `json:"removed_top_level_thinking,omitempty"`
}

RectifyResult mirrors cc-switch's thinking rectifier counters. The gateway only ever removes fields that OpenAI-compatible upstreams cannot validate; it never invents signatures or rewrites model output.

func RectifyAnthropicRequest added in v0.7.34

func RectifyAnthropicRequest(body []byte) ([]byte, RectifyResult, error)

RectifyAnthropicRequest applies the minimal cc-switch cleanup to a decoded Anthropic Messages body. Historical thinking blocks carry signatures that belong to a different provider; replaying them upstream causes 400 errors or visible <thinking> scaffolding in clients. Plain text, tool calls and tool results are preserved byte-for-byte where possible.

type ResponseToolName added in v0.6.0

type ResponseToolName struct {
	Namespace string
	Name      string
}

ResponseToolName is request-local metadata; it must never reach the provider.

type ResponsesEvent added in v0.6.7

type ResponsesEvent struct {
	Type string
	// Terminal marks response.completed / response.incomplete /
	// response.failed and bare error events.
	Terminal bool
	// FinishReason is "stop", "length" (incomplete), or "error".
	FinishReason string
	// Response is the full response object carried by a terminal success
	// event, verbatim.
	Response json.RawMessage
	// Usage is present only when the terminal event reported it.
	InputTokens  *int
	OutputTokens *int
	CachedTokens *int
	// FirstToken marks an output delta (first-token timing).
	FirstToken bool
}

ResponsesEvent is the accounting view of one OpenAI Responses SSE event. The stream relay and the non-stream collector both read events through it, so "what counts as terminal" and "where usage lives" are decided once.

func ParseResponsesEvent added in v0.6.7

func ParseResponsesEvent(data string) (ResponsesEvent, bool)

type ResponsesRequest added in v0.2.42

type ResponsesRequest struct {
	Model             string          `json:"model"`
	Input             json.RawMessage `json:"input"`
	Instructions      json.RawMessage `json:"instructions,omitempty"`
	MaxOutputTokens   json.RawMessage `json:"max_output_tokens,omitempty"`
	Stream            bool            `json:"stream"`
	Tools             json.RawMessage `json:"tools,omitempty"`
	ToolChoice        json.RawMessage `json:"tool_choice,omitempty"`
	Reasoning         json.RawMessage `json:"reasoning,omitempty"`
	TopP              json.RawMessage `json:"top_p,omitempty"`
	ParallelToolCalls *bool           `json:"parallel_tool_calls,omitempty"`
	Text              json.RawMessage `json:"text,omitempty"`
	PreviousID        string          `json:"previous_response_id,omitempty"`
	Conversation      json.RawMessage `json:"conversation,omitempty"`
}

ResponsesRequest is the supported stateless subset of OpenAI's Responses API.

type ResponsesStreamFailure added in v0.6.7

type ResponsesStreamFailure struct {
	Body string
}

ResponsesStreamFailure is a terminal response.failed / error event. Body is the event payload for the caller's error classifier.

func (*ResponsesStreamFailure) Error added in v0.6.7

func (e *ResponsesStreamFailure) Error() string

type ResponsesTranslation added in v0.6.7

type ResponsesTranslation struct {
	Chat      ChatRequest
	ToolNames map[string]ResponseToolName
}

ResponsesTranslation is a Responses request in the shared chat form plus the request-local tool identity the gateway needs to restore on the way out. ToolNames never travels with Chat: providers only ever see flattened names.

func TranslateResponsesRequest added in v0.6.7

func TranslateResponsesRequest(request ResponsesRequest) (ResponsesTranslation, error)

Jump to

Keyboard shortcuts

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