feat(chat): 完善 Chat Completions 兼容层
This commit is contained in:
@@ -151,6 +151,187 @@ func TestOpenAIClientChatContract(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIClientChatRequestNormalizesToolContext(t *testing.T) {
|
||||
var captured map[string]any
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := json.NewDecoder(r.Body).Decode(&captured); err != nil {
|
||||
t.Fatalf("decode request: %v", err)
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"id": "chatcmpl-normalized-request",
|
||||
"object": "chat.completion",
|
||||
"model": captured["model"],
|
||||
"choices": []any{map[string]any{
|
||||
"message": map[string]any{"role": "assistant", "content": "ok"},
|
||||
}},
|
||||
})
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
_, err := (OpenAIClient{HTTPClient: server.Client()}).Run(context.Background(), Request{
|
||||
Kind: "chat.completions",
|
||||
Model: "openai:gpt-4o-mini",
|
||||
Body: map[string]any{
|
||||
"model": "openai:gpt-4o-mini",
|
||||
"messages": []any{
|
||||
map[string]any{
|
||||
"role": "assistant",
|
||||
"functionCall": map[string]any{
|
||||
"name": "lookup",
|
||||
"arguments": map[string]any{"q": "weather"},
|
||||
},
|
||||
},
|
||||
map[string]any{"role": "tool", "toolCallId": "call_0", "content": "sunny"},
|
||||
map[string]any{
|
||||
"role": "user",
|
||||
"content": []any{
|
||||
map[string]any{"type": "text", "text": "keep this"},
|
||||
map[string]any{"type": "tool_result", "tool_use_id": "toolu_1", "content": map[string]any{"ok": true}},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
Candidate: store.RuntimeModelCandidate{
|
||||
BaseURL: server.URL,
|
||||
ProviderModelName: "openai-compatible-gpt-4o-mini",
|
||||
Credentials: map[string]any{"apiKey": "test-key"},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("run openai client: %v", err)
|
||||
}
|
||||
messages, _ := captured["messages"].([]any)
|
||||
if len(messages) != 4 {
|
||||
t.Fatalf("unexpected normalized messages: %+v", messages)
|
||||
}
|
||||
assistant, _ := messages[0].(map[string]any)
|
||||
if _, ok := assistant["functionCall"]; ok {
|
||||
t.Fatalf("functionCall should be converted away: %+v", assistant)
|
||||
}
|
||||
toolCalls, _ := assistant["tool_calls"].([]any)
|
||||
toolCall, _ := toolCalls[0].(map[string]any)
|
||||
function, _ := toolCall["function"].(map[string]any)
|
||||
if function["name"] != "lookup" || function["arguments"] != `{"q":"weather"}` {
|
||||
t.Fatalf("unexpected normalized tool call: %+v", assistant)
|
||||
}
|
||||
toolMessage, _ := messages[1].(map[string]any)
|
||||
if toolMessage["tool_call_id"] != "call_0" || toolMessage["toolCallId"] != nil {
|
||||
t.Fatalf("tool message was not normalized: %+v", toolMessage)
|
||||
}
|
||||
keptUser, _ := messages[2].(map[string]any)
|
||||
convertedToolResult, _ := messages[3].(map[string]any)
|
||||
if keptUser["content"] != "keep this" || convertedToolResult["role"] != "tool" || convertedToolResult["tool_call_id"] != "toolu_1" || convertedToolResult["content"] != `{"ok":true}` {
|
||||
t.Fatalf("tool_result block was not restored: user=%+v tool=%+v", keptUser, convertedToolResult)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIClientChatResponseNormalizesReasoning(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"id": "chatcmpl-reasoning",
|
||||
"object": "chat.completion",
|
||||
"model": "openrouter-test",
|
||||
"choices": []any{map[string]any{
|
||||
"message": map[string]any{
|
||||
"role": "assistant",
|
||||
"reasoning_details": []any{
|
||||
map[string]any{"type": "reasoning.text", "text": "detail-"},
|
||||
map[string]any{"type": "reasoning.summary", "summary": "summary"},
|
||||
map[string]any{"type": "reasoning.encrypted", "data": "secret"},
|
||||
},
|
||||
"content": "<think>tagged</think>answer",
|
||||
},
|
||||
}},
|
||||
})
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
response, err := (OpenAIClient{HTTPClient: server.Client()}).Run(context.Background(), Request{
|
||||
Kind: "chat.completions",
|
||||
Model: "OpenRouter-Test",
|
||||
Body: map[string]any{"model": "OpenRouter-Test", "messages": []any{map[string]any{"role": "user", "content": "ping"}}},
|
||||
Candidate: store.RuntimeModelCandidate{
|
||||
BaseURL: server.URL,
|
||||
ModelName: "openrouter-test",
|
||||
Credentials: map[string]any{"apiKey": "test-key"},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("run openai client: %v", err)
|
||||
}
|
||||
choices, _ := response.Result["choices"].([]any)
|
||||
choice, _ := choices[0].(map[string]any)
|
||||
message, _ := choice["message"].(map[string]any)
|
||||
if message["reasoning_content"] != "detail-summarytagged" || message["content"] != "answer" {
|
||||
t.Fatalf("reasoning was not normalized: %+v", response.Result)
|
||||
}
|
||||
if _, ok := message["reasoning_details"]; ok {
|
||||
t.Fatalf("reasoning_details should be converted away: %+v", message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIClientChatResponseNormalizesToolCallFormats(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"id": "chatcmpl-tools",
|
||||
"object": "chat.completion",
|
||||
"model": "tool-format-test",
|
||||
"choices": []any{map[string]any{
|
||||
"message": map[string]any{
|
||||
"role": "assistant",
|
||||
"content": []any{
|
||||
map[string]any{"type": "text", "text": "calling tools"},
|
||||
map[string]any{"type": "tool_use", "id": "toolu_1", "name": "anthropic_lookup", "input": map[string]any{"city": "Boston"}},
|
||||
},
|
||||
"toolCalls": []any{map[string]any{"id": "call_camel", "functionCall": map[string]any{"name": "camel_lookup", "args": map[string]any{"city": "SF"}}}},
|
||||
"function_call": map[string]any{"name": "legacy_lookup", "arguments": "{\"city\":\"NYC\"}"},
|
||||
},
|
||||
}},
|
||||
})
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
response, err := (OpenAIClient{HTTPClient: server.Client()}).Run(context.Background(), Request{
|
||||
Kind: "chat.completions",
|
||||
Model: "Tool-Format-Test",
|
||||
Body: map[string]any{"model": "Tool-Format-Test", "messages": []any{map[string]any{"role": "user", "content": "ping"}}},
|
||||
Candidate: store.RuntimeModelCandidate{
|
||||
BaseURL: server.URL,
|
||||
ModelName: "tool-format-test",
|
||||
Credentials: map[string]any{"apiKey": "test-key"},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("run openai client: %v", err)
|
||||
}
|
||||
choices, _ := response.Result["choices"].([]any)
|
||||
choice, _ := choices[0].(map[string]any)
|
||||
message, _ := choice["message"].(map[string]any)
|
||||
if message["content"] != "calling tools" {
|
||||
t.Fatalf("tool_use block should be removed from content: %+v", message)
|
||||
}
|
||||
for _, key := range []string{"toolCalls", "function_call"} {
|
||||
if _, ok := message[key]; ok {
|
||||
t.Fatalf("%s should be converted away: %+v", key, message)
|
||||
}
|
||||
}
|
||||
toolCalls, _ := message["tool_calls"].([]any)
|
||||
if len(toolCalls) != 3 {
|
||||
t.Fatalf("expected 3 normalized tool calls, got %+v", message)
|
||||
}
|
||||
assertToolCall := func(index int, id string, name string, arguments string) {
|
||||
t.Helper()
|
||||
toolCall, _ := toolCalls[index].(map[string]any)
|
||||
function, _ := toolCall["function"].(map[string]any)
|
||||
if toolCall["id"] != id || toolCall["type"] != "function" || function["name"] != name || function["arguments"] != arguments {
|
||||
t.Fatalf("unexpected tool call[%d]: %+v", index, toolCall)
|
||||
}
|
||||
}
|
||||
assertToolCall(0, "call_camel", "camel_lookup", "{\"city\":\"SF\"}")
|
||||
assertToolCall(1, "call_1", "legacy_lookup", "{\"city\":\"NYC\"}")
|
||||
assertToolCall(2, "toolu_1", "anthropic_lookup", "{\"city\":\"Boston\"}")
|
||||
}
|
||||
|
||||
func TestOpenAIClientChatStreamContract(t *testing.T) {
|
||||
var gotStream bool
|
||||
var gotIncludeUsage bool
|
||||
@@ -204,6 +385,133 @@ func TestOpenAIClientChatStreamContract(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIClientChatStreamPreservesStructuredDeltas(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte("data: {\"id\":\"chatcmpl-structured\",\"object\":\"chat.completion.chunk\",\"model\":\"openrouter-reasoner\",\"choices\":[{\"delta\":{\"reasoning_details\":[{\"type\":\"reasoning.text\",\"text\":\"detail-\"},{\"type\":\"reasoning.summary\",\"summary\":\"summary\"},{\"type\":\"reasoning.encrypted\",\"data\":\"secret\"}]}}],\"usage\":null}\n\n"))
|
||||
_, _ = w.Write([]byte("data: {\"id\":\"chatcmpl-structured\",\"object\":\"chat.completion.chunk\",\"model\":\"openrouter-reasoner\",\"choices\":[{\"delta\":{\"content\":\"<think>tagged</think>answer\"}}],\"usage\":null}\n\n"))
|
||||
_, _ = w.Write([]byte("data: {\"id\":\"chatcmpl-structured\",\"object\":\"chat.completion.chunk\",\"model\":\"deepseek-v4\",\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_1\",\"type\":\"function\",\"function\":{\"name\":\"lookup\",\"arguments\":\"{\\\"q\\\":\"}}]}}],\"usage\":null}\n\n"))
|
||||
_, _ = w.Write([]byte("data: {\"id\":\"chatcmpl-structured\",\"object\":\"chat.completion.chunk\",\"model\":\"deepseek-v4\",\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"\\\"weather\\\"}\"}}]},\"finish_reason\":\"tool_calls\"}],\"usage\":null}\n\n"))
|
||||
_, _ = w.Write([]byte("data: [DONE]\n\n"))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
captured := make([]StreamDeltaEvent, 0)
|
||||
response, err := (OpenAIClient{HTTPClient: server.Client()}).Run(context.Background(), Request{
|
||||
Kind: "chat.completions",
|
||||
Model: "DeepSeek-V4",
|
||||
Body: map[string]any{
|
||||
"model": "DeepSeek-V4",
|
||||
"messages": []any{map[string]any{"role": "user", "content": "ping"}},
|
||||
"stream": true,
|
||||
},
|
||||
Candidate: store.RuntimeModelCandidate{
|
||||
BaseURL: server.URL,
|
||||
ModelName: "deepseek-v4",
|
||||
Credentials: map[string]any{"apiKey": "test-key"},
|
||||
},
|
||||
StreamDelta: func(event StreamDeltaEvent) error {
|
||||
captured = append(captured, event)
|
||||
return nil
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("run openai structured stream client: %v", err)
|
||||
}
|
||||
if len(captured) != 4 || captured[0].ReasoningContent != "detail-summary" || captured[1].ReasoningContent != "tagged" || captured[1].Text != "answer" || captured[2].Event == nil {
|
||||
t.Fatalf("structured stream events were not preserved: %+v", captured)
|
||||
}
|
||||
firstChoices, _ := captured[0].Event["choices"].([]any)
|
||||
firstChoice, _ := firstChoices[0].(map[string]any)
|
||||
firstDelta, _ := firstChoice["delta"].(map[string]any)
|
||||
if firstDelta["reasoning_content"] != "detail-summary" {
|
||||
t.Fatalf("reasoning_details were not converted in stream event: %+v", captured[0].Event)
|
||||
}
|
||||
if _, ok := firstDelta["reasoning_details"]; ok {
|
||||
t.Fatalf("reasoning_details should be removed from stream event: %+v", captured[0].Event)
|
||||
}
|
||||
choices, _ := response.Result["choices"].([]any)
|
||||
choice, _ := choices[0].(map[string]any)
|
||||
message, _ := choice["message"].(map[string]any)
|
||||
if message["reasoning_content"] != "detail-summarytagged" || message["content"] != "answer" || choice["finish_reason"] != "tool_calls" {
|
||||
t.Fatalf("reasoning or finish reason missing from aggregated result: %+v", response.Result)
|
||||
}
|
||||
toolCalls, _ := message["tool_calls"].([]any)
|
||||
toolCall, _ := toolCalls[0].(map[string]any)
|
||||
function, _ := toolCall["function"].(map[string]any)
|
||||
if function["arguments"] != "{\"q\":\"weather\"}" {
|
||||
t.Fatalf("tool call arguments were not aggregated: %+v", response.Result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIClientChatStreamNormalizesToolCallFormats(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte("data: {\"id\":\"chatcmpl-tools-stream\",\"object\":\"chat.completion.chunk\",\"model\":\"tool-format-test\",\"choices\":[{\"delta\":{\"function_call\":{\"name\":\"legacy_lookup\",\"arguments\":\"{\\\"city\\\":\"}}}],\"usage\":null}\n\n"))
|
||||
_, _ = w.Write([]byte("data: {\"id\":\"chatcmpl-tools-stream\",\"object\":\"chat.completion.chunk\",\"model\":\"tool-format-test\",\"choices\":[{\"delta\":{\"functionCall\":{\"arguments\":\"\\\"Boston\\\"}\"}}}],\"usage\":null}\n\n"))
|
||||
_, _ = w.Write([]byte("data: {\"id\":\"chatcmpl-tools-stream\",\"object\":\"chat.completion.chunk\",\"model\":\"tool-format-test\",\"choices\":[{\"delta\":{\"toolCall\":{\"index\":1,\"id\":\"call_camel\",\"functionCall\":{\"name\":\"camel_lookup\",\"args\":{\"city\":\"SF\"}}}},\"finish_reason\":\"tool_calls\"}],\"usage\":null}\n\n"))
|
||||
_, _ = w.Write([]byte("data: [DONE]\n\n"))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
captured := make([]StreamDeltaEvent, 0)
|
||||
response, err := (OpenAIClient{HTTPClient: server.Client()}).Run(context.Background(), Request{
|
||||
Kind: "chat.completions",
|
||||
Model: "Tool-Format-Test",
|
||||
Body: map[string]any{
|
||||
"model": "Tool-Format-Test",
|
||||
"messages": []any{map[string]any{"role": "user", "content": "ping"}},
|
||||
"stream": true,
|
||||
},
|
||||
Candidate: store.RuntimeModelCandidate{
|
||||
BaseURL: server.URL,
|
||||
ModelName: "tool-format-test",
|
||||
Credentials: map[string]any{"apiKey": "test-key"},
|
||||
},
|
||||
StreamDelta: func(event StreamDeltaEvent) error {
|
||||
captured = append(captured, event)
|
||||
return nil
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("run openai stream client: %v", err)
|
||||
}
|
||||
if len(captured) != 3 {
|
||||
t.Fatalf("unexpected captured events: %+v", captured)
|
||||
}
|
||||
for _, event := range captured {
|
||||
choices, _ := event.Event["choices"].([]any)
|
||||
choice, _ := choices[0].(map[string]any)
|
||||
delta, _ := choice["delta"].(map[string]any)
|
||||
if _, ok := delta["function_call"]; ok {
|
||||
t.Fatalf("function_call should be converted away: %+v", event.Event)
|
||||
}
|
||||
if _, ok := delta["functionCall"]; ok {
|
||||
t.Fatalf("functionCall should be converted away: %+v", event.Event)
|
||||
}
|
||||
if _, ok := delta["toolCall"]; ok {
|
||||
t.Fatalf("toolCall should be converted away: %+v", event.Event)
|
||||
}
|
||||
}
|
||||
choices, _ := response.Result["choices"].([]any)
|
||||
choice, _ := choices[0].(map[string]any)
|
||||
message, _ := choice["message"].(map[string]any)
|
||||
toolCalls, _ := message["tool_calls"].([]any)
|
||||
if len(toolCalls) != 2 || choice["finish_reason"] != "tool_calls" {
|
||||
t.Fatalf("unexpected normalized stream result: %+v", response.Result)
|
||||
}
|
||||
legacyCall, _ := toolCalls[0].(map[string]any)
|
||||
legacyFunction, _ := legacyCall["function"].(map[string]any)
|
||||
if legacyFunction["name"] != "legacy_lookup" || legacyFunction["arguments"] != "{\"city\":\"Boston\"}" {
|
||||
t.Fatalf("legacy function_call was not aggregated: %+v", response.Result)
|
||||
}
|
||||
camelCall, _ := toolCalls[1].(map[string]any)
|
||||
camelFunction, _ := camelCall["function"].(map[string]any)
|
||||
if camelCall["id"] != "call_camel" || camelFunction["name"] != "camel_lookup" || camelFunction["arguments"] != "{\"city\":\"SF\"}" {
|
||||
t.Fatalf("camel toolCall was not normalized: %+v", response.Result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeminiClientChatContract(t *testing.T) {
|
||||
var gotPath string
|
||||
var gotKey string
|
||||
@@ -261,6 +569,92 @@ func TestGeminiClientChatContract(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeminiClientChatRestoresToolContext(t *testing.T) {
|
||||
var captured map[string]any
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := json.NewDecoder(r.Body).Decode(&captured); err != nil {
|
||||
t.Fatalf("decode request: %v", err)
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"candidates": []any{map[string]any{
|
||||
"content": map[string]any{"parts": []any{map[string]any{"text": "gemini ok"}}},
|
||||
}},
|
||||
})
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
_, err := (GeminiClient{HTTPClient: server.Client()}).Run(context.Background(), Request{
|
||||
Kind: "chat.completions",
|
||||
Model: "gemini:gemini-2.5-flash",
|
||||
Body: map[string]any{
|
||||
"model": "gemini:gemini-2.5-flash",
|
||||
"messages": []any{
|
||||
map[string]any{"role": "user", "content": "weather?"},
|
||||
map[string]any{
|
||||
"role": "assistant",
|
||||
"content": "checking",
|
||||
"tool_calls": []any{map[string]any{
|
||||
"id": "call_weather",
|
||||
"type": "function",
|
||||
"function": map[string]any{
|
||||
"name": "get_weather",
|
||||
"arguments": `{"city":"SF"}`,
|
||||
},
|
||||
}},
|
||||
},
|
||||
map[string]any{"role": "tool", "tool_call_id": "call_weather", "content": `{"temperature":"72F"}`},
|
||||
},
|
||||
"tools": []any{map[string]any{
|
||||
"type": "function",
|
||||
"function": map[string]any{
|
||||
"name": "get_weather",
|
||||
"description": "lookup weather",
|
||||
"parameters": map[string]any{"type": "object"},
|
||||
},
|
||||
}},
|
||||
},
|
||||
Candidate: store.RuntimeModelCandidate{
|
||||
BaseURL: server.URL,
|
||||
ProviderModelName: "gemini-2.5-flash",
|
||||
ModelType: "chat",
|
||||
Credentials: map[string]any{"apiKey": "gemini-key"},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("run gemini client: %v", err)
|
||||
}
|
||||
contents, _ := captured["contents"].([]any)
|
||||
if len(contents) != 3 {
|
||||
t.Fatalf("unexpected Gemini contents: %+v", captured)
|
||||
}
|
||||
modelTurn, _ := contents[1].(map[string]any)
|
||||
if modelTurn["role"] != "model" {
|
||||
t.Fatalf("assistant turn should become Gemini model turn: %+v", modelTurn)
|
||||
}
|
||||
modelParts, _ := modelTurn["parts"].([]any)
|
||||
callPart, _ := modelParts[1].(map[string]any)
|
||||
functionCall, _ := callPart["functionCall"].(map[string]any)
|
||||
args, _ := functionCall["args"].(map[string]any)
|
||||
if functionCall["name"] != "get_weather" || args["city"] != "SF" {
|
||||
t.Fatalf("tool call was not restored for Gemini: %+v", modelTurn)
|
||||
}
|
||||
toolTurn, _ := contents[2].(map[string]any)
|
||||
toolParts, _ := toolTurn["parts"].([]any)
|
||||
responsePart, _ := toolParts[0].(map[string]any)
|
||||
functionResponse, _ := responsePart["functionResponse"].(map[string]any)
|
||||
response, _ := functionResponse["response"].(map[string]any)
|
||||
if toolTurn["role"] != "user" || functionResponse["name"] != "get_weather" || response["temperature"] != "72F" {
|
||||
t.Fatalf("tool result was not restored for Gemini: %+v", toolTurn)
|
||||
}
|
||||
tools, _ := captured["tools"].([]any)
|
||||
declarationGroup, _ := tools[0].(map[string]any)
|
||||
declarations, _ := declarationGroup["functionDeclarations"].([]any)
|
||||
declaration, _ := declarations[0].(map[string]any)
|
||||
if declaration["name"] != "get_weather" || declaration["description"] != "lookup weather" {
|
||||
t.Fatalf("tool declaration was not converted for Gemini: %+v", captured["tools"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeminiURLAcceptsVersionedBaseURL(t *testing.T) {
|
||||
got := geminiURL("https://generativelanguage.googleapis.com/v1beta", "gemini-2.5-flash", "test-key")
|
||||
want := "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=test-key"
|
||||
|
||||
@@ -70,15 +70,185 @@ func geminiBody(request Request) map[string]any {
|
||||
return map[string]any{"contents": contents}
|
||||
}
|
||||
prompt := firstNonEmptyPrompt(request.Body, "")
|
||||
if prompt == "" {
|
||||
prompt = textFromMessages(request.Body)
|
||||
if prompt != "" {
|
||||
return map[string]any{
|
||||
"contents": []any{map[string]any{
|
||||
"role": "user",
|
||||
"parts": []any{map[string]any{"text": prompt}},
|
||||
}},
|
||||
}
|
||||
}
|
||||
return map[string]any{
|
||||
"contents": []any{map[string]any{
|
||||
"role": "user",
|
||||
"parts": []any{map[string]any{"text": prompt}},
|
||||
}},
|
||||
body := map[string]any{"contents": geminiContentsFromMessages(request.Body)}
|
||||
if tools := geminiToolsFromOpenAITools(request.Body["tools"]); len(tools) > 0 {
|
||||
body["tools"] = tools
|
||||
}
|
||||
contents, _ := body["contents"].([]any)
|
||||
if len(contents) > 0 {
|
||||
return body
|
||||
}
|
||||
return map[string]any{"contents": []any{map[string]any{
|
||||
"role": "user",
|
||||
"parts": []any{map[string]any{"text": textFromMessages(request.Body)}},
|
||||
}}}
|
||||
}
|
||||
|
||||
func geminiContentsFromMessages(body map[string]any) []any {
|
||||
normalized := NormalizeChatCompletionRequestBody(body)
|
||||
messages, _ := normalized["messages"].([]any)
|
||||
contents := make([]any, 0, len(messages))
|
||||
toolNames := map[string]string{}
|
||||
for _, rawMessage := range messages {
|
||||
message, _ := rawMessage.(map[string]any)
|
||||
if len(message) == 0 {
|
||||
continue
|
||||
}
|
||||
role := stringFromAny(message["role"])
|
||||
if role == "tool" {
|
||||
toolCallID := stringFromAny(message["tool_call_id"])
|
||||
name := toolNames[toolCallID]
|
||||
if name == "" {
|
||||
name = toolCallID
|
||||
}
|
||||
if name == "" {
|
||||
name = "tool"
|
||||
}
|
||||
contents = append(contents, map[string]any{
|
||||
"role": "user",
|
||||
"parts": []any{map[string]any{"functionResponse": map[string]any{
|
||||
"name": name,
|
||||
"response": geminiFunctionResponsePayload(message["content"]),
|
||||
}}},
|
||||
})
|
||||
continue
|
||||
}
|
||||
parts := geminiTextParts(message["content"])
|
||||
if role == "assistant" {
|
||||
for _, rawToolCall := range toolCallsSlice(message["tool_calls"]) {
|
||||
toolCall, _ := rawToolCall.(map[string]any)
|
||||
function, _ := toolCall["function"].(map[string]any)
|
||||
name := stringFromAny(function["name"])
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
if id := stringFromAny(toolCall["id"]); id != "" {
|
||||
toolNames[id] = name
|
||||
}
|
||||
parts = append(parts, map[string]any{"functionCall": map[string]any{
|
||||
"name": name,
|
||||
"args": geminiFunctionArgs(function["arguments"]),
|
||||
}})
|
||||
}
|
||||
}
|
||||
if len(parts) == 0 {
|
||||
continue
|
||||
}
|
||||
contents = append(contents, map[string]any{
|
||||
"role": geminiRole(role),
|
||||
"parts": parts,
|
||||
})
|
||||
}
|
||||
return contents
|
||||
}
|
||||
|
||||
func geminiRole(role string) string {
|
||||
if role == "assistant" {
|
||||
return "model"
|
||||
}
|
||||
return "user"
|
||||
}
|
||||
|
||||
func geminiTextParts(content any) []any {
|
||||
parts := make([]any, 0)
|
||||
switch typed := content.(type) {
|
||||
case string:
|
||||
if strings.TrimSpace(typed) != "" {
|
||||
parts = append(parts, map[string]any{"text": typed})
|
||||
}
|
||||
case []any:
|
||||
for _, rawPart := range typed {
|
||||
part, _ := rawPart.(map[string]any)
|
||||
if text := stringFromAny(firstPresent(part["text"], part["content"])); strings.TrimSpace(text) != "" {
|
||||
parts = append(parts, map[string]any{"text": text})
|
||||
}
|
||||
}
|
||||
}
|
||||
return parts
|
||||
}
|
||||
|
||||
func toolCallsSlice(value any) []any {
|
||||
switch typed := value.(type) {
|
||||
case []any:
|
||||
return typed
|
||||
case map[string]any:
|
||||
return []any{typed}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func geminiFunctionArgs(value any) map[string]any {
|
||||
if value == nil {
|
||||
return map[string]any{}
|
||||
}
|
||||
if args, ok := value.(map[string]any); ok {
|
||||
return args
|
||||
}
|
||||
if text, ok := value.(string); ok {
|
||||
if strings.TrimSpace(text) == "" {
|
||||
return map[string]any{}
|
||||
}
|
||||
var args map[string]any
|
||||
if err := json.Unmarshal([]byte(text), &args); err == nil {
|
||||
return args
|
||||
}
|
||||
return map[string]any{"arguments": text}
|
||||
}
|
||||
return map[string]any{"arguments": value}
|
||||
}
|
||||
|
||||
func geminiFunctionResponsePayload(value any) map[string]any {
|
||||
if payload, ok := value.(map[string]any); ok {
|
||||
return payload
|
||||
}
|
||||
if text, ok := value.(string); ok {
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal([]byte(text), &payload); err == nil {
|
||||
return payload
|
||||
}
|
||||
return map[string]any{"content": text}
|
||||
}
|
||||
if value == nil {
|
||||
return map[string]any{}
|
||||
}
|
||||
return map[string]any{"content": value}
|
||||
}
|
||||
|
||||
func geminiToolsFromOpenAITools(value any) []any {
|
||||
tools, ok := value.([]any)
|
||||
if !ok || len(tools) == 0 {
|
||||
return nil
|
||||
}
|
||||
declarations := make([]any, 0, len(tools))
|
||||
for _, rawTool := range tools {
|
||||
tool, _ := rawTool.(map[string]any)
|
||||
function, _ := tool["function"].(map[string]any)
|
||||
name := stringFromAny(function["name"])
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
declaration := map[string]any{"name": name}
|
||||
if description := stringFromAny(function["description"]); description != "" {
|
||||
declaration["description"] = description
|
||||
}
|
||||
if parameters, ok := function["parameters"]; ok {
|
||||
declaration["parameters"] = parameters
|
||||
}
|
||||
declarations = append(declarations, declaration)
|
||||
}
|
||||
if len(declarations) == 0 {
|
||||
return nil
|
||||
}
|
||||
return []any{map[string]any{"functionDeclarations": declarations}}
|
||||
}
|
||||
|
||||
func geminiResult(request Request, raw map[string]any) map[string]any {
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -87,8 +88,11 @@ func decodeOpenAIStreamReader(reader io.Reader, onDelta StreamDelta) (map[string
|
||||
scanner.Buffer(make([]byte, 0, 64*1024), 16*1024*1024)
|
||||
rawLines := make([]string, 0)
|
||||
parts := make([]string, 0)
|
||||
reasoningParts := make([]string, 0)
|
||||
var last map[string]any
|
||||
var usage Usage
|
||||
finishReason := ""
|
||||
toolCalls := map[int]map[string]any{}
|
||||
for scanner.Scan() {
|
||||
rawLine := scanner.Text()
|
||||
rawLines = append(rawLines, rawLine)
|
||||
@@ -104,13 +108,23 @@ func decodeOpenAIStreamReader(reader io.Reader, onDelta StreamDelta) (map[string
|
||||
if err := json.Unmarshal([]byte(payload), &event); err != nil {
|
||||
continue
|
||||
}
|
||||
event = NormalizeChatCompletionStreamEvent(event)
|
||||
last = event
|
||||
if text := streamEventText(event); text != "" {
|
||||
text := streamEventText(event)
|
||||
reasoningText := streamEventReasoningContent(event)
|
||||
if text != "" {
|
||||
parts = append(parts, text)
|
||||
if onDelta != nil {
|
||||
if err := onDelta(text); err != nil {
|
||||
return nil, true, err
|
||||
}
|
||||
}
|
||||
if reasoningText != "" {
|
||||
reasoningParts = append(reasoningParts, reasoningText)
|
||||
}
|
||||
aggregateStreamToolCalls(event, toolCalls)
|
||||
if reason := streamEventFinishReason(event); reason != "" {
|
||||
finishReason = reason
|
||||
}
|
||||
if onDelta != nil {
|
||||
if err := onDelta(StreamDeltaEvent{Text: text, ReasoningContent: reasoningText, Event: event}); err != nil {
|
||||
return nil, true, err
|
||||
}
|
||||
}
|
||||
if eventUsage := usageFromOpenAI(event); eventUsage.TotalTokens > 0 {
|
||||
@@ -131,7 +145,7 @@ func decodeOpenAIStreamReader(reader io.Reader, onDelta StreamDelta) (map[string
|
||||
}
|
||||
return out, true, nil
|
||||
}
|
||||
return buildOpenAIStreamResult(last, parts, usage), true, nil
|
||||
return buildOpenAIStreamResult(last, parts, reasoningParts, toolCalls, finishReason, usage), true, nil
|
||||
}
|
||||
|
||||
func decodeOpenAIStream(raw []byte) (map[string]any, bool) {
|
||||
@@ -142,22 +156,32 @@ func decodeOpenAIStream(raw []byte) (map[string]any, bool) {
|
||||
return result, ok && err == nil
|
||||
}
|
||||
|
||||
func buildOpenAIStreamResult(last map[string]any, parts []string, usage Usage) map[string]any {
|
||||
if len(parts) == 0 {
|
||||
func buildOpenAIStreamResult(last map[string]any, parts []string, reasoningParts []string, toolCalls map[int]map[string]any, finishReason string, usage Usage) map[string]any {
|
||||
if len(parts) == 0 && len(reasoningParts) == 0 && len(toolCalls) == 0 {
|
||||
return last
|
||||
}
|
||||
message := map[string]any{
|
||||
"role": "assistant",
|
||||
"content": strings.Join(parts, ""),
|
||||
}
|
||||
if len(reasoningParts) > 0 {
|
||||
message["reasoning_content"] = strings.Join(reasoningParts, "")
|
||||
}
|
||||
if len(toolCalls) > 0 {
|
||||
message["tool_calls"] = sortedStreamToolCalls(toolCalls)
|
||||
}
|
||||
if finishReason == "" {
|
||||
finishReason = "stop"
|
||||
}
|
||||
var out map[string]any
|
||||
out = map[string]any{
|
||||
"id": stringFromAny(firstPresent(last["id"], "chatcmpl-stream")),
|
||||
"object": "chat.completion",
|
||||
"model": stringFromAny(last["model"]),
|
||||
"choices": []any{map[string]any{
|
||||
"index": 0,
|
||||
"message": map[string]any{
|
||||
"role": "assistant",
|
||||
"content": strings.Join(parts, ""),
|
||||
},
|
||||
"finish_reason": "stop",
|
||||
"index": 0,
|
||||
"message": message,
|
||||
"finish_reason": finishReason,
|
||||
}},
|
||||
}
|
||||
if usage.TotalTokens > 0 {
|
||||
@@ -170,6 +194,571 @@ func buildOpenAIStreamResult(last map[string]any, parts []string, usage Usage) m
|
||||
return out
|
||||
}
|
||||
|
||||
// NormalizeChatCompletionRequestBody 将后续请求里的工具调用上下文还原为
|
||||
// OpenAI Chat Completions 标准格式,便于再次发送给 OpenAI-compatible 上游。
|
||||
func NormalizeChatCompletionRequestBody(body map[string]any) map[string]any {
|
||||
if body == nil {
|
||||
return nil
|
||||
}
|
||||
out := cloneBody(body)
|
||||
messages, ok := out["messages"].([]any)
|
||||
if !ok {
|
||||
return out
|
||||
}
|
||||
normalizedMessages := make([]any, 0, len(messages))
|
||||
for _, rawMessage := range messages {
|
||||
message, ok := rawMessage.(map[string]any)
|
||||
if !ok {
|
||||
normalizedMessages = append(normalizedMessages, rawMessage)
|
||||
continue
|
||||
}
|
||||
copied := cloneMapAny(message)
|
||||
normalizeToolCallsContainer(copied, false)
|
||||
normalizeToolMessageFields(copied)
|
||||
toolMessages, cleanContent, changed := toolResultMessagesFromContent(copied["content"])
|
||||
if changed {
|
||||
if cleanContent != nil && contentHasText(cleanContent) {
|
||||
copied["content"] = cleanContent
|
||||
normalizedMessages = append(normalizedMessages, copied)
|
||||
} else if len(copied) > 1 || copied["role"] != nil {
|
||||
delete(copied, "content")
|
||||
if len(copied) > 1 {
|
||||
normalizedMessages = append(normalizedMessages, copied)
|
||||
}
|
||||
}
|
||||
normalizedMessages = append(normalizedMessages, toolMessages...)
|
||||
continue
|
||||
}
|
||||
normalizedMessages = append(normalizedMessages, copied)
|
||||
}
|
||||
out["messages"] = normalizedMessages
|
||||
return out
|
||||
}
|
||||
|
||||
func cloneMapAny(source map[string]any) map[string]any {
|
||||
if source == nil {
|
||||
return nil
|
||||
}
|
||||
out := make(map[string]any, len(source))
|
||||
for key, value := range source {
|
||||
out[key] = value
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// NormalizeChatCompletionResult 将供应商自定义推理字段归一化到
|
||||
// message.reasoning_content,并从最终回答 content 中剥离内联推理块。
|
||||
// 加密推理载荷不可展示,且不应作为正文输出,因此会被忽略。
|
||||
func NormalizeChatCompletionResult(result map[string]any) map[string]any {
|
||||
if result == nil {
|
||||
return nil
|
||||
}
|
||||
choices, _ := result["choices"].([]any)
|
||||
for _, rawChoice := range choices {
|
||||
choice, _ := rawChoice.(map[string]any)
|
||||
if message, ok := choice["message"].(map[string]any); ok {
|
||||
normalizeToolCallsContainer(message, false)
|
||||
normalizeReasoningContainer(message, false)
|
||||
}
|
||||
if delta, ok := choice["delta"].(map[string]any); ok {
|
||||
normalizeToolCallsContainer(delta, true)
|
||||
normalizeReasoningContainer(delta, true)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// NormalizeChatCompletionStreamEvent 将供应商自定义流式推理字段
|
||||
// (例如 reasoning_details 或 reasoning)归一化到 delta.reasoning_content。
|
||||
func NormalizeChatCompletionStreamEvent(event map[string]any) map[string]any {
|
||||
if event == nil {
|
||||
return nil
|
||||
}
|
||||
choices, _ := event["choices"].([]any)
|
||||
for _, rawChoice := range choices {
|
||||
choice, _ := rawChoice.(map[string]any)
|
||||
if delta, ok := choice["delta"].(map[string]any); ok {
|
||||
normalizeToolCallsContainer(delta, true)
|
||||
normalizeReasoningContainer(delta, true)
|
||||
}
|
||||
if message, ok := choice["message"].(map[string]any); ok {
|
||||
normalizeToolCallsContainer(message, false)
|
||||
normalizeReasoningContainer(message, false)
|
||||
}
|
||||
}
|
||||
return event
|
||||
}
|
||||
|
||||
func normalizeToolCallsContainer(container map[string]any, stream bool) {
|
||||
if container == nil {
|
||||
return
|
||||
}
|
||||
toolCalls := make([]any, 0)
|
||||
for _, rawToolCall := range rawToolCallValues(container) {
|
||||
for _, normalized := range normalizeRawToolCalls(rawToolCall, len(toolCalls), stream) {
|
||||
toolCalls = append(toolCalls, normalized)
|
||||
}
|
||||
}
|
||||
if contentToolCalls, cleanContent, changed := toolCallsFromContent(container["content"], len(toolCalls), stream); changed {
|
||||
toolCalls = append(toolCalls, contentToolCalls...)
|
||||
setNormalizedContent(container, cleanContent, stream)
|
||||
}
|
||||
if partToolCalls := toolCallsFromParts(container["parts"], len(toolCalls), stream); len(partToolCalls) > 0 {
|
||||
toolCalls = append(toolCalls, partToolCalls...)
|
||||
delete(container, "parts")
|
||||
}
|
||||
if len(toolCalls) > 0 {
|
||||
container["tool_calls"] = toolCalls
|
||||
}
|
||||
for _, key := range []string{"tool_call", "toolCall", "toolCalls", "function_call", "functionCall"} {
|
||||
delete(container, key)
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeToolMessageFields(message map[string]any) {
|
||||
if message == nil {
|
||||
return
|
||||
}
|
||||
if id := firstNonEmptyString(message["tool_call_id"], message["toolCallId"], message["tool_use_id"], message["toolUseId"], message["call_id"], message["callId"]); id != "" {
|
||||
message["tool_call_id"] = id
|
||||
}
|
||||
for _, key := range []string{"toolCallId", "tool_use_id", "toolUseId", "call_id", "callId"} {
|
||||
delete(message, key)
|
||||
}
|
||||
}
|
||||
|
||||
func toolResultMessagesFromContent(value any) ([]any, any, bool) {
|
||||
blocks, ok := value.([]any)
|
||||
if !ok {
|
||||
return nil, nil, false
|
||||
}
|
||||
toolMessages := make([]any, 0)
|
||||
remaining := make([]any, 0, len(blocks))
|
||||
for _, rawBlock := range blocks {
|
||||
block, _ := rawBlock.(map[string]any)
|
||||
if len(block) == 0 || stringFromAny(block["type"]) != "tool_result" {
|
||||
remaining = append(remaining, rawBlock)
|
||||
continue
|
||||
}
|
||||
message := map[string]any{
|
||||
"role": "tool",
|
||||
"tool_call_id": firstNonEmptyString(block["tool_call_id"], block["toolCallId"], block["tool_use_id"], block["toolUseId"], block["id"]),
|
||||
"content": toolResultContent(block["content"]),
|
||||
}
|
||||
toolMessages = append(toolMessages, message)
|
||||
}
|
||||
if len(toolMessages) == 0 {
|
||||
return nil, nil, false
|
||||
}
|
||||
return toolMessages, contentBlocksText(remaining), true
|
||||
}
|
||||
|
||||
func toolResultContent(value any) any {
|
||||
if text, ok := value.(string); ok {
|
||||
return text
|
||||
}
|
||||
return jsonStringFromAny(value)
|
||||
}
|
||||
|
||||
func contentHasText(value any) bool {
|
||||
switch typed := value.(type) {
|
||||
case string:
|
||||
return strings.TrimSpace(typed) != ""
|
||||
case []any:
|
||||
return len(typed) > 0
|
||||
default:
|
||||
return value != nil
|
||||
}
|
||||
}
|
||||
|
||||
func rawToolCallValues(container map[string]any) []any {
|
||||
values := make([]any, 0, 6)
|
||||
for _, key := range []string{"tool_calls", "tool_call", "toolCalls", "toolCall", "function_call", "functionCall"} {
|
||||
if value, ok := container[key]; ok {
|
||||
values = append(values, value)
|
||||
}
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
func normalizeRawToolCalls(value any, startIndex int, stream bool) []any {
|
||||
switch typed := value.(type) {
|
||||
case []any:
|
||||
out := make([]any, 0, len(typed))
|
||||
for _, raw := range typed {
|
||||
if toolCall := normalizeToolCall(raw, startIndex+len(out), stream); toolCall != nil {
|
||||
out = append(out, toolCall)
|
||||
}
|
||||
}
|
||||
return out
|
||||
default:
|
||||
if toolCall := normalizeToolCall(value, startIndex, stream); toolCall != nil {
|
||||
return []any{toolCall}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeToolCall(value any, index int, stream bool) map[string]any {
|
||||
source, _ := value.(map[string]any)
|
||||
if len(source) == 0 {
|
||||
return nil
|
||||
}
|
||||
functionSource := mapFromAny(source["function"])
|
||||
if len(functionSource) == 0 {
|
||||
functionSource = mapFromAny(firstPresent(source["function_call"], source["functionCall"]))
|
||||
}
|
||||
name := firstNonEmptyString(
|
||||
functionSource["name"], source["name"], source["function_name"], source["functionName"], source["tool_name"], source["toolName"],
|
||||
)
|
||||
arguments, hasArguments := toolCallArguments(functionSource)
|
||||
if !hasArguments {
|
||||
arguments, hasArguments = toolCallArguments(source)
|
||||
}
|
||||
if name == "" && !hasArguments && firstNonEmptyString(source["id"], source["call_id"], source["callId"], source["tool_call_id"], source["toolCallId"]) == "" {
|
||||
return nil
|
||||
}
|
||||
function := map[string]any{}
|
||||
if name != "" {
|
||||
function["name"] = name
|
||||
}
|
||||
if hasArguments {
|
||||
function["arguments"] = arguments
|
||||
}
|
||||
toolCall := map[string]any{
|
||||
"type": firstNonEmptyString(source["type"], "function"),
|
||||
"function": function,
|
||||
}
|
||||
if id := firstNonEmptyString(source["id"], source["call_id"], source["callId"], source["tool_call_id"], source["toolCallId"]); id != "" {
|
||||
toolCall["id"] = id
|
||||
} else if !stream {
|
||||
toolCall["id"] = fmt.Sprintf("call_%d", index)
|
||||
}
|
||||
if stream {
|
||||
if rawIndex, ok := firstPresent(source["index"], source["idx"]).(float64); ok {
|
||||
toolCall["index"] = int(math.Round(rawIndex))
|
||||
} else if rawIndex, ok := firstPresent(source["index"], source["idx"]).(int); ok {
|
||||
toolCall["index"] = rawIndex
|
||||
} else {
|
||||
toolCall["index"] = index
|
||||
}
|
||||
}
|
||||
return toolCall
|
||||
}
|
||||
|
||||
func toolCallsFromContent(value any, startIndex int, stream bool) ([]any, any, bool) {
|
||||
blocks, ok := value.([]any)
|
||||
if !ok {
|
||||
return nil, nil, false
|
||||
}
|
||||
toolCalls := make([]any, 0)
|
||||
remaining := make([]any, 0, len(blocks))
|
||||
containsReasoning := false
|
||||
for _, rawBlock := range blocks {
|
||||
block, _ := rawBlock.(map[string]any)
|
||||
if len(block) == 0 {
|
||||
remaining = append(remaining, rawBlock)
|
||||
continue
|
||||
}
|
||||
switch stringFromAny(block["type"]) {
|
||||
case "tool_use":
|
||||
if toolCall := normalizeToolUseBlock(block, startIndex+len(toolCalls), stream); toolCall != nil {
|
||||
toolCalls = append(toolCalls, toolCall)
|
||||
}
|
||||
case "tool_result":
|
||||
remaining = append(remaining, rawBlock)
|
||||
default:
|
||||
if isReasoningContentBlock(block) {
|
||||
containsReasoning = true
|
||||
}
|
||||
remaining = append(remaining, rawBlock)
|
||||
}
|
||||
}
|
||||
if len(toolCalls) == 0 {
|
||||
return nil, nil, false
|
||||
}
|
||||
if containsReasoning {
|
||||
return toolCalls, remaining, true
|
||||
}
|
||||
return toolCalls, contentBlocksText(remaining), true
|
||||
}
|
||||
|
||||
func normalizeToolUseBlock(block map[string]any, index int, stream bool) map[string]any {
|
||||
toolCall := map[string]any{
|
||||
"type": "function",
|
||||
"function": map[string]any{
|
||||
"name": stringFromAny(block["name"]),
|
||||
"arguments": jsonStringFromAny(block["input"]),
|
||||
},
|
||||
}
|
||||
if id := firstNonEmptyString(block["id"], block["tool_use_id"], block["toolUseId"]); id != "" {
|
||||
toolCall["id"] = id
|
||||
} else if !stream {
|
||||
toolCall["id"] = fmt.Sprintf("call_%d", index)
|
||||
}
|
||||
if stream {
|
||||
toolCall["index"] = index
|
||||
}
|
||||
return toolCall
|
||||
}
|
||||
|
||||
func toolCallsFromParts(value any, startIndex int, stream bool) []any {
|
||||
parts, ok := value.([]any)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
out := make([]any, 0)
|
||||
for _, rawPart := range parts {
|
||||
part, _ := rawPart.(map[string]any)
|
||||
if functionCall := mapFromAny(firstPresent(part["functionCall"], part["function_call"])); len(functionCall) > 0 {
|
||||
if toolCall := normalizeGeminiFunctionCall(functionCall, startIndex+len(out), stream); toolCall != nil {
|
||||
out = append(out, toolCall)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func normalizeGeminiFunctionCall(functionCall map[string]any, index int, stream bool) map[string]any {
|
||||
toolCall := map[string]any{
|
||||
"type": "function",
|
||||
"function": map[string]any{
|
||||
"name": stringFromAny(functionCall["name"]),
|
||||
"arguments": jsonStringFromAny(firstPresent(functionCall["args"], functionCall["arguments"])),
|
||||
},
|
||||
}
|
||||
if id := firstNonEmptyString(functionCall["id"], functionCall["call_id"], functionCall["callId"]); id != "" {
|
||||
toolCall["id"] = id
|
||||
} else if !stream {
|
||||
toolCall["id"] = fmt.Sprintf("call_%d", index)
|
||||
}
|
||||
if stream {
|
||||
toolCall["index"] = index
|
||||
}
|
||||
return toolCall
|
||||
}
|
||||
|
||||
func setNormalizedContent(container map[string]any, value any, stream bool) {
|
||||
if text, ok := value.(string); ok && text == "" {
|
||||
if stream {
|
||||
delete(container, "content")
|
||||
return
|
||||
}
|
||||
container["content"] = nil
|
||||
return
|
||||
}
|
||||
container["content"] = value
|
||||
}
|
||||
|
||||
func isReasoningContentBlock(block map[string]any) bool {
|
||||
switch stringFromAny(block["type"]) {
|
||||
case "thinking", "redacted_thinking", "reasoning.text", "reasoning.summary", "reasoning.encrypted":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func contentBlocksText(blocks []any) string {
|
||||
parts := make([]string, 0, len(blocks))
|
||||
for _, rawBlock := range blocks {
|
||||
switch block := rawBlock.(type) {
|
||||
case string:
|
||||
parts = append(parts, block)
|
||||
case map[string]any:
|
||||
if text := stringFromAny(firstPresent(block["text"], block["content"])); text != "" {
|
||||
parts = append(parts, text)
|
||||
}
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, "")
|
||||
}
|
||||
|
||||
func toolCallArguments(source map[string]any) (string, bool) {
|
||||
for _, key := range []string{"arguments", "args", "input", "parameters"} {
|
||||
if value, ok := source[key]; ok {
|
||||
return jsonStringFromAny(value), true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func jsonStringFromAny(value any) string {
|
||||
if value == nil {
|
||||
return ""
|
||||
}
|
||||
if text, ok := value.(string); ok {
|
||||
return text
|
||||
}
|
||||
encoded, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return string(encoded)
|
||||
}
|
||||
|
||||
func normalizeReasoningContainer(container map[string]any, deleteEmptyContent bool) {
|
||||
if container == nil {
|
||||
return
|
||||
}
|
||||
reasoningParts := make([]string, 0, 3)
|
||||
if reasoning := reasoningDetailsText(container["reasoning_details"]); reasoning != "" {
|
||||
reasoningParts = append(reasoningParts, reasoning)
|
||||
} else if reasoning := stringFromAny(container["reasoning_content"]); reasoning != "" {
|
||||
reasoningParts = append(reasoningParts, reasoning)
|
||||
} else if reasoning := stringFromAny(container["reasoning"]); reasoning != "" {
|
||||
reasoningParts = append(reasoningParts, reasoning)
|
||||
}
|
||||
if content, ok := container["content"]; ok {
|
||||
cleanContent, contentReasoning, changed := normalizeReasoningContentValue(content)
|
||||
if changed {
|
||||
if deleteEmptyContent {
|
||||
if text, ok := cleanContent.(string); ok && text == "" {
|
||||
delete(container, "content")
|
||||
} else {
|
||||
container["content"] = cleanContent
|
||||
}
|
||||
} else {
|
||||
container["content"] = cleanContent
|
||||
}
|
||||
}
|
||||
if contentReasoning != "" {
|
||||
reasoningParts = append(reasoningParts, contentReasoning)
|
||||
}
|
||||
}
|
||||
if len(reasoningParts) > 0 {
|
||||
container["reasoning_content"] = strings.Join(reasoningParts, "")
|
||||
}
|
||||
delete(container, "reasoning_details")
|
||||
delete(container, "reasoning")
|
||||
}
|
||||
|
||||
func reasoningDetailsText(value any) string {
|
||||
rawItems, ok := value.([]any)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
parts := make([]string, 0, len(rawItems))
|
||||
for _, rawItem := range rawItems {
|
||||
item, _ := rawItem.(map[string]any)
|
||||
switch stringFromAny(item["type"]) {
|
||||
case "reasoning.text":
|
||||
if text := stringFromAny(item["text"]); text != "" {
|
||||
parts = append(parts, text)
|
||||
}
|
||||
case "reasoning.summary":
|
||||
if summary := stringFromAny(item["summary"]); summary != "" {
|
||||
parts = append(parts, summary)
|
||||
}
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, "")
|
||||
}
|
||||
|
||||
func normalizeReasoningContentValue(value any) (any, string, bool) {
|
||||
switch typed := value.(type) {
|
||||
case string:
|
||||
cleanContent, reasoning, changed := splitTaggedReasoningText(typed)
|
||||
return cleanContent, reasoning, changed
|
||||
case []any:
|
||||
contentParts := make([]string, 0, len(typed))
|
||||
reasoningParts := make([]string, 0)
|
||||
changed := false
|
||||
for _, rawItem := range typed {
|
||||
switch item := rawItem.(type) {
|
||||
case string:
|
||||
contentParts = append(contentParts, item)
|
||||
case map[string]any:
|
||||
switch stringFromAny(item["type"]) {
|
||||
case "thinking":
|
||||
if thinking := stringFromAny(item["thinking"]); thinking != "" {
|
||||
reasoningParts = append(reasoningParts, thinking)
|
||||
}
|
||||
changed = true
|
||||
case "redacted_thinking", "reasoning.encrypted":
|
||||
changed = true
|
||||
case "reasoning.text":
|
||||
if text := stringFromAny(item["text"]); text != "" {
|
||||
reasoningParts = append(reasoningParts, text)
|
||||
}
|
||||
changed = true
|
||||
case "reasoning.summary":
|
||||
if summary := stringFromAny(item["summary"]); summary != "" {
|
||||
reasoningParts = append(reasoningParts, summary)
|
||||
}
|
||||
changed = true
|
||||
case "text", "output_text":
|
||||
if text := stringFromAny(firstPresent(item["text"], item["content"])); text != "" {
|
||||
cleanText, reasoning, tagged := splitTaggedReasoningText(text)
|
||||
contentParts = append(contentParts, cleanText)
|
||||
if reasoning != "" {
|
||||
reasoningParts = append(reasoningParts, reasoning)
|
||||
}
|
||||
changed = changed || tagged
|
||||
}
|
||||
default:
|
||||
if text := stringFromAny(firstPresent(item["text"], item["content"])); text != "" {
|
||||
contentParts = append(contentParts, text)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return value, "", false
|
||||
}
|
||||
return strings.Join(contentParts, ""), strings.Join(reasoningParts, ""), true
|
||||
default:
|
||||
return value, "", false
|
||||
}
|
||||
}
|
||||
|
||||
func splitTaggedReasoningText(text string) (string, string, bool) {
|
||||
lower := strings.ToLower(text)
|
||||
clean := strings.Builder{}
|
||||
reasoning := strings.Builder{}
|
||||
changed := false
|
||||
for offset := 0; offset < len(text); {
|
||||
start, tag := nextReasoningOpenTag(lower, offset)
|
||||
if start < 0 {
|
||||
clean.WriteString(text[offset:])
|
||||
break
|
||||
}
|
||||
clean.WriteString(text[offset:start])
|
||||
openEnd := start + len("<"+tag+">")
|
||||
closeToken := "</" + tag + ">"
|
||||
closeStart := strings.Index(lower[openEnd:], closeToken)
|
||||
if closeStart < 0 {
|
||||
reasoning.WriteString(text[openEnd:])
|
||||
offset = len(text)
|
||||
changed = true
|
||||
break
|
||||
}
|
||||
closeStart += openEnd
|
||||
reasoning.WriteString(text[openEnd:closeStart])
|
||||
offset = closeStart + len(closeToken)
|
||||
changed = true
|
||||
}
|
||||
return clean.String(), reasoning.String(), changed
|
||||
}
|
||||
|
||||
func nextReasoningOpenTag(lower string, offset int) (int, string) {
|
||||
bestStart := -1
|
||||
bestTag := ""
|
||||
for _, tag := range []string{"think", "reasoning", "analysis"} {
|
||||
needle := "<" + tag + ">"
|
||||
idx := strings.Index(lower[offset:], needle)
|
||||
if idx < 0 {
|
||||
continue
|
||||
}
|
||||
absolute := offset + idx
|
||||
if bestStart < 0 || absolute < bestStart {
|
||||
bestStart = absolute
|
||||
bestTag = tag
|
||||
}
|
||||
}
|
||||
return bestStart, bestTag
|
||||
}
|
||||
|
||||
func streamEventText(event map[string]any) string {
|
||||
if choices, ok := event["choices"].([]any); ok {
|
||||
for _, rawChoice := range choices {
|
||||
@@ -195,6 +784,91 @@ func streamEventText(event map[string]any) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func streamEventReasoningContent(event map[string]any) string {
|
||||
if choices, ok := event["choices"].([]any); ok {
|
||||
for _, rawChoice := range choices {
|
||||
choice, _ := rawChoice.(map[string]any)
|
||||
if delta, ok := choice["delta"].(map[string]any); ok {
|
||||
if content, ok := delta["reasoning_content"].(string); ok {
|
||||
return content
|
||||
}
|
||||
if content, ok := delta["reasoning"].(string); ok {
|
||||
return content
|
||||
}
|
||||
}
|
||||
if message, ok := choice["message"].(map[string]any); ok {
|
||||
if content, ok := message["reasoning_content"].(string); ok {
|
||||
return content
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func streamEventFinishReason(event map[string]any) string {
|
||||
if choices, ok := event["choices"].([]any); ok {
|
||||
for _, rawChoice := range choices {
|
||||
choice, _ := rawChoice.(map[string]any)
|
||||
if reason, ok := choice["finish_reason"].(string); ok && reason != "" {
|
||||
return reason
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func aggregateStreamToolCalls(event map[string]any, toolCalls map[int]map[string]any) {
|
||||
choices, _ := event["choices"].([]any)
|
||||
for _, rawChoice := range choices {
|
||||
choice, _ := rawChoice.(map[string]any)
|
||||
delta, _ := choice["delta"].(map[string]any)
|
||||
rawToolCalls, _ := delta["tool_calls"].([]any)
|
||||
for _, rawToolCall := range rawToolCalls {
|
||||
incoming, _ := rawToolCall.(map[string]any)
|
||||
index := intFromAny(incoming["index"])
|
||||
current := toolCalls[index]
|
||||
if current == nil {
|
||||
current = map[string]any{}
|
||||
toolCalls[index] = current
|
||||
}
|
||||
for _, key := range []string{"id", "type"} {
|
||||
if value, ok := incoming[key].(string); ok && value != "" {
|
||||
current[key] = value
|
||||
}
|
||||
}
|
||||
incomingFn, _ := incoming["function"].(map[string]any)
|
||||
if len(incomingFn) == 0 {
|
||||
continue
|
||||
}
|
||||
currentFn, _ := current["function"].(map[string]any)
|
||||
if currentFn == nil {
|
||||
currentFn = map[string]any{}
|
||||
current["function"] = currentFn
|
||||
}
|
||||
if name, ok := incomingFn["name"].(string); ok && name != "" {
|
||||
currentFn["name"] = stringFromAny(currentFn["name"]) + name
|
||||
}
|
||||
if arguments, ok := incomingFn["arguments"].(string); ok && arguments != "" {
|
||||
currentFn["arguments"] = stringFromAny(currentFn["arguments"]) + arguments
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func sortedStreamToolCalls(toolCalls map[int]map[string]any) []any {
|
||||
indices := make([]int, 0, len(toolCalls))
|
||||
for index := range toolCalls {
|
||||
indices = append(indices, index)
|
||||
}
|
||||
sort.Ints(indices)
|
||||
out := make([]any, 0, len(indices))
|
||||
for _, index := range indices {
|
||||
out = append(out, toolCalls[index])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func usageFromOpenAI(result map[string]any) Usage {
|
||||
usage, _ := result["usage"].(map[string]any)
|
||||
input := intFromAny(firstPresent(usage["prompt_tokens"], usage["input_tokens"]))
|
||||
@@ -254,6 +928,15 @@ func stringFromAny(value any) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func firstNonEmptyString(values ...any) string {
|
||||
for _, value := range values {
|
||||
if text := strings.TrimSpace(stringFromAny(value)); text != "" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func firstPresent(values ...any) any {
|
||||
for _, value := range values {
|
||||
if value != nil {
|
||||
|
||||
@@ -23,6 +23,9 @@ func (c OpenAIClient) Run(ctx context.Context, request Request) (Response, error
|
||||
return Response{}, &ClientError{Code: "unsupported_kind", Message: "unsupported openai request kind", Retryable: false}
|
||||
}
|
||||
body := cloneBody(request.Body)
|
||||
if request.Kind == "chat.completions" {
|
||||
body = NormalizeChatCompletionRequestBody(body)
|
||||
}
|
||||
body["model"] = upstreamModelName(request.Candidate)
|
||||
stream := request.Stream || boolValue(body, "stream")
|
||||
ensureOpenAIStreamUsage(body, request.Kind, stream)
|
||||
@@ -40,6 +43,9 @@ func (c OpenAIClient) Run(ctx context.Context, request Request) (Response, error
|
||||
}
|
||||
requestID := requestIDFromHTTPResponse(resp)
|
||||
result, err := decodeOpenAIResponse(resp, stream, request.StreamDelta)
|
||||
if err == nil && request.Kind == "chat.completions" {
|
||||
result = NormalizeChatCompletionResult(result)
|
||||
}
|
||||
responseFinishedAt := time.Now()
|
||||
if err != nil {
|
||||
return Response{}, annotateResponseError(err, requestID, responseStartedAt, responseFinishedAt)
|
||||
|
||||
@@ -48,7 +48,13 @@ type Progress struct {
|
||||
Payload map[string]any
|
||||
}
|
||||
|
||||
type StreamDelta func(text string) error
|
||||
type StreamDeltaEvent struct {
|
||||
Text string
|
||||
ReasoningContent string
|
||||
Event map[string]any
|
||||
}
|
||||
|
||||
type StreamDelta func(event StreamDeltaEvent) error
|
||||
|
||||
type Client interface {
|
||||
Run(ctx context.Context, request Request) (Response, error)
|
||||
|
||||
Reference in New Issue
Block a user