codec

package
v0.0.13 Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package codec defines the Intermediate Representation (IR) types and Codec interfaces used by the native protocol conversion layer. The IR provides a unified data model that sits between inbound (client-facing) and outbound (provider-facing) protocols, enabling M x N protocol conversion via a shared intermediate form.

Index

Constants

View Source
const (
	EndpointKeyChatCompletions = "chat_completions"
	EndpointKeyResponses       = "responses"
	EndpointKeyMessages        = "messages"
)

Endpoint JSON keys used in Channel.Endpoints field.

View Source
const (
	ImageSourceBase64 = "base64"
	ImageSourceURL    = "url"
)

Image source type 常量。

View Source
const (
	DroppedToolReasonCrossProtocolIncompatible   = "cross_protocol_incompatible"
	DroppedToolReasonFunctionFallbackUnsupported = "function_fallback_unsupported"
)

Variables

View Source
var ErrBuiltinToolUnsupported = errors.New("codec: built-in tool not supported by target protocol")

ErrBuiltinToolUnsupported 表示目标协议无法表达该内置工具,且渠道策略为 error。

View Source
var ErrFunctionToolMissingName = errors.New("codec: function tool has empty name")

ErrFunctionToolMissingName 表示一个声称 type=function 的工具缺少 name。 这是 IR 的结构性错误,与 policy 无关,必须 fail-loud。

Functions

func AdaptFunctionFallbackEvents added in v0.0.13

func AdaptFunctionFallbackEvents(
	ctx context.Context,
	events <-chan Event,
	tools map[string]FunctionFallbackTool,
) <-chan Event

AdaptFunctionFallbackEvents restores custom tool calls that a limited upstream emitted as function calls. The returned event is raw Responses wire data so the inbound Responses codec can preserve custom-tool semantics.

func ApplyIRTransformers

func ApplyIRTransformers(p Protocol, req *Request, cfg *ChannelConfig)

ApplyIRTransformers 由 native.go 在调用 outboundCodec.EncodeRequest 之前调用。 按注册顺序对所有 AppliesTo(p) == true 的 transformer 链式应用。

func AssertStreamingToolCallInvariant

func AssertStreamingToolCallInvariant(events []Event) error

AssertStreamingToolCallInvariant verifies that for each call_id in the event stream the order is: exactly one Start, zero or more ArgumentsDelta, exactly one End. Parallel tool_calls (multiple call_ids interleaved) are allowed.

func AssertToolsInvariant

func AssertToolsInvariant(tools []any) error

AssertToolsInvariant 扫描已构造好的出站 tools 数组,若任何 function 形状的 条目 name 为空则返回 ErrFunctionToolMissingName。这是编码器序列化前的最后 一道绊马索:即使未来有其它路径往 raw.Tools 里塞东西,也能兜住结构性缺陷。

识别的三种 function 形状:

OpenAI Chat:      {"type":"function", "function":{"name":"..."}}
OpenAI Responses: {"type":"function", "name":"..."}
Claude:           {"name":"..."}(顶层 name,且无 type 字段或 type 非 function)

非 function 形状(如内置工具的 RawConfig passthrough)一律跳过。

func BuildConnectivityTestRequest added in v0.0.7

func BuildConnectivityTestRequest(endpoints, supportedAPITypes, endpointType, model string, stream bool) (path string, body map[string]any, err error)

BuildConnectivityTestRequest returns the relay path and minimal request body for a connectivity test, shaped by the resolved Protocol. Shared by the master public-channel test and agent RPC test so the endpoint vocabulary and body shape live in one place.

func DefaultEndpointPath

func DefaultEndpointPath(p Protocol) string

DefaultEndpointPath returns the standard endpoint path for a protocol.

func FilterOptionalRequestFields added in v0.0.13

func FilterOptionalRequestFields(req *Request, permissions RequestFieldPermissions)

FilterOptionalRequestFields applies the channel request-field policy before an outbound codec serializes the IR. It mutates the working request owned by the dataflow pass; Pass.Original remains unchanged.

func FunctionFallbackTools added in v0.0.13

func FunctionFallbackTools(req *Request) map[string]FunctionFallbackTool

