package model import ( "encoding/json" ) // openAIChatResponse 是 /chat/completions 返回的 JSON 体,既用于 // 非流式负载,也用于每个 SSE 流块。 type openAIChatResponse struct { ID string `json:"id"` Model string `json:"model"` Choices []openAIChoice `json:"choices"` Usage *openAIUsage `json:"usage,omitempty"` } // openAIChoice 是一个候选补全。 type openAIChoice struct { Index int `json:"index"` Message openAIResponseMessage `json:"message"` Delta *openAIDelta `json:"delta,omitempty"` FinishReason string `json:"finish_reason,omitempty"` } // openAIResponseMessage 是非流式 choice 里的助手消息。 type openAIResponseMessage struct { Role string `json:"role"` Content string `json:"content"` ToolCalls []openAIToolCall `json:"tool_calls,omitempty"` } // openAIDelta 是流块里的增量负载。推理内容 // (OpenAI o 系 / DeepSeek / DashScope)到达 ReasoningContent;流式 // 函数调用到达 ToolCalls,按片段索引累积。 type openAIDelta struct { Role string `json:"role"` Content string `json:"content"` ReasoningContent string `json:"reasoning_content"` ToolCalls []openAIToolCallDelta `json:"tool_calls"` } // openAIToolCallDelta 是一个流式函数调用片段。OpenAI 会发出一串 // 共享同一 Index 的此类片段:ID 与 Function.Name 通常 // 只在第一个片段里出现一次,而 Function.Arguments 跨 // 多个片段流式到达。 type openAIToolCallDelta struct { Index int `json:"index"` ID string `json:"id"` Function openAIToolCallFn `json:"function"` } // openAIUsage 上报 token 消耗。 type openAIUsage struct { PromptTokens int `json:"prompt_tokens"` CompletionTokens int `json:"completion_tokens"` TotalTokens int `json:"total_tokens"` } func responseFromWire(wire *openAIChatResponse) Response { out := Response{Model: wire.Model} if len(wire.Choices) > 0 { text := wire.Choices[0].Message.Content out.Content = text out.Message = Message{Role: RoleAssistant, Content: []Content{{Type: ContentTypeText, Text: text}}} out.StopReason = wire.Choices[0].FinishReason for _, tc := range wire.Choices[0].Message.ToolCalls { args := map[string]any{} if tc.Function.Arguments != "" { _ = json.Unmarshal([]byte(tc.Function.Arguments), &args) } out.ToolCalls = append(out.ToolCalls, ToolCall{Name: tc.Function.Name, ID: tc.ID, Args: args}) } } if u := wire.Usage; u != nil { out.PromptTokens = u.PromptTokens out.CompletionTokens = u.CompletionTokens out.TotalTokens = u.TotalTokens } return out }