diff --git a/README.md b/README.md index 2c5a603..7acd2cf 100644 --- a/README.md +++ b/README.md @@ -158,7 +158,7 @@ SOCKS5 代理示例: | 字段 | 含义 | | --- | --- | -| `retry.max_attempts` | 单个请求的最大尝试次数,包含第一次请求。非 2xx 响应或网络错误会切换节点。 | +| `retry.max_attempts` | 单个请求的最大尝试次数,包含第一次请求。网络错误、认证失败、限流和 5xx 会切换节点;其他 4xx 属于确定性的请求错误,会直接返回而不轮换 key。 | | `retry.timeout_seconds` | 单个客户端请求的总超时时间,同时用于限制上游响应头等待时间。 | 流式响应一旦已经向客户端输出数据,就不会切换节点重新生成,避免拼接两个不同的响应。 @@ -170,6 +170,7 @@ SOCKS5 代理示例: | `models.refresh_seconds` | 重新读取 Zen 和 Go 模型列表的间隔秒数。两个列表会并发刷新。 | | `models.protocols` | 手动指定模型的原生协议。值只能是 `chat`、`responses` 或 `anthropic`。通常保持为空。 | + 模型协议覆盖示例: ```json diff --git a/convert.go b/convert.go index 6caf3e6..6fb63f6 100644 --- a/convert.go +++ b/convert.go @@ -3,42 +3,49 @@ package main import ( "encoding/json" "fmt" + "sort" "strings" "time" ) -type canonicalBlock struct { - Type string - Text string - URL string - Media string - Data string - ID string - Name string - Input any - ToolID string - Content any - IsError bool +type bridgeBlock struct { + Kind string + Text string + URL string + MediaType string + Data string + ID string + Name string + Arguments any + ArgumentsJSON string + CallID string + Result any + IsError bool } -type canonicalMessage struct { +type bridgeMessage struct { Role string - Blocks []canonicalBlock + Blocks []bridgeBlock } -type canonicalTool struct { +type bridgeTool struct { Name string Description string - Parameters any + Schema any Strict bool } -type canonicalRequest struct { +type bridgeToolChoice struct { + Mode string + Name string +} + +type bridgeRequest struct { Model string - System []canonicalBlock - Messages []canonicalMessage - Tools []canonicalTool - ToolChoice any + System []bridgeBlock + Messages []bridgeMessage + Tools []bridgeTool + ToolChoice bridgeToolChoice Stream bool Temperature any TopP any @@ -48,7 +55,7 @@ type canonicalRequest struct { Metadata any } -type canonicalUsage struct { +type bridgeUsage struct { Input int Output int Total int @@ -56,13 +63,13 @@ type canonicalUsage struct { Reasoning int } -type canonicalResponse struct { +type bridgeResponse struct { ID string Model string Text string - Tools []canonicalBlock + Tools []bridgeBlock Stop string - Usage canonicalUsage + Usage bridgeUsage Created int64 } @@ -70,15 +77,15 @@ func convertRequest(from, to Protocol, input map[string]any) (map[string]any, er if from == to { return cloneMap(input), nil } - canonical, err := decodeRequest(from, input) + request, err := decodeBridgeRequest(from, input) if err != nil { return nil, err } - return encodeRequest(to, canonical), nil + return encodeBridgeRequest(to, request) } -func decodeRequest(protocol Protocol, input map[string]any) (canonicalRequest, error) { - request := canonicalRequest{ +func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest, error) { + request := bridgeRequest{ Model: stringAt(input, "model"), Stream: boolAt(input, "stream"), Temperature: input["temperature"], @@ -90,399 +97,570 @@ func decodeRequest(protocol Protocol, input map[string]any) (canonicalRequest, e request.MaxTokens = firstAny(input["max_completion_tokens"], input["max_tokens"]) request.Stop = input["stop"] request.Reasoning = firstAny(input["reasoning_effort"], input["reasoning"]) - for _, raw := range sliceAt(input, "messages") { + for i, raw := range sliceAt(input, "messages") { message, ok := raw.(map[string]any) if !ok { - return request, fmt.Errorf("messages must contain objects") + return request, fmt.Errorf("messages[%d] must be an object", i) } role := stringAt(message, "role") - blocks := decodeOpenAIContent(message["content"]) - if role == "system" || role == "developer" { + blocks := decodeOpenAIBlocks(message["content"]) + for j, rawCall := range sliceAt(message, "tool_calls") { + call, ok := rawCall.(map[string]any) + if !ok { + return request, fmt.Errorf("messages[%d].tool_calls[%d] must be an object", i, j) + } + function := mapAt(call, "function") + blocks = append(blocks, bridgeBlock{ + Kind: "tool_call", + ID: stringAt(call, "id"), + Name: stringAt(function, "name"), + ArgumentsJSON: stringAt(function, "arguments"), + }) + } + switch role { + case "system", "developer": request.System = append(request.System, blocks...) - continue + case "tool": + request.Messages = append(request.Messages, bridgeMessage{Role: "user", Blocks: []bridgeBlock{{ + Kind: "tool_result", + CallID: stringAt(message, "tool_call_id"), + Result: message["content"], + }}}) + case "user", "assistant": + request.Messages = append(request.Messages, bridgeMessage{Role: role, Blocks: blocks}) + default: + return request, fmt.Errorf("messages[%d] has unsupported role %q", i, role) } - if role == "tool" { - blocks = []canonicalBlock{{Type: "tool_result", ToolID: stringAt(message, "tool_call_id"), Content: message["content"]}} - role = "user" - } - for _, rawCall := range sliceAt(message, "tool_calls") { - call, _ := rawCall.(map[string]any) - fn, _ := call["function"].(map[string]any) - blocks = append(blocks, canonicalBlock{Type: "tool_use", ID: stringAt(call, "id"), Name: stringAt(fn, "name"), Input: parseJSONOrString(stringAt(fn, "arguments"))}) - } - request.Messages = append(request.Messages, canonicalMessage{Role: role, Blocks: blocks}) } - for _, raw := range sliceAt(input, "tools") { - tool, _ := raw.(map[string]any) - fn, _ := tool["function"].(map[string]any) - request.Tools = append(request.Tools, canonicalTool{Name: stringAt(fn, "name"), Description: stringAt(fn, "description"), Parameters: fn["parameters"], Strict: boolAt(fn, "strict")}) + for i, raw := range sliceAt(input, "tools") { + tool, ok := raw.(map[string]any) + if !ok || stringAt(tool, "type") != "function" { + return request, fmt.Errorf("tools[%d] must be a function tool", i) + } + function := mapAt(tool, "function") + request.Tools = append(request.Tools, bridgeTool{ + Name: stringAt(function, "name"), + Description: stringAt(function, "description"), + Schema: function["parameters"], + Strict: boolAt(function, "strict"), + }) } request.ToolChoice = decodeChatToolChoice(input["tool_choice"]) + case ProtocolResponses: request.MaxTokens = input["max_output_tokens"] request.Stop = input["stop"] request.Reasoning = input["reasoning"] - request.System = append(request.System, decodeOpenAIContent(input["instructions"])...) - switch raw := input["input"].(type) { + request.System = append(request.System, decodeOpenAIBlocks(input["instructions"])...) + switch value := input["input"].(type) { case string: - request.Messages = append(request.Messages, canonicalMessage{Role: "user", Blocks: []canonicalBlock{{Type: "text", Text: raw}}}) + request.Messages = append(request.Messages, bridgeMessage{Role: "user", Blocks: []bridgeBlock{{Kind: "text", Text: value}}}) case []any: - for _, itemRaw := range raw { - item, ok := itemRaw.(map[string]any) + for i, raw := range value { + item, ok := raw.(map[string]any) if !ok { - return request, fmt.Errorf("input must contain objects") + return request, fmt.Errorf("input[%d] must be an object", i) } switch stringAt(item, "type") { case "function_call": - request.Messages = append(request.Messages, canonicalMessage{Role: "assistant", Blocks: []canonicalBlock{{Type: "tool_use", ID: stringAt(item, "call_id"), Name: stringAt(item, "name"), Input: parseJSONOrString(stringAt(item, "arguments"))}}}) + appendBridgeBlock(&request.Messages, "assistant", bridgeBlock{ + Kind: "tool_call", + ID: firstString(stringAt(item, "call_id"), stringAt(item, "id")), + Name: stringAt(item, "name"), + ArgumentsJSON: stringAt(item, "arguments"), + }) case "function_call_output": - request.Messages = append(request.Messages, canonicalMessage{Role: "user", Blocks: []canonicalBlock{{Type: "tool_result", ToolID: stringAt(item, "call_id"), Content: item["output"]}}}) - default: + appendBridgeBlock(&request.Messages, "user", bridgeBlock{ + Kind: "tool_result", + CallID: stringAt(item, "call_id"), + Result: item["output"], + }) + case "message", "": role := stringAt(item, "role") - blocks := decodeOpenAIContent(item["content"]) + blocks := decodeOpenAIBlocks(item["content"]) if role == "system" || role == "developer" { request.System = append(request.System, blocks...) - } else { - request.Messages = append(request.Messages, canonicalMessage{Role: role, Blocks: blocks}) + } else if role == "user" || role == "assistant" { + request.Messages = append(request.Messages, bridgeMessage{Role: role, Blocks: blocks}) } } } default: return request, fmt.Errorf("input must be a string or array") } - for _, raw := range sliceAt(input, "tools") { - tool, _ := raw.(map[string]any) - if stringAt(tool, "type") != "function" { - return request, fmt.Errorf("only function tools can be converted between protocols") + for i, raw := range sliceAt(input, "tools") { + tool, ok := raw.(map[string]any) + if !ok || stringAt(tool, "type") != "function" { + return request, fmt.Errorf("tools[%d] must be a function tool", i) } - request.Tools = append(request.Tools, canonicalTool{Name: stringAt(tool, "name"), Description: stringAt(tool, "description"), Parameters: tool["parameters"], Strict: boolAt(tool, "strict")}) + request.Tools = append(request.Tools, bridgeTool{ + Name: stringAt(tool, "name"), + Description: stringAt(tool, "description"), + Schema: tool["parameters"], + Strict: boolAt(tool, "strict"), + }) } request.ToolChoice = decodeResponsesToolChoice(input["tool_choice"]) + case ProtocolAnthropic: request.MaxTokens = input["max_tokens"] request.Stop = input["stop_sequences"] request.Reasoning = firstAny(input["thinking"], input["effort"]) - request.System = decodeAnthropicContent(input["system"]) - for _, raw := range sliceAt(input, "messages") { + request.System = decodeAnthropicBlocks(input["system"]) + for i, raw := range sliceAt(input, "messages") { message, ok := raw.(map[string]any) if !ok { - return request, fmt.Errorf("messages must contain objects") + return request, fmt.Errorf("messages[%d] must be an object", i) } - request.Messages = append(request.Messages, canonicalMessage{Role: stringAt(message, "role"), Blocks: decodeAnthropicContent(message["content"])}) + role := stringAt(message, "role") + if role != "user" && role != "assistant" { + return request, fmt.Errorf("messages[%d] has unsupported role %q", i, role) + } + request.Messages = append(request.Messages, bridgeMessage{Role: role, Blocks: decodeAnthropicBlocks(message["content"])}) } - for _, raw := range sliceAt(input, "tools") { - tool, _ := raw.(map[string]any) - request.Tools = append(request.Tools, canonicalTool{Name: stringAt(tool, "name"), Description: stringAt(tool, "description"), Parameters: tool["input_schema"]}) + for i, raw := range sliceAt(input, "tools") { + tool, ok := raw.(map[string]any) + if !ok { + return request, fmt.Errorf("tools[%d] must be an object", i) + } + request.Tools = append(request.Tools, bridgeTool{ + Name: stringAt(tool, "name"), + Description: stringAt(tool, "description"), + Schema: tool["input_schema"], + }) } request.ToolChoice = decodeAnthropicToolChoice(input["tool_choice"]) + default: return request, fmt.Errorf("unsupported input protocol %q", protocol) } return request, nil } -func encodeRequest(protocol Protocol, request canonicalRequest) map[string]any { +func appendBridgeBlock(messages *[]bridgeMessage, role string, block bridgeBlock) { + if len(*messages) > 0 { + last := &(*messages)[len(*messages)-1] + if last.Role == role && bridgeBlocksOnlyTools(last.Blocks) { + last.Blocks = append(last.Blocks, block) + return + } + } + *messages = append(*messages, bridgeMessage{Role: role, Blocks: []bridgeBlock{block}}) +} + +func bridgeBlocksOnlyTools(blocks []bridgeBlock) bool { + if len(blocks) == 0 { + return false + } + for _, block := range blocks { + if block.Kind != "tool_call" && block.Kind != "tool_result" { + return false + } + } + return true +} + +func encodeBridgeRequest(protocol Protocol, request bridgeRequest) (map[string]any, error) { + switch protocol { + case ProtocolChat: + return encodeChatRequest(request) + case ProtocolResponses: + return encodeResponsesRequest(request), nil + case ProtocolAnthropic: + return encodeAnthropicRequest(request), nil + default: + return nil, fmt.Errorf("unsupported output protocol %q", protocol) + } +} + +func encodeChatRequest(request bridgeRequest) (map[string]any, error) { output := map[string]any{"model": request.Model, "stream": request.Stream} put(output, "temperature", request.Temperature) put(output, "top_p", request.TopP) - put(output, "metadata", request.Metadata) - switch protocol { - case ProtocolChat: - messages := make([]any, 0, len(request.Messages)+1) - if len(request.System) > 0 { - messages = append(messages, map[string]any{"role": "system", "content": encodeChatContent(request.System)}) - } - for _, message := range request.Messages { - messages = append(messages, encodeChatMessages(message)...) - } - output["messages"] = normalizeChatToolMessages(messages) - put(output, "max_tokens", request.MaxTokens) - put(output, "stop", request.Stop) - if effort := reasoningEffort(request.Reasoning); effort != nil { - output["reasoning_effort"] = effort - } - if request.Stream { - output["stream_options"] = map[string]any{"include_usage": true} - } - if len(request.Tools) > 0 { - tools := make([]any, 0, len(request.Tools)) - for _, tool := range request.Tools { - tools = append(tools, map[string]any{"type": "function", "function": map[string]any{"name": tool.Name, "description": tool.Description, "parameters": schemaOrDefault(tool.Parameters), "strict": tool.Strict}}) + put(output, "max_tokens", request.MaxTokens) + put(output, "stop", request.Stop) + if effort := reasoningEffort(request.Reasoning); effort != nil { + output["reasoning_effort"] = effort + } + if request.Stream { + output["stream_options"] = map[string]any{"include_usage": true} + } + + messages := make([]any, 0, len(request.Messages)+1) + if len(request.System) > 0 { + messages = append(messages, map[string]any{"role": "system", "content": encodeChatBlocks(request.System)}) + } + pending := make(map[string]bool) + pendingResults := make(map[string]bridgeBlock) + var pendingOrder []string + var deferred [][]bridgeBlock + flushDeferred := func() { + for _, blocks := range deferred { + if len(blocks) > 0 { + messages = append(messages, map[string]any{"role": "user", "content": encodeChatBlocks(blocks)}) } - output["tools"] = tools - put(output, "tool_choice", encodeChatToolChoice(request.ToolChoice)) } - case ProtocolResponses: - if len(request.System) > 0 { - output["instructions"] = blocksText(request.System) - } - items := make([]any, 0, len(request.Messages)) - for _, message := range request.Messages { - items = append(items, encodeResponsesMessage(message)...) - } - output["input"] = items - put(output, "max_output_tokens", request.MaxTokens) - put(output, "stop", request.Stop) - if request.Reasoning != nil { - switch v := request.Reasoning.(type) { - case string: - output["reasoning"] = map[string]any{"effort": v} + deferred = nil + } + + for i, message := range request.Messages { + var content, calls, results []bridgeBlock + for _, block := range message.Blocks { + switch block.Kind { + case "tool_call": + calls = append(calls, block) + case "tool_result": + results = append(results, block) default: - output["reasoning"] = v + content = append(content, block) } } - if len(request.Tools) > 0 { - tools := make([]any, 0, len(request.Tools)) - for _, tool := range request.Tools { - tools = append(tools, map[string]any{"type": "function", "name": tool.Name, "description": tool.Description, "parameters": schemaOrDefault(tool.Parameters), "strict": tool.Strict}) + if message.Role == "assistant" { + if len(pending) > 0 { + return nil, fmt.Errorf("messages[%d]: assistant message appears before tool results for %s", i, strings.Join(missingToolIDs(pendingOrder, pending), ", ")) } - output["tools"] = tools - put(output, "tool_choice", encodeResponsesToolChoice(request.ToolChoice)) - } - case ProtocolAnthropic: - if len(request.System) > 0 { - output["system"] = encodeAnthropicContent(request.System) - } - messages := make([]any, 0, len(request.Messages)) - for _, message := range request.Messages { - messages = append(messages, map[string]any{"role": normalizeAnthropicRole(message.Role), "content": encodeAnthropicContent(message.Blocks)}) - } - output["messages"] = messages - if request.MaxTokens == nil { - output["max_tokens"] = 4096 - } else { - output["max_tokens"] = request.MaxTokens - } - put(output, "stop_sequences", request.Stop) - if effort := reasoningEffort(request.Reasoning); effort != nil { - output["effort"] = effort - } - if len(request.Tools) > 0 { - tools := make([]any, 0, len(request.Tools)) - for _, tool := range request.Tools { - tools = append(tools, map[string]any{"name": tool.Name, "description": tool.Description, "input_schema": schemaOrDefault(tool.Parameters)}) + if len(results) > 0 { + return nil, fmt.Errorf("messages[%d]: assistant message contains tool results", i) } - output["tools"] = tools - put(output, "tool_choice", encodeAnthropicToolChoice(request.ToolChoice)) + encoded := map[string]any{"role": "assistant", "content": nil} + if len(content) > 0 { + encoded["content"] = encodeChatBlocks(content) + } + if len(calls) > 0 { + toolCalls := make([]any, 0, len(calls)) + for _, call := range calls { + if call.ID == "" || call.Name == "" { + return nil, fmt.Errorf("messages[%d]: tool call must contain id and name", i) + } + if pending[call.ID] { + return nil, fmt.Errorf("messages[%d]: duplicate tool call id %q", i, call.ID) + } + pending[call.ID] = true + pendingOrder = append(pendingOrder, call.ID) + toolCalls = append(toolCalls, map[string]any{ + "id": call.ID, + "type": "function", + "function": map[string]any{ + "name": call.Name, + "arguments": bridgeArgumentsJSON(call), + }, + }) + } + encoded["tool_calls"] = toolCalls + } + if len(content) > 0 || len(calls) > 0 { + messages = append(messages, encoded) + } + continue + } + + if len(calls) > 0 { + return nil, fmt.Errorf("messages[%d]: user message contains tool calls", i) + } + for _, result := range results { + if _, duplicate := pendingResults[result.CallID]; duplicate { + return nil, fmt.Errorf("messages[%d]: duplicate tool result %q", i, result.CallID) + } + if !pending[result.CallID] { + return nil, fmt.Errorf("messages[%d]: tool result %q has no pending tool call", i, result.CallID) + } + pendingResults[result.CallID] = result + delete(pending, result.CallID) + } + if len(content) > 0 { + if len(pendingOrder) > 0 || len(deferred) > 0 { + deferred = append(deferred, content) + } else { + messages = append(messages, map[string]any{"role": "user", "content": encodeChatBlocks(content)}) + } + } + if len(pending) == 0 && len(pendingOrder) > 0 { + for _, id := range pendingOrder { + result := pendingResults[id] + messages = append(messages, map[string]any{ + "role": "tool", + "tool_call_id": id, + "content": bridgeToolResultContent(result.Result), + }) + } + flushDeferred() + pendingOrder = nil + clear(pendingResults) + } + } + if len(pending) > 0 { + return nil, fmt.Errorf("tool calls are missing results for %s", strings.Join(missingToolIDs(pendingOrder, pending), ", ")) + } + flushDeferred() + output["messages"] = messages + + if len(request.Tools) > 0 { + tools := make([]any, 0, len(request.Tools)) + for _, tool := range request.Tools { + function := map[string]any{ + "name": tool.Name, + "description": tool.Description, + "parameters": schemaOrDefault(tool.Schema), + } + if tool.Strict { + function["strict"] = true + } + tools = append(tools, map[string]any{"type": "function", "function": function}) + } + output["tools"] = tools + if choice := encodeChatToolChoice(request.ToolChoice); choice != nil { + output["tool_choice"] = choice + } + } + return output, nil +} + +func missingToolIDs(order []string, pending map[string]bool) []string { + missing := make([]string, 0, len(pending)) + for _, id := range order { + if pending[id] { + missing = append(missing, id) + } + } + if len(missing) == len(pending) { + return missing + } + for id := range pending { + found := false + for _, current := range missing { + if current == id { + found = true + break + } + } + if !found { + missing = append(missing, id) + } + } + sort.Strings(missing) + return missing +} + +func encodeResponsesRequest(request bridgeRequest) map[string]any { + output := map[string]any{"model": request.Model, "stream": request.Stream} + put(output, "temperature", request.Temperature) + put(output, "top_p", request.TopP) + put(output, "max_output_tokens", request.MaxTokens) + put(output, "stop", request.Stop) + put(output, "metadata", request.Metadata) + if len(request.System) > 0 { + output["instructions"] = bridgeBlocksText(request.System) + } + if request.Reasoning != nil { + switch value := request.Reasoning.(type) { + case string: + output["reasoning"] = map[string]any{"effort": value} + default: + output["reasoning"] = value + } + } + + items := make([]any, 0, len(request.Messages)) + for _, message := range request.Messages { + var content []any + flushContent := func() { + if len(content) == 0 { + return + } + items = append(items, map[string]any{ + "type": "message", + "role": normalizeResponsesRole(message.Role), + "content": content, + }) + content = nil + } + for _, block := range message.Blocks { + switch block.Kind { + case "text": + kind := "input_text" + if message.Role == "assistant" { + kind = "output_text" + } + content = append(content, map[string]any{"type": kind, "text": block.Text}) + case "image": + url := block.URL + if url == "" && block.Data != "" { + url = "data:" + block.MediaType + ";base64," + block.Data + } + content = append(content, map[string]any{"type": "input_image", "image_url": url}) + case "tool_call": + flushContent() + items = append(items, map[string]any{ + "type": "function_call", + "call_id": block.ID, + "name": block.Name, + "arguments": bridgeArgumentsJSON(block), + }) + case "tool_result": + flushContent() + items = append(items, map[string]any{ + "type": "function_call_output", + "call_id": block.CallID, + "output": bridgeToolResultContent(block.Result), + }) + } + } + flushContent() + } + output["input"] = items + if len(request.Tools) > 0 { + tools := make([]any, 0, len(request.Tools)) + for _, tool := range request.Tools { + tools = append(tools, map[string]any{ + "type": "function", + "name": tool.Name, + "description": tool.Description, + "parameters": schemaOrDefault(tool.Schema), + "strict": tool.Strict, + }) + } + output["tools"] = tools + if choice := encodeResponsesToolChoice(request.ToolChoice); choice != nil { + output["tool_choice"] = choice } } return output } -func decodeOpenAIContent(value any) []canonicalBlock { +func encodeAnthropicRequest(request bridgeRequest) map[string]any { + output := map[string]any{"model": request.Model, "stream": request.Stream} + put(output, "temperature", request.Temperature) + put(output, "top_p", request.TopP) + put(output, "stop_sequences", request.Stop) + if request.MaxTokens == nil { + output["max_tokens"] = 4096 + } else { + output["max_tokens"] = request.MaxTokens + } + if effort := reasoningEffort(request.Reasoning); effort != nil { + output["effort"] = effort + } + if len(request.System) > 0 { + output["system"] = encodeAnthropicBlocks(request.System) + } + + messages := make([]any, 0, len(request.Messages)) + for _, message := range request.Messages { + content := encodeAnthropicBlocks(message.Blocks) + if len(content) == 0 { + continue + } + role := "user" + if message.Role == "assistant" { + role = "assistant" + } + if len(messages) > 0 { + last, _ := messages[len(messages)-1].(map[string]any) + if stringAt(last, "role") == role { + last["content"] = append(asSlice(last["content"]), content...) + continue + } + } + messages = append(messages, map[string]any{"role": role, "content": content}) + } + output["messages"] = messages + if len(request.Tools) > 0 { + tools := make([]any, 0, len(request.Tools)) + for _, tool := range request.Tools { + tools = append(tools, map[string]any{ + "name": tool.Name, + "description": tool.Description, + "input_schema": schemaOrDefault(tool.Schema), + }) + } + output["tools"] = tools + if choice := encodeAnthropicToolChoice(request.ToolChoice); choice != nil { + output["tool_choice"] = choice + } + } + return output +} + +func decodeOpenAIBlocks(value any) []bridgeBlock { switch value := value.(type) { case string: if value == "" { return nil } - return []canonicalBlock{{Type: "text", Text: value}} + return []bridgeBlock{{Kind: "text", Text: value}} + case map[string]any: + return decodeOpenAIBlocks([]any{value}) case []any: - var blocks []canonicalBlock + blocks := make([]bridgeBlock, 0, len(value)) for _, raw := range value { part, _ := raw.(map[string]any) switch stringAt(part, "type") { case "text", "input_text", "output_text": - blocks = append(blocks, canonicalBlock{Type: "text", Text: stringAt(part, "text")}) + blocks = append(blocks, bridgeBlock{Kind: "text", Text: stringAt(part, "text")}) case "image_url": - blocks = append(blocks, canonicalBlock{Type: "image", URL: stringAt(part, "image_url", "url")}) + blocks = append(blocks, bridgeBlock{Kind: "image", URL: firstString(stringAt(part, "image_url", "url"), stringAt(part, "image_url"))}) case "input_image": - blocks = append(blocks, canonicalBlock{Type: "image", URL: stringAt(part, "image_url")}) + blocks = append(blocks, bridgeBlock{Kind: "image", URL: stringAt(part, "image_url")}) } } return blocks - case map[string]any: - return decodeOpenAIContent([]any{value}) default: return nil } } -func decodeAnthropicContent(value any) []canonicalBlock { +func decodeAnthropicBlocks(value any) []bridgeBlock { if text, ok := value.(string); ok { - return []canonicalBlock{{Type: "text", Text: text}} + if text == "" { + return nil + } + return []bridgeBlock{{Kind: "text", Text: text}} } - var blocks []canonicalBlock + var blocks []bridgeBlock for _, raw := range asSlice(value) { part, _ := raw.(map[string]any) switch stringAt(part, "type") { case "text": - blocks = append(blocks, canonicalBlock{Type: "text", Text: stringAt(part, "text")}) + blocks = append(blocks, bridgeBlock{Kind: "text", Text: stringAt(part, "text")}) case "image": - source, _ := part["source"].(map[string]any) + source := mapAt(part, "source") if stringAt(source, "type") == "url" { - blocks = append(blocks, canonicalBlock{Type: "image", URL: stringAt(source, "url")}) + blocks = append(blocks, bridgeBlock{Kind: "image", URL: stringAt(source, "url")}) } else { - blocks = append(blocks, canonicalBlock{Type: "image", Media: stringAt(source, "media_type"), Data: stringAt(source, "data")}) + blocks = append(blocks, bridgeBlock{Kind: "image", MediaType: stringAt(source, "media_type"), Data: stringAt(source, "data")}) } case "tool_use": - blocks = append(blocks, canonicalBlock{Type: "tool_use", ID: stringAt(part, "id"), Name: stringAt(part, "name"), Input: part["input"]}) + blocks = append(blocks, bridgeBlock{ + Kind: "tool_call", + ID: stringAt(part, "id"), + Name: stringAt(part, "name"), + Arguments: part["input"], + }) case "tool_result": - blocks = append(blocks, canonicalBlock{Type: "tool_result", ToolID: stringAt(part, "tool_use_id"), Content: part["content"], IsError: boolAt(part, "is_error")}) + blocks = append(blocks, bridgeBlock{ + Kind: "tool_result", + CallID: stringAt(part, "tool_use_id"), + Result: part["content"], + IsError: boolAt(part, "is_error"), + }) } } return blocks } -func encodeChatMessages(message canonicalMessage) []any { - out := map[string]any{"role": normalizeChatRole(message.Role)} - var content []canonicalBlock - var toolCalls []any - var results []any - for _, block := range message.Blocks { - switch block.Type { - case "tool_use": - args, _ := json.Marshal(block.Input) - toolCalls = append(toolCalls, map[string]any{"id": block.ID, "type": "function", "function": map[string]any{"name": block.Name, "arguments": string(args)}}) - case "tool_result": - results = append(results, map[string]any{"role": "tool", "tool_call_id": block.ToolID, "content": contentString(block.Content)}) - default: - content = append(content, block) - } - } - if len(content) > 0 { - out["content"] = encodeChatContent(content) - } else { - out["content"] = nil - } - if len(toolCalls) > 0 { - out["tool_calls"] = toolCalls - } - messages := make([]any, 0, len(results)+1) - if len(content) > 0 || len(toolCalls) > 0 { - messages = append(messages, out) - } - messages = append(messages, results...) - return messages -} - -// normalizeChatToolMessages adapts tool history to the stricter ordering used -// by OpenAI-compatible Chat APIs. Anthropic clients can put tool results and -// text in one user message, while persisted or compacted agent histories may -// spread parallel results across multiple messages. Chat requires every -// assistant tool_calls message to be followed immediately by all matching tool -// messages. -// -// Results are paired globally by tool_call_id and emitted in call order. Tool -// calls without a result are removed from converted history, because forwarding -// an unresolved historical call makes the entire request invalid. An orphaned -// result is retained as ordinary user content instead of an invalid tool -// message. -func normalizeChatToolMessages(messages []any) []any { - type toolResult struct { - message map[string]any - used bool - } - type toolPair struct { - call any - result *toolResult - } - - resultsByID := make(map[string][]*toolResult) - resultAt := make(map[int]*toolResult) - for i, raw := range messages { - message, _ := raw.(map[string]any) - if stringAt(message, "role") != "tool" { - continue - } - result := &toolResult{message: message} - resultAt[i] = result - if id := stringAt(message, "tool_call_id"); id != "" { - resultsByID[id] = append(resultsByID[id], result) - } - } - - pairsAt := make(map[int][]toolPair) - toolCallAt := make(map[int]bool) - for i, raw := range messages { - message, _ := raw.(map[string]any) - calls := sliceAt(message, "tool_calls") - if stringAt(message, "role") != "assistant" || len(calls) == 0 { - continue - } - toolCallAt[i] = true - for _, rawCall := range calls { - call, _ := rawCall.(map[string]any) - id := stringAt(call, "id") - for _, result := range resultsByID[id] { - if result.used { - continue - } - result.used = true - pairsAt[i] = append(pairsAt[i], toolPair{call: rawCall, result: result}) - break - } - } - } - - out := make([]any, 0, len(messages)) - for i, raw := range messages { - if result := resultAt[i]; result != nil { - if !result.used { - out = append(out, map[string]any{ - "role": "user", - "content": contentString(result.message["content"]), - }) - } - continue - } - if !toolCallAt[i] { - out = append(out, raw) - continue - } - - message, _ := raw.(map[string]any) - converted := make(map[string]any, len(message)) - for key, value := range message { - converted[key] = value - } - pairs := pairsAt[i] - if len(pairs) == 0 { - delete(converted, "tool_calls") - if hasChatContent(converted["content"]) { - out = append(out, converted) - } - continue - } - - calls := make([]any, 0, len(pairs)) - for _, pair := range pairs { - calls = append(calls, pair.call) - } - converted["tool_calls"] = calls - out = append(out, converted) - for _, pair := range pairs { - out = append(out, pair.result.message) - } - } - return out -} - -func hasChatContent(value any) bool { - switch value := value.(type) { - case nil: - return false - case string: - return strings.TrimSpace(value) != "" - case []any: - return len(value) > 0 - default: - return true - } -} - -func encodeChatContent(blocks []canonicalBlock) any { - if len(blocks) == 1 && blocks[0].Type == "text" { +func encodeChatBlocks(blocks []bridgeBlock) any { + if len(blocks) == 1 && blocks[0].Kind == "text" { return blocks[0].Text } parts := make([]any, 0, len(blocks)) for _, block := range blocks { - switch block.Type { + switch block.Kind { case "text": parts = append(parts, map[string]any{"type": "text", "text": block.Text}) case "image": url := block.URL if url == "" && block.Data != "" { - url = "data:" + block.Media + ";base64," + block.Data + url = "data:" + block.MediaType + ";base64," + block.Data } parts = append(parts, map[string]any{"type": "image_url", "image_url": map[string]any{"url": url}}) } @@ -490,71 +668,165 @@ func encodeChatContent(blocks []canonicalBlock) any { return parts } -func encodeResponsesMessage(message canonicalMessage) []any { - var output []any - var content []any - for _, block := range message.Blocks { - switch block.Type { - case "text": - kind := "input_text" - if message.Role == "assistant" { - kind = "output_text" - } - content = append(content, map[string]any{"type": kind, "text": block.Text}) - case "image": - url := block.URL - if url == "" { - url = "data:" + block.Media + ";base64," + block.Data - } - content = append(content, map[string]any{"type": "input_image", "image_url": url}) - case "tool_use": - args, _ := json.Marshal(block.Input) - output = append(output, map[string]any{"type": "function_call", "call_id": block.ID, "name": block.Name, "arguments": string(args)}) - case "tool_result": - output = append(output, map[string]any{"type": "function_call_output", "call_id": block.ToolID, "output": contentString(block.Content)}) - } - } - if len(content) > 0 { - output = append([]any{map[string]any{"role": normalizeResponsesRole(message.Role), "content": content}}, output...) - } - return output -} - -func encodeAnthropicContent(blocks []canonicalBlock) []any { +func encodeAnthropicBlocks(blocks []bridgeBlock) []any { parts := make([]any, 0, len(blocks)) for _, block := range blocks { - switch block.Type { + switch block.Kind { case "text": parts = append(parts, map[string]any{"type": "text", "text": block.Text}) case "image": if block.URL != "" { parts = append(parts, map[string]any{"type": "image", "source": map[string]any{"type": "url", "url": block.URL}}) } else { - parts = append(parts, map[string]any{"type": "image", "source": map[string]any{"type": "base64", "media_type": block.Media, "data": block.Data}}) + parts = append(parts, map[string]any{"type": "image", "source": map[string]any{"type": "base64", "media_type": block.MediaType, "data": block.Data}}) } - case "tool_use": - parts = append(parts, map[string]any{"type": "tool_use", "id": block.ID, "name": block.Name, "input": block.Input}) + case "tool_call": + input := block.Arguments + if input == nil { + input = parseJSONOrString(block.ArgumentsJSON) + } + parts = append(parts, map[string]any{"type": "tool_use", "id": block.ID, "name": block.Name, "input": input}) case "tool_result": - parts = append(parts, map[string]any{"type": "tool_result", "tool_use_id": block.ToolID, "content": block.Content, "is_error": block.IsError}) + parts = append(parts, map[string]any{"type": "tool_result", "tool_use_id": block.CallID, "content": block.Result, "is_error": block.IsError}) } } return parts } +func bridgeArgumentsJSON(block bridgeBlock) string { + if block.ArgumentsJSON != "" { + return block.ArgumentsJSON + } + if block.Arguments == nil { + return "{}" + } + data, err := json.Marshal(block.Arguments) + if err != nil { + return "{}" + } + return string(data) +} + +func bridgeToolResultContent(value any) string { + if text, ok := value.(string); ok { + return text + } + if parts, ok := value.([]any); ok { + var text strings.Builder + allText := true + for _, raw := range parts { + part, ok := raw.(map[string]any) + if !ok || stringAt(part, "type") != "text" { + allText = false + break + } + text.WriteString(stringAt(part, "text")) + } + if allText { + return text.String() + } + } + data, err := json.Marshal(value) + if err != nil { + return "" + } + return string(data) +} + +func decodeChatToolChoice(value any) bridgeToolChoice { + if mode, ok := value.(string); ok { + return bridgeToolChoice{Mode: mode} + } + choice, _ := value.(map[string]any) + if stringAt(choice, "type") == "function" { + return bridgeToolChoice{Mode: "named", Name: stringAt(choice, "function", "name")} + } + return bridgeToolChoice{} +} + +func decodeResponsesToolChoice(value any) bridgeToolChoice { + if mode, ok := value.(string); ok { + return bridgeToolChoice{Mode: mode} + } + choice, _ := value.(map[string]any) + if stringAt(choice, "type") == "function" { + return bridgeToolChoice{Mode: "named", Name: stringAt(choice, "name")} + } + return bridgeToolChoice{} +} + +func decodeAnthropicToolChoice(value any) bridgeToolChoice { + choice, _ := value.(map[string]any) + switch stringAt(choice, "type") { + case "auto": + return bridgeToolChoice{Mode: "auto"} + case "none": + return bridgeToolChoice{Mode: "none"} + case "any": + return bridgeToolChoice{Mode: "required"} + case "tool": + return bridgeToolChoice{Mode: "named", Name: stringAt(choice, "name")} + default: + return bridgeToolChoice{} + } +} + +func encodeChatToolChoice(choice bridgeToolChoice) any { + switch choice.Mode { + case "named": + return map[string]any{"type": "function", "function": map[string]any{"name": choice.Name}} + case "auto", "none", "required": + return choice.Mode + default: + return nil + } +} + +func encodeResponsesToolChoice(choice bridgeToolChoice) any { + switch choice.Mode { + case "named": + return map[string]any{"type": "function", "name": choice.Name} + case "auto", "none", "required": + return choice.Mode + default: + return nil + } +} + +func encodeAnthropicToolChoice(choice bridgeToolChoice) any { + switch choice.Mode { + case "named": + return map[string]any{"type": "tool", "name": choice.Name} + case "required": + return map[string]any{"type": "any"} + case "auto", "none": + return map[string]any{"type": choice.Mode} + default: + return nil + } +} + func convertResponse(from, to Protocol, body []byte) ([]byte, error) { + if from == to { + return append([]byte(nil), body...), nil + } var input map[string]any if err := json.Unmarshal(body, &input); err != nil { return nil, err } - response, err := decodeResponse(from, input) + response, err := decodeBridgeResponse(from, input) if err != nil { return nil, err } - return json.Marshal(encodeResponse(to, response)) + return json.Marshal(encodeBridgeResponse(to, response)) } -func decodeResponse(protocol Protocol, input map[string]any) (canonicalResponse, error) { - response := canonicalResponse{ID: stringAt(input, "id"), Model: stringAt(input, "model"), Created: int64At(input, "created")} +func decodeBridgeResponse(protocol Protocol, input map[string]any) (bridgeResponse, error) { + response := bridgeResponse{ + ID: stringAt(input, "id"), + Model: stringAt(input, "model"), + Created: int64At(input, "created"), + } if response.Created == 0 { response.Created = int64At(input, "created_at") } @@ -565,15 +837,20 @@ func decodeResponse(protocol Protocol, input map[string]any) (canonicalResponse, case ProtocolChat: choices := sliceAt(input, "choices") if len(choices) == 0 { - return response, fmt.Errorf("chat response has no choices") + return response, fmt.Errorf("chat response contains no choices") } choice, _ := choices[0].(map[string]any) - message, _ := choice["message"].(map[string]any) - response.Text = blocksText(decodeOpenAIContent(message["content"])) + message := mapAt(choice, "message") + response.Text = bridgeBlocksText(decodeOpenAIBlocks(message["content"])) for _, raw := range sliceAt(message, "tool_calls") { call, _ := raw.(map[string]any) - fn, _ := call["function"].(map[string]any) - response.Tools = append(response.Tools, canonicalBlock{Type: "tool_use", ID: stringAt(call, "id"), Name: stringAt(fn, "name"), Input: parseJSONOrString(stringAt(fn, "arguments"))}) + function := mapAt(call, "function") + response.Tools = append(response.Tools, bridgeBlock{ + Kind: "tool_call", + ID: stringAt(call, "id"), + Name: stringAt(function, "name"), + ArgumentsJSON: stringAt(function, "arguments"), + }) } response.Stop = stringAt(choice, "finish_reason") response.Usage = decodeOpenAIUsage(mapAt(input, "usage")) @@ -582,33 +859,41 @@ func decodeResponse(protocol Protocol, input map[string]any) (canonicalResponse, item, _ := raw.(map[string]any) switch stringAt(item, "type") { case "message": - response.Text += blocksText(decodeOpenAIContent(item["content"])) + response.Text += bridgeBlocksText(decodeOpenAIBlocks(item["content"])) case "function_call": - response.Tools = append(response.Tools, canonicalBlock{Type: "tool_use", ID: stringAt(item, "call_id"), Name: stringAt(item, "name"), Input: parseJSONOrString(stringAt(item, "arguments"))}) + response.Tools = append(response.Tools, bridgeBlock{ + Kind: "tool_call", + ID: firstString(stringAt(item, "call_id"), stringAt(item, "id")), + Name: stringAt(item, "name"), + ArgumentsJSON: stringAt(item, "arguments"), + }) } } response.Stop = "stop" if len(response.Tools) > 0 { response.Stop = "tool_calls" } + if stringAt(input, "status") == "incomplete" { + response.Stop = "length" + } response.Usage = decodeOpenAIUsage(mapAt(input, "usage")) case ProtocolAnthropic: - for _, block := range decodeAnthropicContent(input["content"]) { - if block.Type == "text" { + for _, block := range decodeAnthropicBlocks(input["content"]) { + if block.Kind == "text" { response.Text += block.Text - } else if block.Type == "tool_use" { + } else if block.Kind == "tool_call" { response.Tools = append(response.Tools, block) } } response.Stop = stringAt(input, "stop_reason") response.Usage = decodeAnthropicUsage(mapAt(input, "usage")) default: - return response, fmt.Errorf("unsupported response protocol") + return response, fmt.Errorf("unsupported response protocol %q", protocol) } return response, nil } -func encodeResponse(protocol Protocol, response canonicalResponse) map[string]any { +func encodeBridgeResponse(protocol Protocol, response bridgeResponse) map[string]any { if response.ID == "" { response.ID = randomID("resp", 12) } @@ -618,138 +903,159 @@ func encodeResponse(protocol Protocol, response canonicalResponse) map[string]an if len(response.Tools) > 0 { calls := make([]any, 0, len(response.Tools)) for _, tool := range response.Tools { - args, _ := json.Marshal(tool.Input) - calls = append(calls, map[string]any{"id": tool.ID, "type": "function", "function": map[string]any{"name": tool.Name, "arguments": string(args)}}) + calls = append(calls, map[string]any{ + "id": tool.ID, + "type": "function", + "function": map[string]any{ + "name": tool.Name, + "arguments": bridgeArgumentsJSON(tool), + }, + }) } message["tool_calls"] = calls } - return map[string]any{"id": asPrefix(response.ID, "chatcmpl"), "object": "chat.completion", "created": response.Created, "model": response.Model, "choices": []any{map[string]any{"index": 0, "message": message, "finish_reason": chatStop(response.Stop)}}, "usage": openAIUsage(response.Usage)} + return map[string]any{ + "id": asPrefix(response.ID, "chatcmpl"), + "object": "chat.completion", + "created": response.Created, + "model": response.Model, + "choices": []any{map[string]any{ + "index": 0, + "message": message, + "finish_reason": chatStop(response.Stop), + }}, + "usage": openAIUsage(response.Usage), + } case ProtocolResponses: output := make([]any, 0, len(response.Tools)+1) if response.Text != "" { - output = append(output, map[string]any{"id": randomID("msg", 12), "type": "message", "status": "completed", "role": "assistant", "content": []any{map[string]any{"type": "output_text", "text": response.Text, "annotations": []any{}}}}) + output = append(output, map[string]any{ + "id": randomID("msg", 12), + "type": "message", + "status": "completed", + "role": "assistant", + "content": []any{map[string]any{ + "type": "output_text", + "text": response.Text, + "annotations": []any{}, + }}, + }) } for _, tool := range response.Tools { - args, _ := json.Marshal(tool.Input) - output = append(output, map[string]any{"id": randomID("fc", 12), "type": "function_call", "status": "completed", "call_id": tool.ID, "name": tool.Name, "arguments": string(args)}) + output = append(output, map[string]any{ + "id": randomID("fc", 12), + "type": "function_call", + "status": "completed", + "call_id": tool.ID, + "name": tool.Name, + "arguments": bridgeArgumentsJSON(tool), + }) + } + return map[string]any{ + "id": asPrefix(response.ID, "resp"), + "object": "response", + "created_at": response.Created, + "status": "completed", + "model": response.Model, + "output": output, + "error": nil, + "incomplete_details": nil, + "usage": map[string]any{ + "input_tokens": response.Usage.Input, + "output_tokens": response.Usage.Output, + "total_tokens": response.Usage.Total, + "input_tokens_details": map[string]any{ + "cached_tokens": response.Usage.Cached, + }, + "output_tokens_details": map[string]any{ + "reasoning_tokens": response.Usage.Reasoning, + }, + }, } - return map[string]any{"id": asPrefix(response.ID, "resp"), "object": "response", "created_at": response.Created, "status": "completed", "model": response.Model, "output": output, "usage": map[string]any{"input_tokens": response.Usage.Input, "output_tokens": response.Usage.Output, "total_tokens": response.Usage.Total, "input_tokens_details": map[string]any{"cached_tokens": response.Usage.Cached}, "output_tokens_details": map[string]any{"reasoning_tokens": response.Usage.Reasoning}}, "error": nil, "incomplete_details": nil} case ProtocolAnthropic: - content := []any{} + content := make([]any, 0, len(response.Tools)+1) if response.Text != "" { content = append(content, map[string]any{"type": "text", "text": response.Text}) } for _, tool := range response.Tools { - content = append(content, map[string]any{"type": "tool_use", "id": tool.ID, "name": tool.Name, "input": tool.Input}) + input := tool.Arguments + if input == nil { + input = parseJSONOrString(tool.ArgumentsJSON) + } + content = append(content, map[string]any{"type": "tool_use", "id": tool.ID, "name": tool.Name, "input": input}) } - return map[string]any{"id": asPrefix(response.ID, "msg"), "type": "message", "role": "assistant", "model": response.Model, "content": content, "stop_reason": anthropicStop(response.Stop), "stop_sequence": nil, "usage": map[string]any{"input_tokens": response.Usage.Input, "output_tokens": response.Usage.Output, "cache_read_input_tokens": response.Usage.Cached}} + return map[string]any{ + "id": asPrefix(response.ID, "msg"), + "type": "message", + "role": "assistant", + "model": response.Model, + "content": content, + "stop_reason": anthropicStop(response.Stop), + "stop_sequence": nil, + "usage": map[string]any{ + "input_tokens": response.Usage.Input, + "output_tokens": response.Usage.Output, + "cache_read_input_tokens": response.Usage.Cached, + }, + } + default: + return map[string]any{} } - return map[string]any{} } -func decodeOpenAIUsage(u map[string]any) canonicalUsage { - input := intAt(u, "prompt_tokens") - if input == 0 { - input = intAt(u, "input_tokens") - } - output := intAt(u, "completion_tokens") - if output == 0 { - output = intAt(u, "output_tokens") - } - total := intAt(u, "total_tokens") +func decodeOpenAIUsage(usage map[string]any) bridgeUsage { + input := firstNonZero(intAt(usage, "prompt_tokens"), intAt(usage, "input_tokens")) + output := firstNonZero(intAt(usage, "completion_tokens"), intAt(usage, "output_tokens")) + total := intAt(usage, "total_tokens") if total == 0 { total = input + output } - cached := intAt(u, "prompt_tokens_details", "cached_tokens") - if cached == 0 { - cached = intAt(u, "input_tokens_details", "cached_tokens") - } - reasoning := intAt(u, "completion_tokens_details", "reasoning_tokens") - if reasoning == 0 { - reasoning = intAt(u, "output_tokens_details", "reasoning_tokens") - } - return canonicalUsage{Input: input, Output: output, Total: total, Cached: cached, Reasoning: reasoning} -} -func decodeAnthropicUsage(u map[string]any) canonicalUsage { - input := intAt(u, "input_tokens") - output := intAt(u, "output_tokens") - cached := intAt(u, "cache_read_input_tokens") - return canonicalUsage{Input: input, Output: output, Total: input + output, Cached: cached} -} -func openAIUsage(u canonicalUsage) map[string]any { - return map[string]any{"prompt_tokens": u.Input, "completion_tokens": u.Output, "total_tokens": u.Total, "prompt_tokens_details": map[string]any{"cached_tokens": u.Cached}, "completion_tokens_details": map[string]any{"reasoning_tokens": u.Reasoning}} + cached := firstNonZero(intAt(usage, "prompt_tokens_details", "cached_tokens"), intAt(usage, "input_tokens_details", "cached_tokens")) + reasoning := firstNonZero(intAt(usage, "completion_tokens_details", "reasoning_tokens"), intAt(usage, "output_tokens_details", "reasoning_tokens")) + return bridgeUsage{Input: input, Output: output, Total: total, Cached: cached, Reasoning: reasoning} } -func decodeChatToolChoice(v any) any { - m, _ := v.(map[string]any) - if stringAt(m, "type") == "function" { - return map[string]any{"name": stringAt(m, "function", "name")} +func decodeAnthropicUsage(usage map[string]any) bridgeUsage { + input := intAt(usage, "input_tokens") + output := intAt(usage, "output_tokens") + return bridgeUsage{ + Input: input, + Output: output, + Total: input + output, + Cached: intAt(usage, "cache_read_input_tokens"), } - return v -} -func decodeResponsesToolChoice(v any) any { - m, _ := v.(map[string]any) - if stringAt(m, "type") == "function" { - return map[string]any{"name": stringAt(m, "name")} - } - return v -} -func decodeAnthropicToolChoice(v any) any { - m, _ := v.(map[string]any) - if stringAt(m, "type") == "tool" { - return map[string]any{"name": stringAt(m, "name")} - } - if s := stringAt(m, "type"); s != "" { - return s - } - return v -} -func encodeChatToolChoice(v any) any { - if m, ok := v.(map[string]any); ok { - return map[string]any{"type": "function", "function": map[string]any{"name": stringAt(m, "name")}} - } - return v -} -func encodeResponsesToolChoice(v any) any { - if m, ok := v.(map[string]any); ok { - return map[string]any{"type": "function", "name": stringAt(m, "name")} - } - return v -} -func encodeAnthropicToolChoice(v any) any { - if m, ok := v.(map[string]any); ok { - return map[string]any{"type": "tool", "name": stringAt(m, "name")} - } - if v == "required" { - return map[string]any{"type": "any"} - } - if v == "none" { - return map[string]any{"type": "none"} - } - if v == "auto" { - return map[string]any{"type": "auto"} - } - return v } -func normalizeChatRole(role string) string { - if role == "developer" { - return "system" +func openAIUsage(usage bridgeUsage) map[string]any { + return map[string]any{ + "prompt_tokens": usage.Input, + "completion_tokens": usage.Output, + "total_tokens": usage.Total, + "prompt_tokens_details": map[string]any{ + "cached_tokens": usage.Cached, + }, + "completion_tokens_details": map[string]any{ + "reasoning_tokens": usage.Reasoning, + }, } - return role } + +func firstNonZero(values ...int) int { + for _, value := range values { + if value != 0 { + return value + } + } + return 0 +} + func normalizeResponsesRole(role string) string { - if role == "tool" { - return "user" - } - return role -} -func normalizeAnthropicRole(role string) string { if role == "assistant" { - return role + return "assistant" } return "user" } + func chatStop(stop string) string { switch stop { case "tool_use", "tool_calls": @@ -760,6 +1066,7 @@ func chatStop(stop string) string { return "stop" } } + func anthropicStop(stop string) string { switch stop { case "tool_use", "tool_calls": @@ -770,114 +1077,125 @@ func anthropicStop(stop string) string { return "end_turn" } } -func schemaOrDefault(v any) any { - if v == nil { + +func schemaOrDefault(value any) any { + if value == nil { return map[string]any{"type": "object", "properties": map[string]any{}} } - return v + return value } -func reasoningEffort(v any) any { - if m, ok := v.(map[string]any); ok { - return firstAny(m["effort"], m["type"]) + +func reasoningEffort(value any) any { + if object, ok := value.(map[string]any); ok { + return firstAny(object["effort"], object["type"]) } - return v + return value } -func blocksText(blocks []canonicalBlock) string { - var b strings.Builder + +func bridgeBlocksText(blocks []bridgeBlock) string { + var text strings.Builder for _, block := range blocks { - if block.Type == "text" { - b.WriteString(block.Text) + if block.Kind == "text" { + text.WriteString(block.Text) } } - return b.String() + return text.String() } -func contentString(v any) string { - if s, ok := v.(string); ok { - return s - } - data, _ := json.Marshal(v) - return string(data) -} -func parseJSONOrString(v string) any { - if v == "" { + +func parseJSONOrString(value string) any { + if value == "" { return map[string]any{} } - var out any - if json.Unmarshal([]byte(v), &out) == nil { - return out + var decoded any + if json.Unmarshal([]byte(value), &decoded) == nil { + return decoded } - return v + return value } + func asPrefix(id, prefix string) string { if strings.HasPrefix(id, prefix+"_") { return id } - return prefix + "_" + strings.TrimPrefix(id, "resp_") + for _, current := range []string{"chatcmpl_", "resp_", "msg_"} { + id = strings.TrimPrefix(id, current) + } + return prefix + "_" + id } -func put(m map[string]any, k string, v any) { - if v != nil { - m[k] = v + +func put(object map[string]any, key string, value any) { + if value != nil { + object[key] = value } } + func firstAny(values ...any) any { - for _, v := range values { - if v != nil { - return v + for _, value := range values { + if value != nil { + return value } } return nil } -func cloneMap(in map[string]any) map[string]any { - data, _ := json.Marshal(in) - var out map[string]any - _ = json.Unmarshal(data, &out) - return out + +func cloneMap(input map[string]any) map[string]any { + data, _ := json.Marshal(input) + var output map[string]any + _ = json.Unmarshal(data, &output) + return output } -func asSlice(v any) []any { - if values, ok := v.([]any); ok { + +func asSlice(value any) []any { + if values, ok := value.([]any); ok { return values } - if v == nil { + if value == nil { return nil } - return []any{v} + return []any{value} } -func sliceAt(m map[string]any, path ...string) []any { - v := anyAt(m, path...) - values, _ := v.([]any) + +func sliceAt(object map[string]any, path ...string) []any { + values, _ := anyAt(object, path...).([]any) return values } -func mapAt(m map[string]any, path ...string) map[string]any { - v := anyAt(m, path...) - value, _ := v.(map[string]any) + +func mapAt(object map[string]any, path ...string) map[string]any { + value, _ := anyAt(object, path...).(map[string]any) return value } -func stringAt(m map[string]any, path ...string) string { - v := anyAt(m, path...) - value, _ := v.(string) + +func stringAt(object map[string]any, path ...string) string { + value, _ := anyAt(object, path...).(string) return value } -func boolAt(m map[string]any, path ...string) bool { - v := anyAt(m, path...) - value, _ := v.(bool) + +func boolAt(object map[string]any, path ...string) bool { + value, _ := anyAt(object, path...).(bool) return value } -func intAt(m map[string]any, path ...string) int { - v := anyAt(m, path...) - switch n := v.(type) { + +func intAt(object map[string]any, path ...string) int { + value := anyAt(object, path...) + switch number := value.(type) { case float64: - return int(n) + return int(number) case int: - return n + return number case json.Number: - i, _ := n.Int64() - return int(i) + integer, _ := number.Int64() + return int(integer) + default: + return 0 } - return 0 } -func int64At(m map[string]any, path ...string) int64 { return int64(intAt(m, path...)) } -func anyAt(m map[string]any, path ...string) any { - var current any = m + +func int64At(object map[string]any, path ...string) int64 { + return int64(intAt(object, path...)) +} + +func anyAt(object map[string]any, path ...string) any { + var current any = object for _, key := range path { next, ok := current.(map[string]any) if !ok { diff --git a/gateway.go b/gateway.go index def8330..8abc269 100644 --- a/gateway.go +++ b/gateway.go @@ -344,6 +344,14 @@ func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, body []byte, g.logger.Debug("upstream accepted request", "request_id", ids.Request, "attempt", attempt, "tier", route.Tier, "proxy", redactURL(proxy.name)) return resp, nil } + // Request-shape errors are deterministic and must be returned to the + // caller without rotating through unrelated keys. Authentication, + // throttling, server, and transport failures remain retryable. + if err == nil && resp.StatusCode >= 400 && resp.StatusCode < 500 && resp.StatusCode != http.StatusUnauthorized && resp.StatusCode != http.StatusForbidden && resp.StatusCode != http.StatusTooManyRequests { + nodes.MarkSuccess(node) + g.logger.Debug("upstream rejected request without retry", "request_id", ids.Request, "attempt", attempt, "status", resp.StatusCode, "proxy", redactURL(proxy.name)) + return resp, nil + } if proxyFailed { if nodes.Proxy(node) == proxy { nodes.MarkFailure(node, resp, err) diff --git a/models.go b/models.go index 006d725..dc43b04 100644 --- a/models.go +++ b/models.go @@ -166,7 +166,7 @@ func inferProtocol(model string) Protocol { return ProtocolAnthropic } } - for _, prefix := range []string{"gpt-", "o1", "o3", "o4", "grok-"} { + for _, prefix := range []string{"gpt-", "o1", "o3", "o4", "grok-", "muse-"} { if strings.HasPrefix(m, prefix) { return ProtocolResponses } diff --git a/stream.go b/stream.go index b568110..f5c0599 100644 --- a/stream.go +++ b/stream.go @@ -10,31 +10,37 @@ import ( "time" ) -type streamEvent struct { - Kind string - ID string - Model string - Text string - Key string - ToolID string - Name string - Stop string - Usage *canonicalUsage +type bridgeStreamEvent struct { + Kind string + ResponseID string + Model string + Text string + ToolKey string + ToolID string + ToolName string + Stop string + Usage *bridgeUsage } -type streamParser struct { - protocol Protocol - toolSeen map[string]bool +type bridgeStreamParser struct { + protocol Protocol + started bool + tools map[string]bool + responseArgs map[string]bool } -func transcodeStream(w http.ResponseWriter, r io.Reader, from, to Protocol, model string) error { +func transcodeStream(w http.ResponseWriter, reader io.Reader, from, to Protocol, model string) error { flusher, ok := w.(http.Flusher) if !ok { return fmt.Errorf("response writer does not support streaming") } - parser := &streamParser{protocol: from, toolSeen: map[string]bool{}} - emitter := newStreamEmitter(w, flusher, to, model) - err := readSSE(r, func(eventName, data string) error { + parser := &bridgeStreamParser{ + protocol: from, + tools: map[string]bool{}, + responseArgs: map[string]bool{}, + } + emitter := newBridgeStreamEmitter(w, flusher, to, model) + if err := readSSE(reader, func(eventName, data string) error { events, err := parser.Parse(eventName, data) if err != nil { return err @@ -45,26 +51,25 @@ func transcodeStream(w http.ResponseWriter, r io.Reader, from, to Protocol, mode } } return nil - }) - if err != nil { + }); err != nil { return err } return emitter.Finish() } -func readSSE(r io.Reader, fn func(eventName, data string) error) error { - scanner := bufio.NewScanner(r) +func readSSE(reader io.Reader, handler func(eventName, data string) error) error { + scanner := bufio.NewScanner(reader) scanner.Buffer(make([]byte, 64<<10), 16<<20) var eventName string - var data []string + var dataLines []string flush := func() error { - if len(data) == 0 { + if len(dataLines) == 0 { eventName = "" return nil } - err := fn(eventName, strings.Join(data, "\n")) + err := handler(eventName, strings.Join(dataLines, "\n")) eventName = "" - data = data[:0] + dataLines = dataLines[:0] return err } for scanner.Scan() { @@ -75,11 +80,15 @@ func readSSE(r io.Reader, fn func(eventName, data string) error) error { } continue } + if strings.HasPrefix(line, ":") { + continue + } if strings.HasPrefix(line, "event:") { eventName = strings.TrimSpace(strings.TrimPrefix(line, "event:")) + continue } if strings.HasPrefix(line, "data:") { - data = append(data, strings.TrimSpace(strings.TrimPrefix(line, "data:"))) + dataLines = append(dataLines, strings.TrimSpace(strings.TrimPrefix(line, "data:"))) } } if err := scanner.Err(); err != nil { @@ -88,172 +97,233 @@ func readSSE(r io.Reader, fn func(eventName, data string) error) error { return flush() } -func (p *streamParser) Parse(eventName, data string) ([]streamEvent, error) { +func (parser *bridgeStreamParser) Parse(eventName, data string) ([]bridgeStreamEvent, error) { if data == "[DONE]" { - return []streamEvent{{Kind: "done"}}, nil + return []bridgeStreamEvent{{Kind: "done"}}, nil } var value map[string]any if err := json.Unmarshal([]byte(data), &value); err != nil { return nil, fmt.Errorf("invalid upstream SSE JSON: %w", err) } - switch p.protocol { + switch parser.protocol { case ProtocolChat: - return p.parseChat(value), nil + return parser.parseChat(value), nil case ProtocolAnthropic: - return p.parseAnthropic(value), nil + return parser.parseAnthropic(value) case ProtocolResponses: - return p.parseResponses(eventName, value), nil + return parser.parseResponses(eventName, value), nil default: - return nil, fmt.Errorf("unsupported stream protocol %q", p.protocol) + return nil, fmt.Errorf("unsupported stream protocol %q", parser.protocol) } } -func (p *streamParser) parseChat(v map[string]any) []streamEvent { - var events []streamEvent - if id := stringAt(v, "id"); id != "" { - events = append(events, streamEvent{Kind: "start", ID: id, Model: stringAt(v, "model")}) +func (parser *bridgeStreamParser) parseChat(value map[string]any) []bridgeStreamEvent { + events := make([]bridgeStreamEvent, 0, 4) + if !parser.started { + if id := stringAt(value, "id"); id != "" { + parser.started = true + events = append(events, bridgeStreamEvent{Kind: "start", ResponseID: id, Model: stringAt(value, "model")}) + } } - if usageMap := mapAt(v, "usage"); len(usageMap) > 0 { + if usageMap := mapAt(value, "usage"); len(usageMap) > 0 { usage := decodeOpenAIUsage(usageMap) - events = append(events, streamEvent{Kind: "usage", Usage: &usage}) + events = append(events, bridgeStreamEvent{Kind: "usage", Usage: &usage}) } - for _, raw := range sliceAt(v, "choices") { + for _, raw := range sliceAt(value, "choices") { choice, _ := raw.(map[string]any) delta := mapAt(choice, "delta") if text := stringAt(delta, "content"); text != "" { - events = append(events, streamEvent{Kind: "text", Text: text}) + events = append(events, bridgeStreamEvent{Kind: "text", Text: text}) } for _, rawCall := range sliceAt(delta, "tool_calls") { call, _ := rawCall.(map[string]any) key := fmt.Sprint(firstAny(call["index"], stringAt(call, "id"))) - fn := mapAt(call, "function") - if !p.toolSeen[key] { - p.toolSeen[key] = true - events = append(events, streamEvent{Kind: "tool_start", Key: key, ToolID: stringAt(call, "id"), Name: stringAt(fn, "name")}) + function := mapAt(call, "function") + id := stringAt(call, "id") + name := stringAt(function, "name") + if !parser.tools[key] { + parser.tools[key] = true + events = append(events, bridgeStreamEvent{Kind: "tool_start", ToolKey: key, ToolID: id, ToolName: name}) } - if args := stringAt(fn, "arguments"); args != "" { - events = append(events, streamEvent{Kind: "tool_delta", Key: key, Text: args}) + if arguments := stringAt(function, "arguments"); arguments != "" { + events = append(events, bridgeStreamEvent{Kind: "tool_delta", ToolKey: key, ToolID: id, ToolName: name, Text: arguments}) } } if stop := stringAt(choice, "finish_reason"); stop != "" { - events = append(events, streamEvent{Kind: "finish", Stop: stop}) + events = append(events, bridgeStreamEvent{Kind: "finish", Stop: stop}) } } return events } -func (p *streamParser) parseAnthropic(v map[string]any) []streamEvent { - typeName := stringAt(v, "type") - switch typeName { +func (parser *bridgeStreamParser) parseAnthropic(value map[string]any) ([]bridgeStreamEvent, error) { + switch stringAt(value, "type") { case "message_start": - message := mapAt(v, "message") - events := []streamEvent{{Kind: "start", ID: stringAt(message, "id"), Model: stringAt(message, "model")}} + message := mapAt(value, "message") + events := []bridgeStreamEvent{{Kind: "start", ResponseID: stringAt(message, "id"), Model: stringAt(message, "model")}} if usageMap := mapAt(message, "usage"); len(usageMap) > 0 { usage := decodeAnthropicUsage(usageMap) - events = append(events, streamEvent{Kind: "usage", Usage: &usage}) + events = append(events, bridgeStreamEvent{Kind: "usage", Usage: &usage}) } - return events + return events, nil case "content_block_start": - block := mapAt(v, "content_block") - key := fmt.Sprint(v["index"]) - if stringAt(block, "type") == "tool_use" { - return []streamEvent{{Kind: "tool_start", Key: key, ToolID: stringAt(block, "id"), Name: stringAt(block, "name")}} + block := mapAt(value, "content_block") + key := fmt.Sprint(value["index"]) + switch stringAt(block, "type") { + case "tool_use": + parser.tools[key] = true + return []bridgeStreamEvent{{Kind: "tool_start", ToolKey: key, ToolID: stringAt(block, "id"), ToolName: stringAt(block, "name")}}, nil + case "text": + if text := stringAt(block, "text"); text != "" { + return []bridgeStreamEvent{{Kind: "text", Text: text}}, nil + } } - return nil case "content_block_delta": - delta := mapAt(v, "delta") - key := fmt.Sprint(v["index"]) - if stringAt(delta, "type") == "input_json_delta" { - return []streamEvent{{Kind: "tool_delta", Key: key, Text: stringAt(delta, "partial_json")}} - } - if stringAt(delta, "type") == "text_delta" { - return []streamEvent{{Kind: "text", Text: stringAt(delta, "text")}} + delta := mapAt(value, "delta") + key := fmt.Sprint(value["index"]) + switch stringAt(delta, "type") { + case "text_delta": + return []bridgeStreamEvent{{Kind: "text", Text: stringAt(delta, "text")}}, nil + case "input_json_delta": + return []bridgeStreamEvent{{Kind: "tool_delta", ToolKey: key, Text: stringAt(delta, "partial_json")}}, nil } case "message_delta": - var events []streamEvent - if usageMap := mapAt(v, "usage"); len(usageMap) > 0 { + events := make([]bridgeStreamEvent, 0, 2) + if usageMap := mapAt(value, "usage"); len(usageMap) > 0 { usage := decodeAnthropicUsage(usageMap) - events = append(events, streamEvent{Kind: "usage", Usage: &usage}) + events = append(events, bridgeStreamEvent{Kind: "usage", Usage: &usage}) } - if stop := stringAt(v, "delta", "stop_reason"); stop != "" { - events = append(events, streamEvent{Kind: "finish", Stop: stop}) + if stop := stringAt(value, "delta", "stop_reason"); stop != "" { + events = append(events, bridgeStreamEvent{Kind: "finish", Stop: stop}) } - return events + return events, nil case "message_stop": - return []streamEvent{{Kind: "done"}} + return []bridgeStreamEvent{{Kind: "done"}}, nil case "error": - return []streamEvent{{Kind: "finish", Stop: "error"}, {Kind: "done"}} + message := firstString(stringAt(value, "error", "message"), "upstream Anthropic stream error") + return nil, fmt.Errorf("%s", message) } - return nil + return nil, nil } -func (p *streamParser) parseResponses(eventName string, v map[string]any) []streamEvent { - typeName := stringAt(v, "type") +func (parser *bridgeStreamParser) parseResponses(eventName string, value map[string]any) []bridgeStreamEvent { + typeName := stringAt(value, "type") if typeName == "" { typeName = eventName } switch typeName { case "response.created": - response := mapAt(v, "response") - return []streamEvent{{Kind: "start", ID: stringAt(response, "id"), Model: stringAt(response, "model")}} + response := mapAt(value, "response") + return []bridgeStreamEvent{{Kind: "start", ResponseID: stringAt(response, "id"), Model: stringAt(response, "model")}} case "response.output_text.delta": - return []streamEvent{{Kind: "text", Text: stringAt(v, "delta")}} + return []bridgeStreamEvent{{Kind: "text", Text: stringAt(value, "delta")}} case "response.output_item.added": - item := mapAt(v, "item") + item := mapAt(value, "item") if stringAt(item, "type") == "function_call" { - return []streamEvent{{Kind: "tool_start", Key: fmt.Sprint(v["output_index"]), ToolID: stringAt(item, "call_id"), Name: stringAt(item, "name")}} + key := responseToolKey(value, item) + parser.tools[key] = true + return []bridgeStreamEvent{{Kind: "tool_start", ToolKey: key, ToolID: stringAt(item, "call_id"), ToolName: stringAt(item, "name")}} } case "response.function_call_arguments.delta": - return []streamEvent{{Kind: "tool_delta", Key: fmt.Sprint(v["output_index"]), Text: stringAt(v, "delta")}} + key := responseToolKey(value, nil) + parser.responseArgs[key] = true + return []bridgeStreamEvent{{Kind: "tool_delta", ToolKey: key, Text: stringAt(value, "delta")}} + case "response.output_item.done": + item := mapAt(value, "item") + if stringAt(item, "type") == "function_call" { + key := responseToolKey(value, item) + events := make([]bridgeStreamEvent, 0, 2) + if !parser.tools[key] { + parser.tools[key] = true + events = append(events, bridgeStreamEvent{Kind: "tool_start", ToolKey: key, ToolID: stringAt(item, "call_id"), ToolName: stringAt(item, "name")}) + } + if !parser.responseArgs[key] { + if arguments := stringAt(item, "arguments"); arguments != "" { + events = append(events, bridgeStreamEvent{Kind: "tool_delta", ToolKey: key, Text: arguments}) + } + } + return events + } case "response.completed", "response.incomplete", "response.failed": - response := mapAt(v, "response") + response := mapAt(value, "response") usage := decodeOpenAIUsage(mapAt(response, "usage")) stop := "stop" if typeName == "response.incomplete" { stop = "length" - } - if typeName == "response.failed" { + } else if typeName == "response.failed" { stop = "error" } - return []streamEvent{{Kind: "usage", Usage: &usage}, {Kind: "finish", Stop: stop}, {Kind: "done"}} + return []bridgeStreamEvent{{Kind: "usage", Usage: &usage}, {Kind: "finish", Stop: stop}, {Kind: "done"}} } return nil } -type bufferedTool struct { +func responseToolKey(event map[string]any, item map[string]any) string { + if item != nil { + if id := stringAt(item, "id"); id != "" { + return id + } + } + if id := stringAt(event, "item_id"); id != "" { + return id + } + return fmt.Sprint(event["output_index"]) +} + +type bridgeStreamTool struct { + Key string ID string ItemID string Name string Arguments strings.Builder + Index int + Started bool } -type streamEmitter struct { - w io.Writer - flush http.Flusher - target Protocol - response canonicalResponse - started bool - finished bool - textOpen bool - textItem string - sequence int - tools map[string]*bufferedTool - order []string +type bridgeStreamEmitter struct { + w io.Writer + flush http.Flusher + target Protocol + model string + id string + created int64 + started bool + done bool + stop string + usage bridgeUsage + text strings.Builder + + tools map[string]*bridgeStreamTool + order []string + + sequence int + nextOutput int + textOpen bool + textItemID string + textOutput int + responseOutput []any } -func newStreamEmitter(w io.Writer, flush http.Flusher, target Protocol, model string) *streamEmitter { - return &streamEmitter{w: w, flush: flush, target: target, response: canonicalResponse{Model: model, Created: time.Now().Unix()}, tools: map[string]*bufferedTool{}} +func newBridgeStreamEmitter(writer io.Writer, flusher http.Flusher, target Protocol, model string) *bridgeStreamEmitter { + return &bridgeStreamEmitter{ + w: writer, + flush: flusher, + target: target, + model: model, + created: time.Now().Unix(), + tools: map[string]*bridgeStreamTool{}, + } } -func (e *streamEmitter) Emit(event streamEvent) error { - if event.ID != "" && e.response.ID == "" { - e.response.ID = event.ID +func (emitter *bridgeStreamEmitter) Emit(event bridgeStreamEvent) error { + if event.ResponseID != "" && emitter.id == "" { + emitter.id = event.ResponseID } if event.Model != "" { - e.response.Model = event.Model + emitter.model = event.Model } - if !e.started && (event.Kind == "start" || event.Kind == "text" || event.Kind == "tool_start") { - if err := e.start(); err != nil { + if !emitter.started && (event.Kind == "start" || event.Kind == "text" || event.Kind == "tool_start" || event.Kind == "tool_delta") { + if err := emitter.start(); err != nil { return err } } @@ -262,247 +332,378 @@ func (e *streamEmitter) Emit(event streamEvent) error { if event.Text == "" { return nil } - e.response.Text += event.Text - return e.emitText(event.Text) + emitter.text.WriteString(event.Text) + return emitter.emitText(event.Text) case "tool_start": - if _, exists := e.tools[event.Key]; !exists { - id := event.ToolID - if id == "" { - id = randomID("call", 12) - } - e.tools[event.Key] = &bufferedTool{ID: id, ItemID: randomID("fc", 12), Name: event.Name} - e.order = append(e.order, event.Key) + tool := emitter.tool(event.ToolKey) + if event.ToolID != "" { + tool.ID = event.ToolID } + if event.ToolName != "" { + tool.Name = event.ToolName + } + return emitter.startTool(tool) case "tool_delta": - tool := e.tools[event.Key] - if tool == nil { - tool = &bufferedTool{ID: randomID("call", 12), ItemID: randomID("fc", 12)} - e.tools[event.Key] = tool - e.order = append(e.order, event.Key) + tool := emitter.tool(event.ToolKey) + if event.ToolID != "" { + tool.ID = event.ToolID + } + if event.ToolName != "" { + tool.Name = event.ToolName + } + if err := emitter.startTool(tool); err != nil { + return err } tool.Arguments.WriteString(event.Text) + return emitter.emitToolDelta(tool, event.Text) case "usage": if event.Usage != nil { - mergeUsage(&e.response.Usage, *event.Usage) + mergeBridgeUsage(&emitter.usage, *event.Usage) } case "finish": - e.response.Stop = event.Stop + emitter.stop = event.Stop case "done": - return e.Finish() + return emitter.Finish() } return nil } -func (e *streamEmitter) start() error { - if e.started { +func (emitter *bridgeStreamEmitter) tool(key string) *bridgeStreamTool { + if key == "" { + key = fmt.Sprintf("tool-%d", len(emitter.order)) + } + if current := emitter.tools[key]; current != nil { + return current + } + tool := &bridgeStreamTool{ + Key: key, + ID: randomID("call", 12), + ItemID: randomID("fc", 12), + Index: len(emitter.order), + } + emitter.tools[key] = tool + emitter.order = append(emitter.order, key) + return tool +} + +func (emitter *bridgeStreamEmitter) start() error { + if emitter.started { return nil } - e.started = true - if e.response.ID == "" { - e.response.ID = randomID("resp", 12) + emitter.started = true + if emitter.id == "" { + emitter.id = randomID("resp", 12) } - switch e.target { + switch emitter.target { case ProtocolChat: - return e.sse("", map[string]any{"id": asPrefix(e.response.ID, "chatcmpl"), "object": "chat.completion.chunk", "created": e.response.Created, "model": e.response.Model, "choices": []any{map[string]any{"index": 0, "delta": map[string]any{"role": "assistant", "content": ""}, "finish_reason": nil}}}) + return emitter.sse("", map[string]any{ + "id": asPrefix(emitter.id, "chatcmpl"), + "object": "chat.completion.chunk", + "created": emitter.created, + "model": emitter.model, + "choices": []any{map[string]any{ + "index": 0, + "delta": map[string]any{"role": "assistant", "content": ""}, + "finish_reason": nil, + }}, + }) case ProtocolAnthropic: - return e.sse("message_start", map[string]any{"type": "message_start", "message": map[string]any{"id": asPrefix(e.response.ID, "msg"), "type": "message", "role": "assistant", "model": e.response.Model, "content": []any{}, "stop_reason": nil, "stop_sequence": nil, "usage": map[string]any{"input_tokens": 0, "output_tokens": 0}}}) + return emitter.sse("message_start", map[string]any{ + "type": "message_start", + "message": map[string]any{ + "id": asPrefix(emitter.id, "msg"), + "type": "message", + "role": "assistant", + "model": emitter.model, + "content": []any{}, + "stop_reason": nil, + "stop_sequence": nil, + "usage": map[string]any{"input_tokens": 0, "output_tokens": 0}, + }, + }) case ProtocolResponses: - base := map[string]any{"id": asPrefix(e.response.ID, "resp"), "object": "response", "created_at": e.response.Created, "status": "in_progress", "model": e.response.Model, "output": []any{}, "error": nil} - if err := e.sse("response.created", map[string]any{"type": "response.created", "response": base, "sequence_number": e.nextSequence()}); err != nil { + response := emitter.responsesBase("in_progress", []any{}) + if err := emitter.sse("response.created", map[string]any{"type": "response.created", "response": response, "sequence_number": emitter.nextSequence()}); err != nil { return err } - return e.sse("response.in_progress", map[string]any{"type": "response.in_progress", "response": base, "sequence_number": e.nextSequence()}) + return emitter.sse("response.in_progress", map[string]any{"type": "response.in_progress", "response": response, "sequence_number": emitter.nextSequence()}) + default: + return fmt.Errorf("unsupported stream target %q", emitter.target) } - return nil } -func (e *streamEmitter) emitText(delta string) error { - switch e.target { +func (emitter *bridgeStreamEmitter) emitText(delta string) error { + switch emitter.target { case ProtocolChat: - return e.sse("", map[string]any{"id": asPrefix(e.response.ID, "chatcmpl"), "object": "chat.completion.chunk", "created": e.response.Created, "model": e.response.Model, "choices": []any{map[string]any{"index": 0, "delta": map[string]any{"content": delta}, "finish_reason": nil}}}) + return emitter.chatChunk(map[string]any{"content": delta}, nil) case ProtocolAnthropic: - if !e.textOpen { - e.textOpen = true - if err := e.sse("content_block_start", map[string]any{"type": "content_block_start", "index": 0, "content_block": map[string]any{"type": "text", "text": ""}}); err != nil { + if !emitter.textOpen { + emitter.textOpen = true + if err := emitter.sse("content_block_start", map[string]any{ + "type": "content_block_start", + "index": 0, + "content_block": map[string]any{"type": "text", "text": ""}, + }); err != nil { return err } } - return e.sse("content_block_delta", map[string]any{"type": "content_block_delta", "index": 0, "delta": map[string]any{"type": "text_delta", "text": delta}}) + return emitter.sse("content_block_delta", map[string]any{ + "type": "content_block_delta", + "index": 0, + "delta": map[string]any{"type": "text_delta", "text": delta}, + }) case ProtocolResponses: - if !e.textOpen { - e.textOpen = true - e.textItem = randomID("msg", 12) - item := map[string]any{"id": e.textItem, "type": "message", "status": "in_progress", "role": "assistant", "content": []any{}} - if err := e.sse("response.output_item.added", map[string]any{"type": "response.output_item.added", "output_index": 0, "item": item, "sequence_number": e.nextSequence()}); err != nil { + if !emitter.textOpen { + emitter.textOpen = true + emitter.textItemID = randomID("msg", 12) + emitter.textOutput = emitter.nextOutput + emitter.nextOutput++ + item := map[string]any{"id": emitter.textItemID, "type": "message", "status": "in_progress", "role": "assistant", "content": []any{}} + if err := emitter.sse("response.output_item.added", map[string]any{"type": "response.output_item.added", "output_index": emitter.textOutput, "item": item, "sequence_number": emitter.nextSequence()}); err != nil { return err } - if err := e.sse("response.content_part.added", map[string]any{"type": "response.content_part.added", "item_id": item["id"], "output_index": 0, "content_index": 0, "part": map[string]any{"type": "output_text", "text": "", "annotations": []any{}}, "sequence_number": e.nextSequence()}); err != nil { + part := map[string]any{"type": "output_text", "text": "", "annotations": []any{}} + if err := emitter.sse("response.content_part.added", map[string]any{"type": "response.content_part.added", "item_id": emitter.textItemID, "output_index": emitter.textOutput, "content_index": 0, "part": part, "sequence_number": emitter.nextSequence()}); err != nil { return err } } - return e.sse("response.output_text.delta", map[string]any{"type": "response.output_text.delta", "delta": delta, "item_id": e.textItem, "output_index": 0, "content_index": 0, "sequence_number": e.nextSequence()}) + return emitter.sse("response.output_text.delta", map[string]any{"type": "response.output_text.delta", "delta": delta, "item_id": emitter.textItemID, "output_index": emitter.textOutput, "content_index": 0, "sequence_number": emitter.nextSequence()}) } return nil } -func (e *streamEmitter) Finish() error { - if e.finished { +func (emitter *bridgeStreamEmitter) startTool(tool *bridgeStreamTool) error { + if tool.Started || emitter.target == ProtocolAnthropic { return nil } - e.finished = true - if !e.started { - if err := e.start(); err != nil { - return err - } - } - for _, key := range e.order { - tool := e.tools[key] - if tool == nil { - continue - } - input := parseJSONOrString(tool.Arguments.String()) - e.response.Tools = append(e.response.Tools, canonicalBlock{Type: "tool_use", ID: tool.ID, Name: tool.Name, Input: input}) - } - if e.response.Stop == "" { - e.response.Stop = "stop" - } - switch e.target { + tool.Started = true + switch emitter.target { case ProtocolChat: - if len(e.response.Tools) > 0 { - calls := make([]any, 0, len(e.response.Tools)) - for i, tool := range e.response.Tools { - args, _ := json.Marshal(tool.Input) - calls = append(calls, map[string]any{"index": i, "id": tool.ID, "type": "function", "function": map[string]any{"name": tool.Name, "arguments": string(args)}}) - } - if err := e.sse("", map[string]any{"id": asPrefix(e.response.ID, "chatcmpl"), "object": "chat.completion.chunk", "created": e.response.Created, "model": e.response.Model, "choices": []any{map[string]any{"index": 0, "delta": map[string]any{"tool_calls": calls}, "finish_reason": nil}}}); err != nil { - return err - } - } - if err := e.sse("", map[string]any{"id": asPrefix(e.response.ID, "chatcmpl"), "object": "chat.completion.chunk", "created": e.response.Created, "model": e.response.Model, "choices": []any{map[string]any{"index": 0, "delta": map[string]any{}, "finish_reason": chatStop(e.response.Stop)}}}); err != nil { + return emitter.chatChunk(map[string]any{"tool_calls": []any{map[string]any{ + "index": tool.Index, + "id": tool.ID, + "type": "function", + "function": map[string]any{ + "name": tool.Name, + "arguments": "", + }, + }}}, nil) + case ProtocolResponses: + tool.Index = emitter.nextOutput + emitter.nextOutput++ + item := map[string]any{"id": tool.ItemID, "type": "function_call", "status": "in_progress", "arguments": "", "call_id": tool.ID, "name": tool.Name} + return emitter.sse("response.output_item.added", map[string]any{"type": "response.output_item.added", "output_index": tool.Index, "item": item, "sequence_number": emitter.nextSequence()}) + } + return nil +} + +func (emitter *bridgeStreamEmitter) emitToolDelta(tool *bridgeStreamTool, delta string) error { + if delta == "" || emitter.target == ProtocolAnthropic { + return nil + } + switch emitter.target { + case ProtocolChat: + return emitter.chatChunk(map[string]any{"tool_calls": []any{map[string]any{ + "index": tool.Index, + "function": map[string]any{"arguments": delta}, + }}}, nil) + case ProtocolResponses: + return emitter.sse("response.function_call_arguments.delta", map[string]any{"type": "response.function_call_arguments.delta", "delta": delta, "item_id": tool.ItemID, "output_index": tool.Index, "sequence_number": emitter.nextSequence()}) + } + return nil +} + +func (emitter *bridgeStreamEmitter) Finish() error { + if emitter.done { + return nil + } + emitter.done = true + if !emitter.started { + if err := emitter.start(); err != nil { return err } - if err := e.sse("", map[string]any{"id": asPrefix(e.response.ID, "chatcmpl"), "object": "chat.completion.chunk", "created": e.response.Created, "model": e.response.Model, "choices": []any{}, "usage": openAIUsage(e.response.Usage)}); err != nil { + } + if emitter.stop == "" { + if len(emitter.order) > 0 { + emitter.stop = "tool_calls" + } else { + emitter.stop = "stop" + } + } + switch emitter.target { + case ProtocolChat: + if err := emitter.chatChunk(map[string]any{}, chatStop(emitter.stop)); err != nil { return err } - return e.rawSSE("", "[DONE]") + if err := emitter.sse("", map[string]any{ + "id": asPrefix(emitter.id, "chatcmpl"), + "object": "chat.completion.chunk", + "created": emitter.created, + "model": emitter.model, + "choices": []any{}, + "usage": openAIUsage(emitter.usage), + }); err != nil { + return err + } + return emitter.rawSSE("", "[DONE]") + case ProtocolAnthropic: index := 0 - if e.textOpen { - if err := e.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": index}); err != nil { + if emitter.textOpen { + if err := emitter.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": index}); err != nil { return err } index++ } - for _, tool := range e.response.Tools { - if err := e.sse("content_block_start", map[string]any{"type": "content_block_start", "index": index, "content_block": map[string]any{"type": "tool_use", "id": tool.ID, "name": tool.Name, "input": map[string]any{}}}); err != nil { + for _, key := range emitter.order { + tool := emitter.tools[key] + if err := emitter.sse("content_block_start", map[string]any{ + "type": "content_block_start", + "index": index, + "content_block": map[string]any{"type": "tool_use", "id": tool.ID, "name": tool.Name, "input": map[string]any{}}, + }); err != nil { return err } - args, _ := json.Marshal(tool.Input) - if err := e.sse("content_block_delta", map[string]any{"type": "content_block_delta", "index": index, "delta": map[string]any{"type": "input_json_delta", "partial_json": string(args)}}); err != nil { - return err + if arguments := tool.Arguments.String(); arguments != "" { + if err := emitter.sse("content_block_delta", map[string]any{"type": "content_block_delta", "index": index, "delta": map[string]any{"type": "input_json_delta", "partial_json": arguments}}); err != nil { + return err + } } - if err := e.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": index}); err != nil { + if err := emitter.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": index}); err != nil { return err } index++ } - if err := e.sse("message_delta", map[string]any{"type": "message_delta", "delta": map[string]any{"stop_reason": anthropicStop(e.response.Stop), "stop_sequence": nil}, "usage": map[string]any{"input_tokens": e.response.Usage.Input, "output_tokens": e.response.Usage.Output}}); err != nil { + if err := emitter.sse("message_delta", map[string]any{ + "type": "message_delta", + "delta": map[string]any{"stop_reason": anthropicStop(emitter.stop), "stop_sequence": nil}, + "usage": map[string]any{"input_tokens": emitter.usage.Input, "output_tokens": emitter.usage.Output}, + }); err != nil { return err } - return e.sse("message_stop", map[string]any{"type": "message_stop"}) + return emitter.sse("message_stop", map[string]any{"type": "message_stop"}) + case ProtocolResponses: - if e.textOpen { - if err := e.sse("response.output_text.done", map[string]any{"type": "response.output_text.done", "text": e.response.Text, "item_id": e.textItem, "output_index": 0, "content_index": 0, "sequence_number": e.nextSequence()}); err != nil { - return err - } - part := map[string]any{"type": "output_text", "text": e.response.Text, "annotations": []any{}} - if err := e.sse("response.content_part.done", map[string]any{"type": "response.content_part.done", "item_id": e.textItem, "output_index": 0, "content_index": 0, "part": part, "sequence_number": e.nextSequence()}); err != nil { - return err - } - item := map[string]any{"id": e.textItem, "type": "message", "status": "completed", "role": "assistant", "content": []any{part}} - if err := e.sse("response.output_item.done", map[string]any{"type": "response.output_item.done", "output_index": 0, "item": item, "sequence_number": e.nextSequence()}); err != nil { - return err - } + if err := emitter.finishResponsesItems(); err != nil { + return err } - baseIndex := 0 - if e.textOpen { - baseIndex = 1 + response := bridgeResponse{ + ID: emitter.id, + Model: emitter.model, + Text: emitter.text.String(), + Stop: emitter.stop, + Usage: emitter.usage, + Created: emitter.created, } - for i, key := range e.order { - tool := e.tools[key] - if tool == nil { - continue - } - index := baseIndex + i - item := map[string]any{"id": tool.ItemID, "type": "function_call", "status": "in_progress", "arguments": "", "call_id": tool.ID, "name": tool.Name} - if err := e.sse("response.output_item.added", map[string]any{"type": "response.output_item.added", "output_index": index, "item": item, "sequence_number": e.nextSequence()}); err != nil { - return err - } - args := tool.Arguments.String() - if err := e.sse("response.function_call_arguments.delta", map[string]any{"type": "response.function_call_arguments.delta", "delta": args, "item_id": tool.ItemID, "output_index": index, "sequence_number": e.nextSequence()}); err != nil { - return err - } - if err := e.sse("response.function_call_arguments.done", map[string]any{"type": "response.function_call_arguments.done", "arguments": args, "item_id": tool.ItemID, "output_index": index, "sequence_number": e.nextSequence()}); err != nil { - return err - } - item["status"] = "completed" - item["arguments"] = args - if err := e.sse("response.output_item.done", map[string]any{"type": "response.output_item.done", "output_index": index, "item": item, "sequence_number": e.nextSequence()}); err != nil { - return err - } + for _, key := range emitter.order { + tool := emitter.tools[key] + response.Tools = append(response.Tools, bridgeBlock{Kind: "tool_call", ID: tool.ID, Name: tool.Name, ArgumentsJSON: tool.Arguments.String()}) } - output := encodeResponse(ProtocolResponses, e.response)["output"] - response := encodeResponse(ProtocolResponses, e.response) - response["output"] = output - return e.sse("response.completed", map[string]any{"type": "response.completed", "response": response, "sequence_number": e.nextSequence()}) + completed := encodeBridgeResponse(ProtocolResponses, response) + return emitter.sse("response.completed", map[string]any{"type": "response.completed", "response": completed, "sequence_number": emitter.nextSequence()}) } return nil } -func (e *streamEmitter) nextSequence() int { - value := e.sequence - e.sequence++ - return value +func (emitter *bridgeStreamEmitter) finishResponsesItems() error { + if emitter.textOpen { + text := emitter.text.String() + if err := emitter.sse("response.output_text.done", map[string]any{"type": "response.output_text.done", "text": text, "item_id": emitter.textItemID, "output_index": emitter.textOutput, "content_index": 0, "sequence_number": emitter.nextSequence()}); err != nil { + return err + } + part := map[string]any{"type": "output_text", "text": text, "annotations": []any{}} + if err := emitter.sse("response.content_part.done", map[string]any{"type": "response.content_part.done", "item_id": emitter.textItemID, "output_index": emitter.textOutput, "content_index": 0, "part": part, "sequence_number": emitter.nextSequence()}); err != nil { + return err + } + item := map[string]any{"id": emitter.textItemID, "type": "message", "status": "completed", "role": "assistant", "content": []any{part}} + if err := emitter.sse("response.output_item.done", map[string]any{"type": "response.output_item.done", "output_index": emitter.textOutput, "item": item, "sequence_number": emitter.nextSequence()}); err != nil { + return err + } + } + for _, key := range emitter.order { + tool := emitter.tools[key] + arguments := tool.Arguments.String() + if err := emitter.sse("response.function_call_arguments.done", map[string]any{"type": "response.function_call_arguments.done", "arguments": arguments, "item_id": tool.ItemID, "output_index": tool.Index, "sequence_number": emitter.nextSequence()}); err != nil { + return err + } + item := map[string]any{"id": tool.ItemID, "type": "function_call", "status": "completed", "arguments": arguments, "call_id": tool.ID, "name": tool.Name} + if err := emitter.sse("response.output_item.done", map[string]any{"type": "response.output_item.done", "output_index": tool.Index, "item": item, "sequence_number": emitter.nextSequence()}); err != nil { + return err + } + } + return nil } -func (e *streamEmitter) sse(event string, value any) error { +func (emitter *bridgeStreamEmitter) chatChunk(delta map[string]any, finish any) error { + return emitter.sse("", map[string]any{ + "id": asPrefix(emitter.id, "chatcmpl"), + "object": "chat.completion.chunk", + "created": emitter.created, + "model": emitter.model, + "choices": []any{map[string]any{ + "index": 0, + "delta": delta, + "finish_reason": finish, + }}, + }) +} + +func (emitter *bridgeStreamEmitter) responsesBase(status string, output []any) map[string]any { + return map[string]any{ + "id": asPrefix(emitter.id, "resp"), + "object": "response", + "created_at": emitter.created, + "status": status, + "model": emitter.model, + "output": output, + "error": nil, + } +} + +func (emitter *bridgeStreamEmitter) nextSequence() int { + sequence := emitter.sequence + emitter.sequence++ + return sequence +} + +func (emitter *bridgeStreamEmitter) sse(eventName string, value any) error { data, err := json.Marshal(value) if err != nil { return err } - return e.rawSSE(event, string(data)) + return emitter.rawSSE(eventName, string(data)) } -func (e *streamEmitter) rawSSE(event, data string) error { - if event != "" { - if _, err := fmt.Fprintf(e.w, "event: %s\n", event); err != nil { +func (emitter *bridgeStreamEmitter) rawSSE(eventName, data string) error { + if eventName != "" { + if _, err := fmt.Fprintf(emitter.w, "event: %s\n", eventName); err != nil { return err } } - if _, err := fmt.Fprintf(e.w, "data: %s\n\n", data); err != nil { + if _, err := fmt.Fprintf(emitter.w, "data: %s\n\n", data); err != nil { return err } - e.flush.Flush() + emitter.flush.Flush() return nil } -func mergeUsage(dst *canonicalUsage, src canonicalUsage) { - if src.Input != 0 { - dst.Input = src.Input +func mergeBridgeUsage(destination *bridgeUsage, source bridgeUsage) { + if source.Input != 0 { + destination.Input = source.Input } - if src.Output != 0 { - dst.Output = src.Output + if source.Output != 0 { + destination.Output = source.Output } - if src.Total != 0 { - dst.Total = src.Total + if source.Total != 0 { + destination.Total = source.Total } - if src.Cached != 0 { - dst.Cached = src.Cached + if source.Cached != 0 { + destination.Cached = source.Cached } - if src.Reasoning != 0 { - dst.Reasoning = src.Reasoning + if source.Reasoning != 0 { + destination.Reasoning = source.Reasoning } - if dst.Total == 0 { - dst.Total = dst.Input + dst.Output + if destination.Total == 0 { + destination.Total = destination.Input + destination.Output } }