func JoinUpstreamURL added in v0.0.6

func JoinUpstreamURL(baseURL, path string) (string, error)

JoinUpstreamURL appends path to baseURL and verifies the path did not rewrite the scheme/host (e.g. via "@evil" userinfo or a non-rooted ".evil.com" suffix). This is the egress-side backstop for the BYOK endpoints SSRF defense: even a malicious endpoints row already in the DB cannot redirect the request — and the BYOK key — to a host other than the allowlisted base_url host.

func ParseEndpoints

func ParseEndpoints(raw string) map[Protocol]string

func RecordDroppedTools

func RecordDroppedTools(req *Request, dropped []DroppedTool)

RecordDroppedTools 把被丢弃的工具列表写到 req.Metadata["dropped_tools"], 以便 relay 层做日志 / trace 导出。空切片 / nil 为 no-op。

func RecordFunctionFallbackTools added in v0.0.13

func RecordFunctionFallbackTools(req *Request, tools []FunctionFallbackTool)

func RegisterIRTransformer

func RegisterIRTransformer(t IRTransformer)

RegisterIRTransformer 在 init 时注册 transformer。 注册顺序 == 执行顺序。重复注册同名 transformer panic(fail-loud)。

func RegisterInbound

func RegisterInbound(p Protocol, c InboundCodec)

RegisterInbound registers an InboundCodec for the given protocol.

func RegisterOutbound

func RegisterOutbound(p Protocol, c OutboundCodec)

RegisterOutbound registers an OutboundCodec for the given protocol.

func ResolveEndpointPath

func ResolveEndpointPath(endpoints string, proto Protocol) string

Types

type BuiltinToolFallbackPolicy

type BuiltinToolFallbackPolicy string

BuiltinToolFallbackPolicy 定义在目标协议无法表达某个内置工具时的处理策略。

const (
	BuiltinToolFallbackDrop        BuiltinToolFallbackPolicy = "drop"
	BuiltinToolFallbackError       BuiltinToolFallbackPolicy = "error"
	BuiltinToolFallbackPassthrough BuiltinToolFallbackPolicy = "passthrough"
	BuiltinToolFallbackFunction    BuiltinToolFallbackPolicy = "function"
)

func NormalizeBuiltinToolFallback

func NormalizeBuiltinToolFallback(s string) BuiltinToolFallbackPolicy

NormalizeBuiltinToolFallback 把配置里的字符串归一到合法策略。 未知值(含空串)一律回落到 BuiltinToolFallbackDrop。

type ChannelConfig

type ChannelConfig struct {
	BaseURL             string         `json:"base_url"`
	APIKey              string         `json:"api_key"`
	Model               string         `json:"model"`         // upstream model after model_mapping
	InboundModel        string         `json:"inbound_model"` // model as the client sent it (before mapping)
	Organization        string         `json:"organization,omitempty"`
	APIVersion          string         `json:"api_version,omitempty"`
	ParamOverride       map[string]any `json:"param_override,omitempty"`
	HeaderOverride      map[string]any `json:"header_override,omitempty"`
	SystemPrompt        string         `json:"system_prompt,omitempty"`
	EndpointPath        string         `json:"endpoint_path,omitempty"`
	RoleMapping         string         `json:"role_mapping,omitempty"`
	SystemPromptInInput bool           `json:"system_prompt_in_input,omitempty"`
	// BuiltinToolFallback 控制"入站带内置工具但出站协议无法表达"时的处理策略。
	// 合法值:"drop"(默认)、"error"、"passthrough"。空串归一到 "drop"。
	// 从 Channel.OtherSettings["builtin_tool_fallback"] 读入,由 ResolveTool 消费。
	BuiltinToolFallback string `json:"builtin_tool_fallback,omitempty"`
	// SendBackThinking 控制是否把 IR 中 ContentTypeThinking 块作为
	// reasoning_content 回填到上游请求的 history。仅 openai_chat 出站时生效。
	// 由 upstream/channelconfig.go 在 BuildChannelConfig 时根据 OtherSettings 中的
	// model_thinking_passthrough 规则匹配 cfg.Model 后填入。
	SendBackThinking bool `json:"send_back_thinking,omitempty"`
	// InlineImageURL 为 true 时,StepInlineImages 在出站编码前把消息里 MediaURL 形式的
	// 图片下载内联成 base64(MediaB64)。从 Channel.OtherSettings["inline_image_url"] 读入。
	InlineImageURL bool `json:"inline_image_url,omitempty"`
	// RequestFieldPermissions is applied once, immediately before outbound
	// encoding, so every native codec follows the same forwarding policy.
	RequestFieldPermissions RequestFieldPermissions `json:"request_field_permissions"`
	// ClaudeBetaQuery appends beta=true to Claude Messages request URLs.
	ClaudeBetaQuery bool `json:"claude_beta_query,omitempty"`
}

