package ai
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
)
// capture 线程安全地保存假端点收到的请求体。
type capture struct {
mu sync.Mutex
req map[string]any
}
func (c *capture) set(m map[string]any) {
c.mu.Lock()
c.req = m
c.mu.Unlock()
}
func (c *capture) get() map[string]any {
c.mu.Lock()
defer c.mu.Unlock()
return c.req
}
// newCaptureServer 起一个假端点:记录请求体,并按给定状态码与正文响应。
func newCaptureServer(t *testing.T, status int, body string) (*httptest.Server, *capture) {
t.Helper()
c := &capture{}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var m map[string]any
_ = json.NewDecoder(r.Body).Decode(&m)
c.set(m)
w.Header().Set("Content-Type", "application/json")
if status != http.StatusOK {
w.WriteHeader(status)
}
_, _ = w.Write([]byte(body))
}))
t.Cleanup(srv.Close)
return srv, c
}
func testConfig(srv *httptest.Server) Config {
return Config{Enabled: true, BaseURL: srv.URL, Model: "test-model"}
}
// TestChatSendsToolsAndParsesToolCalls 验证工具声明按 OpenAI 格式发出,
// 模型返回的 tool_calls 被正确解析。
func TestChatSendsToolsAndParsesToolCalls(t *testing.T) {
reply := `{"choices":[{"message":{"content":"","tool_calls":[` +
`{"id":"call_1","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"a.go\"}"}}]}}]}`
srv, cap := newCaptureServer(t, http.StatusOK, reply)
res, err := Chat(context.Background(), testConfig(srv), []Message{
{Role: "system", Content: "你是助手"},
{Role: "user", Content: "这个文件里有什么?"},
}, []ToolSpec{{
Name: "read_file",
Description: "读取文件",
Parameters: map[string]any{
"type": "object",
"properties": map[string]any{"path": map[string]any{"type": "string"}},
"required": []string{"path"},
},
}})
if err != nil {
t.Fatalf("Chat 失败: %v", err)
}
req := cap.get()
if req["model"] != "test-model" {
t.Errorf("model 为 %v", req["model"])
}
tools, _ := req["tools"].([]any)
if len(tools) != 1 {
t.Fatalf("请求里应有 1 个工具,实际 %d", len(tools))
}
first, _ := tools[0].(map[string]any)
if first["type"] != "function" {
t.Errorf("工具 type 为 %v,期望 function", first["type"])
}
fn, _ := first["function"].(map[string]any)
if fn["name"] != "read_file" {
t.Errorf("工具名为 %v", fn["name"])
}
if _, ok := fn["parameters"].(map[string]any); !ok {
t.Error("工具缺少 parameters schema")
}
if len(res.ToolCalls) != 1 {
t.Fatalf("应解析出 1 个工具调用,实际 %d", len(res.ToolCalls))
}
if res.ToolCalls[0].ID != "call_1" || res.ToolCalls[0].Name != "read_file" {
t.Errorf("工具调用解析错误: %+v", res.ToolCalls[0])
}
if res.ToolCalls[0].Args != `{"path":"a.go"}` {
t.Errorf("参数原文为 %q", res.ToolCalls[0].Args)
}
}
// TestChatToolResultRoundTrip 验证把工具结果回填给模型时,
// assistant 的 tool_calls 与 tool 消息的 tool_call_id 都在请求体里。
func TestChatToolResultRoundTrip(t *testing.T) {
srv, cap := newCaptureServer(t, http.StatusOK, `{"choices":[{"message":{"content":"done"}}]}`)
res, err := Chat(context.Background(), testConfig(srv), []Message{
{Role: "user", Content: "u"},
{Role: "assistant", ToolCalls: []ToolCall{{ID: "c1", Name: "read_file", Args: "{}"}}},
{Role: "tool", ToolCallID: "c1", Content: "文件内容"},
}, nil)
if err != nil {
t.Fatalf("Chat 失败: %v", err)
}
if res.Content != "done" {
t.Errorf("内容为 %q", res.Content)
}
raw, _ := json.Marshal(cap.get()["messages"])
for _, want := range []string{`"tool_call_id":"c1"`, `"tool_calls"`, `"type":"function"`, "文件内容", `"role":"tool"`} {
if !strings.Contains(string(raw), want) {
t.Errorf("请求消息里缺少 %q:%s", want, raw)
}
}
if _, hasTools := cap.get()["tools"]; hasTools {
t.Error("未声明工具时不应带 tools 字段")
}
}
// TestChatReportsProviderError 接口报错时要带出可诊断的信息。
func TestChatReportsProviderError(t *testing.T) {
srv, _ := newCaptureServer(t, http.StatusBadRequest, `{"error":{"message":"invalid api key"}}`)
_, err := Chat(context.Background(), testConfig(srv), []Message{{Role: "user", Content: "u"}}, nil)
if err == nil || !strings.Contains(err.Error(), "invalid api key") {
t.Fatalf("期望带出接口错误,实际 %v", err)
}
}
// TestChatRejectsEmptyReply 模型什么都没返回时视为失败。
func TestChatRejectsEmptyReply(t *testing.T) {
srv, _ := newCaptureServer(t, http.StatusOK, `{"choices":[{"message":{"content":""}}]}`)
if _, err := Chat(context.Background(), testConfig(srv), []Message{{Role: "user", Content: "u"}}, nil); err == nil {
t.Error("空响应应返回错误")
}
}
// TestChatRejectsIncompleteConfig 配置不完整时不发请求。
func TestChatRejectsIncompleteConfig(t *testing.T) {
if _, err := Chat(context.Background(), Config{Enabled: true}, []Message{{Role: "user", Content: "u"}}, nil); err == nil {
t.Error("配置不完整应直接报错")
}
}
// TestRedactExported 仓库内容外发前的脱敏入口可用。
func TestRedactExported(t *testing.T) {
out := Redact("aws_key = AKIAIOSFODNN7EXAMPLE")
if strings.Contains(out, "AKIAIOSFODNN7EXAMPLE") {
t.Errorf("Redact 未生效: %q", out)
}
}
// TestSplitThinking 验证内联思维链的分离:成对标签、多次出现、未闭合、无思维链。
func TestSplitThinking(t *testing.T) {
cases := []struct {
name, in, wantThink, wantAnswer string
}{
{"无思维链", "普通回答", "", "普通回答"},
{"成对标签", "先想一下正式回答", "先想一下", "正式回答"},
{"前后都有内容", "开头\n推理过程\n\n结尾回答", "推理过程", "开头\n结尾回答"},
{"多次出现", "a中b尾", "a\n\nb", "中尾"},
{"未闭合", "回答前半忘了闭合的思考", "忘了闭合的思考", "回答前半"},
{"带属性", "推理答案", "推理", "答案"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
thinking, answer := SplitThinking(c.in)
if thinking != c.wantThink {
t.Errorf("思维链 = %q,期望 %q", thinking, c.wantThink)
}
if answer != c.wantAnswer {
t.Errorf("回答 = %q,期望 %q", answer, c.wantAnswer)
}
})
}
// StripThinking 是丢弃思维链的便捷入口
if got := StripThinking("xy"); got != "y" {
t.Errorf("StripThinking = %q", got)
}
}
// TestChatParsesReasoningFields 模型把思维链放在独立字段时也要接住。
func TestChatParsesReasoningFields(t *testing.T) {
cases := []struct {
name, body, field string
}{
{"reasoning_content", `{"choices":[{"message":{"content":"答","reasoning_content":"推理A"}}]}`, "推理A"},
{"reasoning", `{"choices":[{"message":{"content":"答","reasoning":"推理B"}}]}`, "推理B"},
{"content 优先于独立字段", `{"choices":[{"message":{"content":"内联答"}}]}`, ""},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
srv, _ := newCaptureServer(t, http.StatusOK, c.body)
res, err := Chat(context.Background(), testConfig(srv), []Message{{Role: "user", Content: "u"}}, nil)
if err != nil {
t.Fatalf("Chat 失败: %v", err)
}
if c.field != "" && res.Reasoning != c.field {
t.Errorf("Reasoning = %q,期望 %q", res.Reasoning, c.field)
}
if c.field == "" && res.Reasoning != "" {
t.Errorf("不应有独立字段思维链,实际 %q", res.Reasoning)
}
})
}
}