From c1b1ab8bd26622019bdaacafb323f42d3001eda1 Mon Sep 17 00:00:00 2001 From: Jason Xu Date: Thu, 20 Aug 2026 00:13:10 +0800 Subject: [PATCH] fix: harden cross-protocol inference conversion --- convert.go | 165 +++++++++++++++++++++++++++++++++++++++++++++++------ models.go | 6 ++ stream.go | 161 +++++++++++++++++++++++++++++++++++++++------------ 3 files changed, 279 insertions(+), 53 deletions(-) diff --git a/convert.go b/convert.go index e666d0d..8848102 100644 --- a/convert.go +++ b/convert.go @@ -52,6 +52,7 @@ type bridgeToolChoice struct { type bridgeRequest struct { Model string System []bridgeBlock + Developer []bridgeBlock Messages []bridgeMessage Tools []bridgeTool ToolChoice bridgeToolChoice @@ -308,8 +309,10 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest }) } switch role { - case "system", "developer": + case "system": request.System = append(request.System, blocks...) + case "developer": + request.Developer = append(request.Developer, blocks...) case "tool": request.Messages = append(request.Messages, bridgeMessage{Role: "user", Blocks: []bridgeBlock{{ Kind: "tool_result", @@ -340,7 +343,7 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest case ProtocolResponses: request.MaxTokens = input["max_output_tokens"] request.Stop = input["stop"] - request.Reasoning = input["reasoning"] + request.Reasoning = firstAny(input["reasoning"], input["reasoning_effort"]) request.System = append(request.System, decodeOpenAIBlocks(input["instructions"])...) switch value := input["input"].(type) { case string: @@ -372,8 +375,10 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest case "message", "": role := stringAt(item, "role") blocks := decodeOpenAIBlocks(item["content"]) - if role == "system" || role == "developer" { + if role == "system" { request.System = append(request.System, blocks...) + } else if role == "developer" { + request.Developer = append(request.Developer, blocks...) } else if role == "user" || role == "assistant" { request.Messages = append(request.Messages, bridgeMessage{Role: role, Blocks: blocks}) } @@ -399,7 +404,7 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest case ProtocolAnthropic: request.MaxTokens = input["max_tokens"] request.Stop = input["stop_sequences"] - request.Reasoning = firstAny(input["thinking"], input["effort"]) + request.Reasoning = firstAny(input["thinking"], anyAt(input, "output_config", "effort"), input["effort"]) request.System = decodeAnthropicBlocks(input["system"]) for i, raw := range sliceAt(input, "messages") { message, ok := raw.(map[string]any) @@ -484,6 +489,9 @@ func encodeChatRequest(request bridgeRequest) (map[string]any, error) { if len(request.System) > 0 { messages = append(messages, map[string]any{"role": "system", "content": encodeChatBlocks(request.System)}) } + if len(request.Developer) > 0 { + messages = append(messages, map[string]any{"role": "developer", "content": encodeChatBlocks(request.Developer)}) + } pending := make(map[string]bool) pendingResults := make(map[string]bridgeBlock) var pendingOrder []string @@ -659,7 +667,13 @@ func encodeResponsesRequest(request bridgeRequest) map[string]any { } } - items := make([]any, 0, len(request.Messages)) + items := make([]any, 0, len(request.Messages)+1) + if len(request.Developer) > 0 { + items = append(items, map[string]any{ + "type": "message", "role": "developer", + "content": []any{map[string]any{"type": "input_text", "text": bridgeBlocksText(request.Developer)}}, + }) + } for _, message := range request.Messages { var content []any flushContent := func() { @@ -739,11 +753,16 @@ func encodeAnthropicRequest(request bridgeRequest) map[string]any { } else { output["max_tokens"] = request.MaxTokens } - if effort := reasoningEffort(request.Reasoning); effort != nil { - output["effort"] = effort + if thinking, outputConfig := anthropicThinking(request.Reasoning); thinking != nil { + output["thinking"] = thinking + if outputConfig != nil { + output["output_config"] = outputConfig + } } - if len(request.System) > 0 { - output["system"] = encodeAnthropicBlocks(request.System) + if len(request.System) > 0 || len(request.Developer) > 0 { + instructions := append([]bridgeBlock(nil), request.System...) + instructions = append(instructions, request.Developer...) + output["system"] = encodeAnthropicBlocks(instructions) } messages := make([]any, 0, len(request.Messages)) @@ -766,7 +785,9 @@ func encodeAnthropicRequest(request bridgeRequest) map[string]any { messages = append(messages, map[string]any{"role": role, "content": content}) } output["messages"] = messages - if len(request.Tools) > 0 { + // Anthropic has no tool_choice "none" value. Omitting the tools is the + // protocol-compatible representation of an explicitly disabled tool set. + if len(request.Tools) > 0 && request.ToolChoice.Mode != "none" { tools := make([]any, 0, len(request.Tools)) for _, tool := range request.Tools { tools = append(tools, map[string]any{ @@ -1052,6 +1073,12 @@ func decodeResponsesToolChoice(value any) bridgeToolChoice { } func decodeAnthropicToolChoice(value any) bridgeToolChoice { + if mode, ok := value.(string); ok { + if mode == "required" { + mode = "any" + } + return decodeAnthropicToolChoice(map[string]any{"type": mode}) + } choice, _ := value.(map[string]any) switch stringAt(choice, "type") { case "auto": @@ -1095,7 +1122,7 @@ func encodeAnthropicToolChoice(choice bridgeToolChoice) any { return map[string]any{"type": "tool", "name": choice.Name} case "required": return map[string]any{"type": "any"} - case "auto", "none": + case "auto": return map[string]any{"type": choice.Mode} default: return nil @@ -1149,7 +1176,7 @@ func decodeBridgeResponse(protocol Protocol, input map[string]any) (bridgeRespon ArgumentsJSON: stringAt(function, "arguments"), }) } - response.Stop = stringAt(choice, "finish_reason") + response.Stop = canonicalChatStop(stringAt(choice, "finish_reason")) response.Usage = decodeOpenAIUsage(mapAt(input, "usage")) case ProtocolResponses: for _, raw := range sliceAt(input, "output") { @@ -1173,7 +1200,9 @@ func decodeBridgeResponse(protocol Protocol, input map[string]any) (bridgeRespon response.Stop = "tool_calls" } if stringAt(input, "status") == "incomplete" { - response.Stop = "length" + response.Stop = canonicalResponsesIncomplete(stringAt(input, "incomplete_details", "reason")) + } else if stringAt(input, "status") == "failed" { + response.Stop = "error" } response.Usage = decodeOpenAIUsage(mapAt(input, "usage")) case ProtocolAnthropic: @@ -1186,7 +1215,7 @@ func decodeBridgeResponse(protocol Protocol, input map[string]any) (bridgeRespon response.Tools = append(response.Tools, block) } } - response.Stop = stringAt(input, "stop_reason") + response.Stop = canonicalAnthropicStop(stringAt(input, "stop_reason")) response.Usage = decodeAnthropicUsage(mapAt(input, "usage")) default: return response, fmt.Errorf("unsupported response protocol %q", protocol) @@ -1261,15 +1290,23 @@ func encodeBridgeResponse(protocol Protocol, response bridgeResponse) map[string "arguments": bridgeArgumentsJSON(tool), }) } + status := "completed" + var incomplete any + if response.Stop == "length" || response.Stop == "content_filter" { + status = "incomplete" + incomplete = map[string]any{"reason": responsesIncompleteReason(response.Stop)} + } else if response.Stop == "error" { + status = "failed" + } return map[string]any{ "id": asPrefix(response.ID, "resp"), "object": "response", "created_at": response.Created, - "status": "completed", + "status": status, "model": response.Model, "output": output, "error": nil, - "incomplete_details": nil, + "incomplete_details": incomplete, "usage": map[string]any{ "input_tokens": response.Usage.Input, "output_tokens": response.Usage.Output, @@ -1373,6 +1410,8 @@ func chatStop(stop string) string { return "tool_calls" case "max_tokens", "length": return "length" + case "content_filter", "error": + return stop default: return "stop" } @@ -1384,6 +1423,8 @@ func anthropicStop(stop string) string { return "tool_use" case "max_tokens", "length": return "max_tokens" + case "stop_sequence", "pause_turn", "refusal": + return stop default: return "end_turn" } @@ -1398,11 +1439,101 @@ func schemaOrDefault(value any) any { func reasoningEffort(value any) any { if object, ok := value.(map[string]any); ok { - return firstAny(object["effort"], object["type"]) + if effort := object["effort"]; effort != nil { + return effort + } + switch stringAt(object, "type") { + case "disabled": + return nil + case "enabled", "adaptive": + return effortForThinkingBudget(intAt(object, "budget_tokens")) + default: + return object["type"] + } } return value } +func anthropicThinking(value any) (any, map[string]any) { + if value == nil { + return nil, nil + } + if object, ok := value.(map[string]any); ok { + kind := stringAt(object, "type") + if kind == "enabled" || kind == "adaptive" || kind == "disabled" { + return value, nil + } + value = firstAny(object["effort"], object["type"]) + } + effort, _ := value.(string) + effort = strings.ToLower(strings.TrimSpace(effort)) + if effort == "" || effort == "none" || effort == "disabled" { + return nil, nil + } + budget := 4096 + switch effort { + case "minimal", "low": + budget = 1024 + case "medium": + budget = 4096 + case "high", "xhigh", "max": + budget = 8192 + } + return map[string]any{"type": "enabled", "budget_tokens": budget}, map[string]any{"effort": effort} +} + +func effortForThinkingBudget(budget int) string { + if budget <= 0 || budget >= 8192 { + return "high" + } + if budget <= 2048 { + return "low" + } + return "medium" +} + +func canonicalChatStop(stop string) string { + switch stop { + case "tool_calls", "function_call": + return "tool_calls" + case "length": + return "length" + case "content_filter": + return "content_filter" + default: + return "stop" + } +} + +func canonicalAnthropicStop(stop string) string { + switch stop { + case "tool_use": + return "tool_calls" + case "max_tokens": + return "length" + case "stop_sequence", "pause_turn", "refusal": + return stop + default: + return "stop" + } +} + +func canonicalResponsesIncomplete(reason string) string { + switch reason { + case "content_filter": + return "content_filter" + default: + return "length" + } +} + +func responsesIncompleteReason(stop string) string { + if stop == "content_filter" { + return "content_filter" + } + return "max_output_tokens" +} + func bridgeBlocksText(blocks []bridgeBlock) string { var text strings.Builder for _, block := range blocks { diff --git a/models.go b/models.go index 099ade4..0ac04d3 100644 --- a/models.go +++ b/models.go @@ -191,6 +191,12 @@ func toSet(items []string) map[string]bool { func inferProtocol(model string) Protocol { m := strings.ToLower(model) + // This compatibility model speaks Chat Completions despite being exposed + // beside models whose names can imply newer OpenAI-style protocols. An + // explicit models.protocols entry is resolved before this default. + if m == "deepseek-v4-flash-free" { + return ProtocolChat + } for _, prefix := range []string{"claude-", "qwen"} { if strings.HasPrefix(m, prefix) { return ProtocolAnthropic diff --git a/stream.go b/stream.go index 0adee2c..423ae45 100644 --- a/stream.go +++ b/stream.go @@ -27,6 +27,9 @@ type bridgeStreamParser struct { protocol Protocol started bool tools map[string]bool + toolIDs map[string]string + toolNames map[string]string + toolOrder []string responseArgs map[string]bool responseReasoning map[string]bool } @@ -39,6 +42,8 @@ func transcodeStream(w http.ResponseWriter, reader io.Reader, from, to Protocol, parser := &bridgeStreamParser{ protocol: from, tools: map[string]bool{}, + toolIDs: map[string]string{}, + toolNames: map[string]string{}, responseArgs: map[string]bool{}, responseReasoning: map[string]bool{}, } @@ -146,16 +151,31 @@ func (parser *bridgeStreamParser) parseChat(value map[string]any) []bridgeStream key := fmt.Sprint(firstAny(call["index"], stringAt(call, "id"))) 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 _, seen := parser.tools[key]; !seen { + parser.tools[key] = false + parser.toolOrder = append(parser.toolOrder, key) + } + if id != "" { + parser.toolIDs[key] = id + } + if name := stringAt(function, "name"); name != "" { + parser.toolNames[key] = mergeToolName(parser.toolNames[key], name) } if arguments := stringAt(function, "arguments"); arguments != "" { - events = append(events, bridgeStreamEvent{Kind: "tool_delta", ToolKey: key, ToolID: id, ToolName: name, Text: arguments}) + if !parser.tools[key] && parser.toolNames[key] != "" { + parser.tools[key] = true + events = append(events, bridgeStreamEvent{Kind: "tool_start", ToolKey: key, ToolID: parser.toolIDs[key], ToolName: parser.toolNames[key]}) + } + events = append(events, bridgeStreamEvent{Kind: "tool_delta", ToolKey: key, ToolID: parser.toolIDs[key], ToolName: parser.toolNames[key], Text: arguments}) } } if stop := stringAt(choice, "finish_reason"); stop != "" { + for _, key := range parser.toolOrder { + if !parser.tools[key] && parser.toolNames[key] != "" { + parser.tools[key] = true + events = append(events, bridgeStreamEvent{Kind: "tool_start", ToolKey: key, ToolID: parser.toolIDs[key], ToolName: parser.toolNames[key]}) + } + } events = append(events, bridgeStreamEvent{Kind: "finish", Stop: stop}) } } @@ -244,13 +264,22 @@ func (parser *bridgeStreamParser) parseResponses(eventName string, value map[str item := mapAt(value, "item") if stringAt(item, "type") == "function_call" { key := responseToolKey(value, item) - parser.tools[key] = true - return []bridgeStreamEvent{{Kind: "tool_start", ToolKey: key, ToolID: stringAt(item, "call_id"), ToolName: stringAt(item, "name")}} + parser.rememberTool(key, stringAt(item, "call_id"), stringAt(item, "name")) + if parser.toolNames[key] != "" { + parser.tools[key] = true + return []bridgeStreamEvent{{Kind: "tool_start", ToolKey: key, ToolID: parser.toolIDs[key], ToolName: parser.toolNames[key]}} + } } case "response.function_call_arguments.delta": key := responseToolKey(value, nil) parser.responseArgs[key] = true - return []bridgeStreamEvent{{Kind: "tool_delta", ToolKey: key, Text: stringAt(value, "delta")}} + return []bridgeStreamEvent{{Kind: "tool_delta", ToolKey: key, ToolID: parser.toolIDs[key], ToolName: parser.toolNames[key], Text: stringAt(value, "delta")}} + case "response.function_call_arguments.done": + key := responseToolKey(value, nil) + if !parser.responseArgs[key] { + parser.responseArgs[key] = true + return []bridgeStreamEvent{{Kind: "tool_delta", ToolKey: key, ToolID: parser.toolIDs[key], ToolName: parser.toolNames[key], Text: stringAt(value, "arguments")}} + } case "response.output_item.done": item := mapAt(value, "item") if stringAt(item, "type") == "reasoning" { @@ -266,10 +295,11 @@ func (parser *bridgeStreamParser) parseResponses(eventName string, value map[str } if stringAt(item, "type") == "function_call" { key := responseToolKey(value, item) + parser.rememberTool(key, stringAt(item, "call_id"), stringAt(item, "name")) 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")}) + events = append(events, bridgeStreamEvent{Kind: "tool_start", ToolKey: key, ToolID: parser.toolIDs[key], ToolName: parser.toolNames[key]}) } if !parser.responseArgs[key] { if arguments := stringAt(item, "arguments"); arguments != "" { @@ -278,12 +308,12 @@ func (parser *bridgeStreamParser) parseResponses(eventName string, value map[str } return events } - case "response.completed", "response.incomplete", "response.failed": + case "response.completed", "response.incomplete", "response.failed", "response.done": response := mapAt(value, "response") usage := decodeOpenAIUsage(mapAt(response, "usage")) stop := "stop" if typeName == "response.incomplete" { - stop = "length" + stop = canonicalResponsesIncomplete(stringAt(response, "incomplete_details", "reason")) } else if typeName == "response.failed" { stop = "error" } @@ -292,6 +322,29 @@ func (parser *bridgeStreamParser) parseResponses(eventName string, value map[str return nil } +func (parser *bridgeStreamParser) rememberTool(key, id, name string) { + if _, seen := parser.tools[key]; !seen { + parser.tools[key] = false + parser.toolOrder = append(parser.toolOrder, key) + } + if id != "" { + parser.toolIDs[key] = id + } + if name != "" { + parser.toolNames[key] = name + } +} + +func mergeToolName(current, fragment string) string { + if current == "" || fragment == current { + return fragment + } + if strings.HasPrefix(fragment, current) { + return fragment + } + return current + fragment +} + func responseToolKey(event map[string]any, item map[string]any) string { if item != nil { if id := stringAt(item, "id"); id != "" { @@ -305,13 +358,15 @@ func responseToolKey(event map[string]any, item map[string]any) string { } type bridgeStreamTool struct { - Key string - ID string - ItemID string - Name string - Arguments strings.Builder - Index int - Started bool + Key string + ID string + ItemID string + Name string + Arguments strings.Builder + Index int + AnthropicIndex int + Started bool + EmittedArguments int } type bridgeStreamEmitter struct { @@ -397,7 +452,10 @@ func (emitter *bridgeStreamEmitter) Emit(event bridgeStreamEvent) error { if event.ToolName != "" { tool.Name = event.ToolName } - return emitter.startTool(tool) + if err := emitter.startTool(tool); err != nil { + return err + } + return emitter.emitPendingToolArguments(tool) case "tool_delta": tool := emitter.tool(event.ToolKey) if event.ToolID != "" { @@ -406,11 +464,11 @@ func (emitter *bridgeStreamEmitter) Emit(event bridgeStreamEvent) error { if event.ToolName != "" { tool.Name = event.ToolName } + tool.Arguments.WriteString(event.Text) if err := emitter.startTool(tool); err != nil { return err } - tool.Arguments.WriteString(event.Text) - return emitter.emitToolDelta(tool, event.Text) + return emitter.emitPendingToolArguments(tool) case "usage": if event.Usage != nil { mergeBridgeUsage(&emitter.usage, *event.Usage) @@ -622,14 +680,20 @@ func (emitter *bridgeStreamEmitter) finishReasoning() error { } func (emitter *bridgeStreamEmitter) startTool(tool *bridgeStreamTool) error { - if tool.Started || emitter.target == ProtocolAnthropic { + if tool.Started || tool.Name == "" { return nil } - if emitter.target == ProtocolResponses { + if emitter.target == ProtocolResponses || emitter.target == ProtocolAnthropic { if err := emitter.finishReasoning(); err != nil { return err } } + if emitter.target == ProtocolAnthropic && emitter.textOpen { + if err := emitter.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": emitter.textIndex}); err != nil { + return err + } + emitter.textOpen = false + } tool.Started = true switch emitter.target { case ProtocolChat: @@ -647,12 +711,19 @@ func (emitter *bridgeStreamEmitter) startTool(tool *bridgeStreamTool) error { 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()}) + case ProtocolAnthropic: + tool.AnthropicIndex = emitter.nextAnthropic + emitter.nextAnthropic++ + return emitter.sse("content_block_start", map[string]any{ + "type": "content_block_start", "index": tool.AnthropicIndex, + "content_block": map[string]any{"type": "tool_use", "id": tool.ID, "name": tool.Name, "input": map[string]any{}}, + }) } return nil } func (emitter *bridgeStreamEmitter) emitToolDelta(tool *bridgeStreamTool, delta string) error { - if delta == "" || emitter.target == ProtocolAnthropic { + if delta == "" { return nil } switch emitter.target { @@ -663,10 +734,25 @@ func (emitter *bridgeStreamEmitter) emitToolDelta(tool *bridgeStreamTool, 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()}) + case ProtocolAnthropic: + return emitter.sse("content_block_delta", map[string]any{"type": "content_block_delta", "index": tool.AnthropicIndex, "delta": map[string]any{"type": "input_json_delta", "partial_json": delta}}) } return nil } +func (emitter *bridgeStreamEmitter) emitPendingToolArguments(tool *bridgeStreamTool) error { + if !tool.Started { + return nil + } + arguments := tool.Arguments.String() + if tool.EmittedArguments >= len(arguments) { + return nil + } + delta := arguments[tool.EmittedArguments:] + tool.EmittedArguments = len(arguments) + return emitter.emitToolDelta(tool, delta) +} + func (emitter *bridgeStreamEmitter) Finish() error { if emitter.done { return nil @@ -712,23 +798,17 @@ func (emitter *bridgeStreamEmitter) Finish() error { } for _, key := range emitter.order { tool := emitter.tools[key] - index := emitter.nextAnthropic - emitter.nextAnthropic++ - 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 { + if err := emitter.startTool(tool); 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 { + if err := emitter.emitPendingToolArguments(tool); err != nil { + return err + } + if tool.Started { + if err := emitter.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": tool.AnthropicIndex}); err != nil { return err } } - if err := emitter.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": index}); err != nil { - return err - } } if err := emitter.sse("message_delta", map[string]any{ "type": "message_delta", @@ -783,6 +863,15 @@ func (emitter *bridgeStreamEmitter) finishResponsesItems() error { for _, key := range emitter.order { tool := emitter.tools[key] arguments := tool.Arguments.String() + if arguments == "" { + arguments = "{}" + } + if err := emitter.startTool(tool); err != nil { + return err + } + if err := emitter.emitPendingToolArguments(tool); err != nil { + return err + } 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 }