ChannelConfig holds provider-specific configuration used when encoding an outbound request to an upstream AI provider.

type ContentBlock

type ContentBlock struct {
	Type     ContentType    `json:"type"`
	Text     string         `json:"text,omitempty"`
	MediaURL string         `json:"media_url,omitempty"`
	MediaB64 string         `json:"media_b64,omitempty"`
	MimeType string         `json:"mime_type,omitempty"`
	Metadata map[string]any `json:"metadata,omitempty"`

	// RawJSON preserves the original JSON for unknown content block types.
	// When set, the encoder should emit this JSON as-is instead of
	// constructing from typed fields.
	RawJSON json.RawMessage `json:"raw_json,omitempty"`
}

ContentBlock is a single piece of typed content within a message.

func DropEmptyTextBlocks added in v0.0.13

func DropEmptyTextBlocks(blocks []ContentBlock) []ContentBlock

DropEmptyTextBlocks 返回去掉「空文本块」后的新 slice。空文本块指 Type==Text、非 RawJSON 且 Text=="" 的结构化块——OpenAI 兼容上游(如 SGLang)会拒绝 {"type":"text"} 这种缺/空 text 字段的块。RawJSON 透传块(Type 为空)、图片/工具等非文本块一律原样保留。 不原地修改入参。

type ContentType

type ContentType string

ContentType describes the kind of content carried by a ContentBlock.

const (
	ContentTypeText       ContentType = "text"
	ContentTypeImage      ContentType = "image"
	ContentTypeAudio      ContentType = "audio"
	ContentTypeToolUse    ContentType = "tool_use"
	ContentTypeToolResult ContentType = "tool_result"
	ContentTypeThinking   ContentType = "thinking"
	ContentTypeInputText  ContentType = "input_text"
	ContentTypeOutputText ContentType = "output_text"
	ContentTypeImageURL   ContentType = "image_url"
	ContentTypeFunction   ContentType = "function"
)

type DeltaPayload

type DeltaPayload struct {
	ContentType ContentType    `json:"content_type,omitempty"`
	Text        string         `json:"text,omitempty"`
	Refusal     string         `json:"refusal,omitempty"`
	Signature   string         `json:"signature,omitempty"`
	ToolCall    *ToolCallDelta `json:"tool_call,omitempty"`
}

DeltaPayload carries incremental content for delta events.

type DroppedTool

type DroppedTool struct {
	Type   string `json:"type"`
	Name   string `json:"name,omitempty"`
	Reason string `json:"reason"`
}

DroppedTool 描述被 ResolveTool 丢弃的工具,供可观测层记录。

type ErrorPayload

type ErrorPayload struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

ErrorPayload describes an error encountered during streaming.

type Event

type Event struct {
	Type              EventType          `json:"type"`
	Delta             *DeltaPayload      `json:"delta,omitempty"`
	ToolCall          *StreamingToolCall `json:"tool_call,omitempty"`
	Usage             *Usage             `json:"usage,omitempty"`
	Error             *ErrorPayload      `json:"error,omitempty"`
	FinishReason      string             `json:"finish_reason,omitempty"`
	Model             string             `json:"model,omitempty"`   // upstream model name passthrough
	Created           int64              `json:"created,omitempty"` // upstream timestamp passthrough
	Metadata          map[string]any     `json:"metadata,omitempty"`
	RawPassthrough    *RawSSEEvent       `json:"raw_passthrough,omitempty"`
	Extras            map[string]any     `json:"extras,omitempty"` // non-streaming response unknown field passthrough
	ContentBlockIndex *int               `json:"content_block_index,omitempty"`
	StopSequence      string             `json:"stop_sequence,omitempty"`
}

