2026-05-30 23:16:49 +08:00
|
|
|
|
package ai
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
|
"bufio"
|
|
|
|
|
|
"bytes"
|
|
|
|
|
|
"context"
|
|
|
|
|
|
"encoding/json"
|
|
|
|
|
|
"fmt"
|
|
|
|
|
|
"io"
|
|
|
|
|
|
"net/http"
|
|
|
|
|
|
"strings"
|
|
|
|
|
|
"time"
|
|
|
|
|
|
|
|
|
|
|
|
"ai-agent-scaffold-go/internal/domain/agent/ports"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
type OpenAIClient struct {
|
|
|
|
|
|
httpClient *http.Client
|
|
|
|
|
|
completionsURL string
|
|
|
|
|
|
apiKey string
|
|
|
|
|
|
model string
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
type OpenAIToolDef struct {
|
|
|
|
|
|
Name string
|
|
|
|
|
|
Description string
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func NewOpenAIClient(completionsURL, apiKey, model string, requestTimeout time.Duration) *OpenAIClient {
|
|
|
|
|
|
if requestTimeout <= 0 {
|
|
|
|
|
|
requestTimeout = 5 * time.Minute
|
|
|
|
|
|
}
|
|
|
|
|
|
return &OpenAIClient{
|
|
|
|
|
|
httpClient: &http.Client{Timeout: requestTimeout},
|
|
|
|
|
|
completionsURL: completionsURL,
|
|
|
|
|
|
apiKey: apiKey,
|
|
|
|
|
|
model: model,
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-05 21:09:39 +08:00
|
|
|
|
// Generate 发送非流式 Chat Completions 请求,等待完整响应后返回文本内容与工具调用列表。
|
|
|
|
|
|
//
|
|
|
|
|
|
// 该请求使用 stream=false,服务端会一次性返回完整 JSON 响应。
|
|
|
|
|
|
// 返回的 ChatReply 包含模型最终文本内容;若模型决定调用工具,则同时包含工具调用列表。
|
2026-05-30 23:16:49 +08:00
|
|
|
|
func (c *OpenAIClient) Generate(ctx context.Context, messages []ports.ChatMessage, tools []OpenAIToolDef) (ports.ChatReply, error) {
|
2026-10-05 21:09:39 +08:00
|
|
|
|
// stream=false,构造一次性返回完整响应的普通请求
|
2026-05-30 23:16:49 +08:00
|
|
|
|
body, err := buildRequestBody(c.model, messages, tools, false)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return ports.ChatReply{}, err
|
|
|
|
|
|
}
|
|
|
|
|
|
resp, err := c.do(ctx, body)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return ports.ChatReply{}, err
|
|
|
|
|
|
}
|
|
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
|
|
|
|
raw, err := io.ReadAll(resp.Body)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return ports.ChatReply{}, fmt.Errorf("openai read body: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
|
|
|
|
return ports.ChatReply{}, fmt.Errorf("openai upstream %d: %s", resp.StatusCode, truncate(string(raw), 400))
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
var parsed openaiCompletion
|
|
|
|
|
|
if err := json.Unmarshal(raw, &parsed); err != nil {
|
|
|
|
|
|
return ports.ChatReply{}, fmt.Errorf("openai decode: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
if len(parsed.Choices) == 0 {
|
|
|
|
|
|
return ports.ChatReply{}, fmt.Errorf("openai response has no choices")
|
|
|
|
|
|
}
|
|
|
|
|
|
choice := parsed.Choices[0].Message
|
|
|
|
|
|
reply := ports.ChatReply{Content: choice.Content}
|
|
|
|
|
|
for _, tc := range choice.ToolCalls {
|
|
|
|
|
|
reply.ToolCalls = append(reply.ToolCalls, ports.ChatToolCall{
|
|
|
|
|
|
ID: tc.ID,
|
|
|
|
|
|
Name: tc.Function.Name,
|
|
|
|
|
|
Arguments: tc.Function.Arguments,
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
return reply, nil
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-05 21:09:39 +08:00
|
|
|
|
// Stream 发送流式 Chat Completions 请求,并通过 channel 持续返回增量文本、工具调用和错误。
|
|
|
|
|
|
//
|
|
|
|
|
|
// 调用方通过 events 接收流式事件,通过 errs 接收错误;
|
|
|
|
|
|
// 当收到 Done=true 事件或 events channel 被关闭时,表示本次流式请求结束。
|
|
|
|
|
|
// 流式响应中 tool_calls 是分片到达的,因此内部使用 map[int]*ChatToolCall 按 index 累积完整工具调用。
|
2026-05-30 23:16:49 +08:00
|
|
|
|
func (c *OpenAIClient) Stream(ctx context.Context, messages []ports.ChatMessage, tools []OpenAIToolDef) (<-chan ports.ChatStreamEvent, <-chan error) {
|
|
|
|
|
|
events := make(chan ports.ChatStreamEvent, 8)
|
|
|
|
|
|
errs := make(chan error, 1)
|
|
|
|
|
|
go func() {
|
|
|
|
|
|
defer close(events)
|
|
|
|
|
|
defer close(errs)
|
|
|
|
|
|
|
|
|
|
|
|
body, err := buildRequestBody(c.model, messages, tools, true)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
errs <- err
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
resp, err := c.do(ctx, body)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
errs <- err
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
|
|
|
|
raw, _ := io.ReadAll(resp.Body)
|
|
|
|
|
|
errs <- fmt.Errorf("openai upstream %d: %s", resp.StatusCode, truncate(string(raw), 400))
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-05 21:09:39 +08:00
|
|
|
|
// 按 index 暂存流式 tool_call,用于跨多个 SSE chunk 累积完整参数
|
2026-05-30 23:16:49 +08:00
|
|
|
|
toolCallBuf := map[int]*ports.ChatToolCall{}
|
2026-10-05 21:09:39 +08:00
|
|
|
|
reader := bufio.NewReader(resp.Body) // 带缓冲逐行读取 SSE 数据
|
2026-05-30 23:16:49 +08:00
|
|
|
|
for {
|
|
|
|
|
|
line, err := reader.ReadString('\n')
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
if err == io.EOF {
|
|
|
|
|
|
emitToolCalls(events, toolCallBuf)
|
|
|
|
|
|
events <- ports.ChatStreamEvent{Done: true}
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
errs <- fmt.Errorf("openai stream read: %w", err)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2026-10-05 21:09:39 +08:00
|
|
|
|
line = strings.TrimRight(line, "\r\n") // 去掉行尾换行符,兼容 \n 与 \r\n
|
2026-05-30 23:16:49 +08:00
|
|
|
|
if line == "" || !strings.HasPrefix(line, "data:") {
|
2026-10-05 21:09:39 +08:00
|
|
|
|
continue // 忽略空行和非 data: 的 SSE 行
|
2026-05-30 23:16:49 +08:00
|
|
|
|
}
|
2026-10-05 21:09:39 +08:00
|
|
|
|
payload := strings.TrimSpace(strings.TrimPrefix(line, "data:")) // 提取 data 内容
|
2026-05-30 23:16:49 +08:00
|
|
|
|
if payload == "[DONE]" {
|
|
|
|
|
|
emitToolCalls(events, toolCallBuf)
|
|
|
|
|
|
events <- ports.ChatStreamEvent{Done: true}
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
var chunk openaiStreamChunk
|
|
|
|
|
|
if err := json.Unmarshal([]byte(payload), &chunk); err != nil {
|
|
|
|
|
|
errs <- fmt.Errorf("openai stream decode: %w", err)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
if len(chunk.Choices) == 0 {
|
|
|
|
|
|
continue
|
|
|
|
|
|
}
|
|
|
|
|
|
delta := chunk.Choices[0].Delta
|
|
|
|
|
|
if delta.Content != "" {
|
|
|
|
|
|
select {
|
|
|
|
|
|
case events <- ports.ChatStreamEvent{Delta: delta.Content}:
|
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
|
|
errs <- ctx.Err()
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
for _, tc := range delta.ToolCalls {
|
|
|
|
|
|
current, ok := toolCallBuf[tc.Index]
|
|
|
|
|
|
if !ok {
|
|
|
|
|
|
current = &ports.ChatToolCall{}
|
|
|
|
|
|
toolCallBuf[tc.Index] = current
|
|
|
|
|
|
}
|
|
|
|
|
|
if tc.ID != "" {
|
|
|
|
|
|
current.ID = tc.ID
|
|
|
|
|
|
}
|
|
|
|
|
|
if tc.Function.Name != "" {
|
|
|
|
|
|
current.Name = tc.Function.Name
|
|
|
|
|
|
}
|
|
|
|
|
|
if tc.Function.Arguments != "" {
|
2026-10-05 21:09:39 +08:00
|
|
|
|
// arguments 是 JSON 增量片段,需要持续拼接成完整参数
|
2026-05-30 23:16:49 +08:00
|
|
|
|
current.Arguments += tc.Function.Arguments
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}()
|
|
|
|
|
|
return events, errs
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-05 21:09:39 +08:00
|
|
|
|
// emitToolCalls 将流式读取过程中累积的工具调用按 index 顺序发送到事件管道。
|
|
|
|
|
|
//
|
|
|
|
|
|
// OpenAI 流式协议中多个工具调用可能交错返回,因此内部先用 map 暂存;
|
|
|
|
|
|
// 发送时按 index 从 0 开始遍历,保证上层拿到的工具调用顺序稳定。
|
2026-05-30 23:16:49 +08:00
|
|
|
|
func emitToolCalls(events chan<- ports.ChatStreamEvent, buf map[int]*ports.ChatToolCall) {
|
|
|
|
|
|
if len(buf) == 0 {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
calls := make([]ports.ChatToolCall, 0, len(buf))
|
|
|
|
|
|
for i := 0; i < len(buf); i++ {
|
|
|
|
|
|
if call, ok := buf[i]; ok && call != nil {
|
|
|
|
|
|
calls = append(calls, *call)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
if len(calls) > 0 {
|
|
|
|
|
|
events <- ports.ChatStreamEvent{ToolCalls: calls}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-05 21:09:39 +08:00
|
|
|
|
// do 构造并发送 HTTP POST 请求,统一处理 Content-Type、Accept 和 Bearer 认证。
|
|
|
|
|
|
//
|
|
|
|
|
|
// 该方法只负责发送请求,不读取响应体;响应体由调用方负责关闭。
|
|
|
|
|
|
// 网络层错误会包装为带上下文的错误返回。
|
2026-05-30 23:16:49 +08:00
|
|
|
|
func (c *OpenAIClient) do(ctx context.Context, body []byte) (*http.Response, error) {
|
|
|
|
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.completionsURL, bytes.NewReader(body))
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("openai build request: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
|
|
req.Header.Set("Accept", "application/json")
|
|
|
|
|
|
if c.apiKey != "" {
|
|
|
|
|
|
req.Header.Set("Authorization", "Bearer "+c.apiKey)
|
|
|
|
|
|
}
|
|
|
|
|
|
resp, err := c.httpClient.Do(req)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("openai http: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
return resp, nil
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-05 21:09:39 +08:00
|
|
|
|
// buildRequestBody 构造 OpenAI Chat Completions 请求体,并序列化为 JSON 字节。
|
|
|
|
|
|
//
|
|
|
|
|
|
// stream 为 true 时生成流式请求,为 false 时生成普通请求;
|
|
|
|
|
|
// 仅当 tools 非空时才写入 tools 字段,避免无工具时发送空数组。
|
2026-05-30 23:16:49 +08:00
|
|
|
|
func buildRequestBody(modelName string, messages []ports.ChatMessage, tools []OpenAIToolDef, stream bool) ([]byte, error) {
|
|
|
|
|
|
payload := map[string]any{
|
|
|
|
|
|
"model": modelName,
|
|
|
|
|
|
"messages": encodeMessages(messages),
|
|
|
|
|
|
"stream": stream,
|
|
|
|
|
|
}
|
|
|
|
|
|
if len(tools) > 0 {
|
|
|
|
|
|
payload["tools"] = encodeTools(tools)
|
|
|
|
|
|
}
|
|
|
|
|
|
raw, err := json.Marshal(payload)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("openai marshal request: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
return raw, nil
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-05 21:09:39 +08:00
|
|
|
|
// encodeMessages 将领域层消息转换为 OpenAI Chat Completions 协议所需的消息格式。
|
|
|
|
|
|
//
|
|
|
|
|
|
// 支持普通 system/user 消息、assistant 工具调用消息、tool 执行结果消息;
|
|
|
|
|
|
// 当 assistant 消息带有 tool_calls 且 content 为空时,按 OpenAI 协议省略 content 字段。
|
2026-05-30 23:16:49 +08:00
|
|
|
|
func encodeMessages(messages []ports.ChatMessage) []map[string]any {
|
|
|
|
|
|
encoded := make([]map[string]any, 0, len(messages))
|
|
|
|
|
|
for _, m := range messages {
|
|
|
|
|
|
entry := map[string]any{"role": string(m.Role)}
|
|
|
|
|
|
if m.Content != "" {
|
|
|
|
|
|
entry["content"] = m.Content
|
|
|
|
|
|
} else if m.Role != ports.ChatRoleAssistant || len(m.ToolCalls) == 0 {
|
|
|
|
|
|
entry["content"] = ""
|
|
|
|
|
|
}
|
|
|
|
|
|
if m.Name != "" {
|
|
|
|
|
|
entry["name"] = m.Name
|
|
|
|
|
|
}
|
|
|
|
|
|
if m.ToolCallID != "" {
|
|
|
|
|
|
entry["tool_call_id"] = m.ToolCallID
|
|
|
|
|
|
}
|
|
|
|
|
|
if len(m.ToolCalls) > 0 {
|
|
|
|
|
|
calls := make([]map[string]any, 0, len(m.ToolCalls))
|
|
|
|
|
|
for _, c := range m.ToolCalls {
|
|
|
|
|
|
calls = append(calls, map[string]any{
|
|
|
|
|
|
"id": c.ID,
|
|
|
|
|
|
"type": "function",
|
|
|
|
|
|
"function": map[string]any{
|
|
|
|
|
|
"name": c.Name,
|
|
|
|
|
|
"arguments": c.Arguments,
|
|
|
|
|
|
},
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
entry["tool_calls"] = calls
|
|
|
|
|
|
}
|
|
|
|
|
|
encoded = append(encoded, entry)
|
|
|
|
|
|
}
|
|
|
|
|
|
return encoded
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-05 21:09:39 +08:00
|
|
|
|
// encodeTools 将工具定义转换为 OpenAI 函数调用(Function Calling)协议格式。
|
|
|
|
|
|
//
|
|
|
|
|
|
// 当前实现把工具参数统一建模为 query 字符串,适合将 MCP/Skill 工具包装为自由文本输入;
|
|
|
|
|
|
// 若工具描述为空,会通过 fallbackDescription 生成默认描述。
|
2026-05-30 23:16:49 +08:00
|
|
|
|
func encodeTools(tools []OpenAIToolDef) []map[string]any {
|
|
|
|
|
|
out := make([]map[string]any, 0, len(tools))
|
|
|
|
|
|
for _, t := range tools {
|
|
|
|
|
|
out = append(out, map[string]any{
|
|
|
|
|
|
"type": "function",
|
|
|
|
|
|
"function": map[string]any{
|
|
|
|
|
|
"name": t.Name,
|
|
|
|
|
|
"description": fallbackDescription(t),
|
|
|
|
|
|
"parameters": map[string]any{
|
|
|
|
|
|
"type": "object",
|
|
|
|
|
|
"properties": map[string]any{
|
|
|
|
|
|
"query": map[string]any{
|
|
|
|
|
|
"type": "string",
|
|
|
|
|
|
"description": "自由文本输入或检索查询,工具会按其语义解释",
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
return out
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-05 21:09:39 +08:00
|
|
|
|
// fallbackDescription 返回工具描述
|
|
|
|
|
|
//
|
|
|
|
|
|
// 当描述为空时,生成一个通用默认描述。
|
|
|
|
|
|
// 默认描述会包含工具名,提示模型该工具接收自由文本 query 参数。
|
2026-05-30 23:16:49 +08:00
|
|
|
|
func fallbackDescription(t OpenAIToolDef) string {
|
|
|
|
|
|
if strings.TrimSpace(t.Description) != "" {
|
|
|
|
|
|
return t.Description
|
|
|
|
|
|
}
|
|
|
|
|
|
return "外部工具 " + t.Name + ",参数 query 为自由文本"
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-05 21:09:39 +08:00
|
|
|
|
// truncate 将过长的字符串截断到指定长度,用于控制错误信息中的响应体长度。
|
|
|
|
|
|
//
|
|
|
|
|
|
// 如果原始字符串长度不超过 max,则原样返回;否则截取前 max 个字符并追加省略号。
|
2026-05-30 23:16:49 +08:00
|
|
|
|
func truncate(s string, max int) string {
|
|
|
|
|
|
if len(s) <= max {
|
|
|
|
|
|
return s
|
|
|
|
|
|
}
|
|
|
|
|
|
return s[:max] + "..."
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-05 21:09:39 +08:00
|
|
|
|
// openaiCompletion 对应 OpenAI 非流式 Chat Completions 响应。
|
|
|
|
|
|
//
|
|
|
|
|
|
// 其中 choices[0].message 保存最终文本内容与模型请求的工具调用列表。
|
2026-05-30 23:16:49 +08:00
|
|
|
|
type openaiCompletion struct {
|
|
|
|
|
|
Choices []struct {
|
|
|
|
|
|
Message struct {
|
|
|
|
|
|
Content string `json:"content"`
|
|
|
|
|
|
ToolCalls []openaiToolCallV1 `json:"tool_calls"`
|
|
|
|
|
|
} `json:"message"`
|
|
|
|
|
|
} `json:"choices"`
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-05 21:09:39 +08:00
|
|
|
|
// openaiStreamChunk 对应 OpenAI 流式响应中的单个 SSE data chunk。
|
|
|
|
|
|
//
|
|
|
|
|
|
// delta 中可能包含 content 文本增量,或 tool_calls 工具的增量片段。
|
2026-05-30 23:16:49 +08:00
|
|
|
|
type openaiStreamChunk struct {
|
|
|
|
|
|
Choices []struct {
|
|
|
|
|
|
Delta struct {
|
|
|
|
|
|
Content string `json:"content"`
|
|
|
|
|
|
ToolCalls []openaiStreamToolCall `json:"tool_calls"`
|
|
|
|
|
|
} `json:"delta"`
|
|
|
|
|
|
FinishReason string `json:"finish_reason"`
|
|
|
|
|
|
} `json:"choices"`
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-05 21:09:39 +08:00
|
|
|
|
// openaiToolCallV1 对应 OpenAI 非流式响应中的完整工具调用。
|
2026-05-30 23:16:49 +08:00
|
|
|
|
type openaiToolCallV1 struct {
|
|
|
|
|
|
ID string `json:"id"`
|
|
|
|
|
|
Type string `json:"type"`
|
|
|
|
|
|
Function struct {
|
|
|
|
|
|
Name string `json:"name"`
|
|
|
|
|
|
Arguments string `json:"arguments"`
|
|
|
|
|
|
} `json:"function"`
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-05 21:09:39 +08:00
|
|
|
|
// openaiStreamToolCall 对应 OpenAI 流式响应中的工具调用增量片段。
|
|
|
|
|
|
//
|
|
|
|
|
|
// Index 用于区分同一响应中的多个工具调用,Arguments 是需要跨 chunk 拼接的 JSON 增量。
|
2026-05-30 23:16:49 +08:00
|
|
|
|
type openaiStreamToolCall struct {
|
|
|
|
|
|
Index int `json:"index"`
|
|
|
|
|
|
ID string `json:"id"`
|
|
|
|
|
|
Type string `json:"type"`
|
|
|
|
|
|
Function struct {
|
|
|
|
|
|
Name string `json:"name"`
|
|
|
|
|
|
Arguments string `json:"arguments"`
|
|
|
|
|
|
} `json:"function"`
|
|
|
|
|
|
}
|