Event is a single element in the IR event stream produced when streaming responses from an upstream provider.

type EventType

type EventType int

EventType identifies the kind of streaming event in an IR event stream.

const (
	EventStreamStart            EventType = iota // stream has started
	EventContentDelta                            // incremental text content
	EventToolCallDelta                           // Deprecated: split into EventToolCallStart / EventToolCallArgumentsDelta / EventToolCallEnd. Will be removed once all stream codecs migrate.
	EventThinkingDelta                           // incremental thinking/reasoning content
	EventUsage                                   // token usage report
	EventDone                                    // stream finished normally
	EventError                                   // stream finished with an error
	EventRawPassthrough                          // raw SSE event that could not be parsed into a known IR event
	EventContentBlockStop                        // content block ended
	EventSignatureDelta                          // thinking block signature
	EventToolCallStart                           // streaming: a tool call began (call_id + name)
	EventToolCallArgumentsDelta                  // streaming: incremental arguments fragment
	EventToolCallEnd                             // streaming: tool call ended with full accumulated arguments
)

type FunctionFallbackTool added in v0.0.13

type FunctionFallbackTool struct {
	Name         string `json:"name"`
	ArgumentName string `json:"argument_name"`
}

FunctionFallbackTool records a custom tool exposed to a limited upstream as a function tool. The response path uses this mapping to restore the original custom_tool_call shape expected by the client.

type IRTransformer

type IRTransformer interface {
	// Name 用于日志 / 重复注册检测,必须全局唯一。
	Name() string

	// AppliesTo 决定该 transformer 是否对当前出站协议生效。
	AppliesTo(p Protocol) bool

	// Transform in-place 改写 req。不动 cfg。
	Transform(req *Request, cfg *ChannelConfig)
}

IRTransformer 在 EncodeRequest 之前对 IR Request 做 in-place 改写。 用于"按 channel/model 配置改写 IR"类需求(系统提示注入、角色映射、 DeepSeek thinking 字段兜底等)。

实现方约定:

  • 必须幂等:同一 (req, cfg) 反复调用结果不变
  • 必须只读 cfg
  • 必须不返回错误:transformer 不阻塞请求路径,遇到非法配置 noop 并打 warn

type InboundCodec

type InboundCodec interface {
	// DecodeRequest parses an incoming HTTP request into the IR Request.
	DecodeRequest(r *http.Request) (*Request, error)

	// EncodeResponse writes an IR event stream back to the client.
	// When stream is true the response is sent as server-sent events;
	// otherwise a single JSON payload is returned.
	EncodeResponse(events <-chan Event, w http.ResponseWriter, stream bool) error

	// EncodeError writes an error response to the client.
	EncodeError(w http.ResponseWriter, statusCode int, err error)
}

InboundCodec handles the client-facing side of a protocol: it decodes incoming requests and encodes outgoing responses back to the client.

func GetInbound

func GetInbound(p Protocol) InboundCodec

GetInbound returns the registered InboundCodec for the given protocol, or nil if none has been registered.

type Message

type Message struct {
	Role       Role           `json:"role"`
	Content    []ContentBlock `json:"content"`
	ToolCalls  []ToolCall     `json:"tool_calls,omitempty"`
	ToolCallID string         `json:"tool_call_id,omitempty"`

	// RawJSON preserves the original JSON for unknown input item types.
	// When set with empty Role, the encoder should emit this JSON as-is.
	RawJSON json.RawMessage `json:"raw_json,omitempty"`
}

Message represents a single conversation turn.

func NormalizeAssistantToolCallSequence

func NormalizeAssistantToolCallSequence(messages []Message) []Message

NormalizeAssistantToolCallSequence reorders and merges messages so that every assistant message with tool_calls is immediately followed by the tool messages that respond to those tool_calls.

Responses API allows function_call output items and assistant text items to be interleaved freely. For example, Codex CLI may emit:

function_call(id=X) → assistant{"preamble text"} → function_call_output(id=X)

This is invalid for OpenAI Chat Completions, which requires:

assistant{tool_calls=[X]} → tool{tool_call_id=X}

The algorithm walks forward from each assistant message that has tool_calls:

  1. Collects subsequent assistant messages with NO tool_calls ("preambles") and subsequent tool messages whose tool_call_id matches one of the pending ids.
  2. Handles consecutive assistant messages that carry tool_calls (parallel tool calls): merges their ToolCalls into the anchor and adds the new IDs to pending so their tool responses are also collected.
  3. Stops when it encounters a message that is neither a preamble, a parallel tool_calls assistant, nor a matching tool response (e.g. a user message, or a tool with a non-matching id).
  4. Merges all preamble text into the anchor assistant message's content (appended with "\n\n" separator). The preamble messages are dropped.
  5. The collected tool messages follow the anchor immediately.

This function does NOT mutate the input slice — it returns a new slice.

func TextMessage

func TextMessage(role Role, text string) Message

TextMessage is a convenience constructor for a simple text message.

type OutboundCodec

type OutboundCodec interface {
	// EncodeRequest converts an IR Request into an HTTP request suitable for
	// the upstream provider described by cfg.
	EncodeRequest(req *Request, cfg *ChannelConfig) (*http.Request, error)

	// DecodeResponse reads the upstream HTTP response and returns a channel
	// of IR events. When stream is true the response body is expected to be
	// a server-sent event stream.
	DecodeResponse(resp *http.Response, stream bool) (<-chan Event, error)
}

OutboundCodec handles the provider-facing side of a protocol: it encodes IR requests into upstream HTTP requests and decodes upstream responses back into the IR event stream.

func GetOutbound

func GetOutbound(p Protocol) OutboundCodec

GetOutbound returns the registered OutboundCodec for the given protocol, or nil if none has been registered.

type Protocol

type Protocol string

Protocol identifies a wire protocol supported by the gateway.

const (
	ProtocolOpenAIChat      Protocol = "openai_chat"
	ProtocolOpenAIResponses Protocol = "openai_responses"
	ProtocolClaude          Protocol = "claude"
	ProtocolGemini          Protocol = "gemini"
	ProtocolUnknown         Protocol = "unknown"
)

func ChannelTypeToProtocol

func ChannelTypeToProtocol(channelType int) Protocol

ChannelTypeToProtocol converts a numeric channel type (as used by the existing channel/model configuration) to a Protocol.

func NegotiateOutboundProtocol

func NegotiateOutboundProtocol(
	inbound Protocol,
	channelType int,
	supportedAPITypes string,
	endpoints string,
	override map[Protocol]Protocol,
) Protocol

NegotiateOutboundProtocol selects the best outbound protocol for a request based on the inbound protocol and the channel's declared supported API types.

Rules:

  1. If override[inbound] is a valid Protocol and target is reachable (in endpoints / supportedAPITypes, or both unset), use override target (highest priority).
  2. If endpoints is configured, use it.
  3. Parse supportedAPITypes JSON array into a Protocol set.
  4. If the set is empty, fall back to ChannelTypeToProtocol.
  5. If the inbound protocol is in the set, use it.
  6. Otherwise pick the first supported protocol by priority: responses > chat > claude.
  7. If none match, fall back to ChannelTypeToProtocol.

func NormalizeEndpointType added in v0.0.7

func NormalizeEndpointType(raw string) (key string, proto Protocol, ok bool)

NormalizeEndpointType maps a request endpoint_type (canonical key or legacy alias) to a canonical endpoint key + Protocol. ok=false for empty input (caller derives a default from the channel's endpoints).

func PathToProtocol

func PathToProtocol(path string) Protocol

PathToProtocol maps a well-known HTTP path to the corresponding Protocol.

func PrimaryOutboundProtocol added in v0.0.8

func PrimaryOutboundProtocol(endpoints, supportedAPITypes string) Protocol

PrimaryOutboundProtocol 返回 channel 的主出站协议(给静态 dataflow describe 复用)。 入参直接收 channel 的 endpoints / supportedAPITypes 字符串,避免 codec 依赖 models。

func ResolveTestEndpoint added in v0.0.7

func ResolveTestEndpoint(endpoints, supportedAPITypes, raw string) (key string, proto Protocol, path string, err error)

ResolveTestEndpoint resolves the upstream path used to connectivity-test a channel, driven by the codec Protocol model (endpoints / supportedAPITypes) — never the deprecated numeric channel type.

type RawSSEEvent

type RawSSEEvent struct {
	EventName string `json:"event_name"`
	Data      string `json:"data"`
}

RawSSEEvent carries a raw SSE event that could not be parsed into a known IR event.

type Request

type Request struct {
	Model       string         `json:"model"`
	Messages    []Message      `json:"messages"`
	Tools       []Tool         `json:"tools,omitempty"`
	Stream      bool           `json:"stream"`
	MaxTokens   int            `json:"max_tokens,omitempty"`
	Temperature *float64       `json:"temperature,omitempty"`
	TopP        *float64       `json:"top_p,omitempty"`
	StopWords   []string       `json:"stop,omitempty"`
	Metadata    map[string]any `json:"metadata,omitempty"`

	// Model behavior fields (commonly used across protocols)
	ToolChoice        *ToolChoice `json:"tool_choice,omitempty"`
	ParallelToolCalls *bool       `json:"parallel_tool_calls,omitempty"`
	ReasoningEffort   string      `json:"reasoning_effort,omitempty"`
	ThinkingEnabled   bool        `json:"thinking_enabled,omitempty"`
	ThinkingBudget    int         `json:"thinking_budget,omitempty"`
	Store             *bool       `json:"store,omitempty"`

	// Sampling / generation parameters
	FrequencyPenalty *float64       `json:"frequency_penalty,omitempty"`
	PresencePenalty  *float64       `json:"presence_penalty,omitempty"`
	Seed             *int64         `json:"seed,omitempty"`
	N                int            `json:"n,omitempty"`
	TopK             *int           `json:"top_k,omitempty"`
	LogitBias        map[string]int `json:"logit_bias,omitempty"`
	Logprobs         *bool          `json:"logprobs,omitempty"`
	TopLogprobs      *int           `json:"top_logprobs,omitempty"`
	User             string         `json:"user,omitempty"`
	ServiceTier      string         `json:"service_tier,omitempty"`
	InferenceGeo     string         `json:"inference_geo,omitempty"`
	SafetyIdentifier string         `json:"safety_identifier,omitempty"`
	ResponseFormat   any            `json:"response_format,omitempty"`
	StreamOptions    map[string]any `json:"stream_options,omitempty"`

	// Protocol-specific passthrough container
	Extras map[string]any `json:"extras,omitempty"`

	// InboundProtocol 由 InboundCodec.DecodeRequest 在成功解析后填写,标识
	// 该请求的原始入站协议。编码器据此判断"源协议 == 目标协议"做 passthrough。
	// 零值 "" 表示未知,ResolveTool 会退化到跨协议分支。
	InboundProtocol Protocol `json:"inbound_protocol,omitempty"`
}

Request is the protocol-agnostic representation of an AI completion request.

type RequestFieldPermissions added in v0.0.13

type RequestFieldPermissions struct {
	AllowServiceTier        bool `json:"allow_service_tier,omitempty"`
	AllowInferenceGeo       bool `json:"allow_inference_geo,omitempty"`
	AllowStore              bool `json:"allow_store"`
	AllowSafetyIdentifier   bool `json:"allow_safety_identifier,omitempty"`
	AllowIncludeObfuscation bool `json:"allow_include_obfuscation,omitempty"`
}

RequestFieldPermissions controls which optional client request fields may be forwarded to an upstream provider. Store is the only field allowed by default, matching the legacy adaptor's privacy and billing policy.

func DefaultRequestFieldPermissions added in v0.0.13

func DefaultRequestFieldPermissions() RequestFieldPermissions

type ResolvedTool

type ResolvedTool struct {
	Emit             any
	Dropped          *DroppedTool
	FunctionFallback *FunctionFallbackTool
}

ResolvedTool 是 ResolveTool 的返回值。Emit 与 Dropped 恰有一个被填充。

func ResolveTool

func ResolveTool(
	t Tool,
	source, target Protocol,
	policy BuiltinToolFallbackPolicy,
	targetEmit TargetEmitFuncs,
) (ResolvedTool, error)

ResolveTool 是把 IR Tool 映射到目标协议 wire 表达的唯一入口。 所有出站 codec 必须委托给它,不得自行构造工具记录。

决策顺序(自上而下、首个命中为准):

A. Type == "function"(含空)且 Name != "" → Emit = targetEmit.Function(t)
B. Type == "function"(含空)且 Name == "" → ErrFunctionToolMissingName(policy 无关)
C. Responses 目标 && policy = function && named custom tool → 作为 function 发出并记录反向映射
D. policy = function && 其它非 function 工具 → Dropped
E. 内置 && source == target && RawConfig != nil → Emit = RawConfig(同协议透传)
F. 内置 && 跨协议 && policy = drop → Dropped
G. 内置 && 跨协议 && policy = error → ErrBuiltinToolUnsupported
H. 内置 && 跨协议 && policy = passthrough → Emit = RawConfig(运维自担)

说明:source 为零值 Protocol("") 被视作"未知入站",等同于"源 != 目标"。

type Role

type Role string

Role represents the role of a message participant.

const (
	RoleSystem    Role = "system"
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
	RoleTool      Role = "tool"
	RoleDeveloper Role = "developer"
)

type StreamingToolCall

type StreamingToolCall struct {
	CallID    string `json:"call_id"`
	Index     int    `json:"index"`
	Name      string `json:"name,omitempty"`
	Arguments string `json:"arguments,omitempty"`
}

StreamingToolCall carries per-event state for the 3 streaming tool_call events. CallID is required on all 3 events to bind identity. Index mirrors the chat protocol's tool_calls[].index for parallel calls. Name is set on Start. Arguments holds a fragment on ArgumentsDelta and the full accumulated value on End.

type TargetEmitFuncs

type TargetEmitFuncs struct {
	// Function 把 IR 的 function tool 构造成目标协议的 wire 形状。
	Function func(t Tool) any
}

TargetEmitFuncs 由调用方(编码器)提供,集中目标协议特有的 wire shape 构造。

type Tool

type Tool struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	InputSchema any    `json:"input_schema"`
	Type        string `json:"type,omitempty"` // "function", "web_search", "custom", etc.
	Strict      *bool  `json:"strict,omitempty"`
	RawConfig   any    `json:"raw_config,omitempty"` // full config for non-function tools
}

Tool describes a tool (function) that the model may invoke.

type ToolCall

type ToolCall struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Arguments string `json:"arguments"`
}

ToolCall represents a model-initiated tool invocation.

type ToolCallDelta

type ToolCallDelta struct {
	ID        string `json:"id,omitempty"`
	Name      string `json:"name,omitempty"`
	Arguments string `json:"arguments,omitempty"`
}

ToolCallDelta carries incremental data for a streaming tool call.

type ToolChoice

type ToolChoice struct {
	Type string `json:"type"`           // "auto", "required", "none", "function", "custom"
	Name string `json:"name,omitempty"` // tool name, when Type="function" or "custom"
}

ToolChoice defines the canonical IR form for tool selection.

type Usage

type Usage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	CacheReadTokens  int `json:"cache_read_tokens,omitempty"`
	CacheWriteTokens int `json:"cache_write_tokens,omitempty"`
	TotalTokens      int `json:"total_tokens"`

	// Detailed token breakdowns (OpenAI completion_tokens_details / prompt_tokens_details)
	ReasoningTokens          int `json:"reasoning_tokens,omitempty"`
	CachedTokens             int `json:"cached_tokens,omitempty"`
	AcceptedPredictionTokens int `json:"accepted_prediction_tokens,omitempty"`
	RejectedPredictionTokens int `json:"rejected_prediction_tokens,omitempty"`
}

Usage reports token consumption for a request.

Directories

Path Synopsis
Package claude implements the Anthropic Claude Messages API protocol codec.
Package claude implements the Anthropic Claude Messages API protocol codec.
Package openai implements the OpenAI Chat Completions protocol codec.
Package openai implements the OpenAI Chat Completions protocol codec.

Jump to

Keyboard shortcuts

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