Include chat, weather, image, travel, streaming ASR and text examples, shared model initialization, documentation, and existing tests. Co-authored-by: TRAE CLI <traecli@bytedance.com>
156 lines
5.7 KiB
Go
156 lines
5.7 KiB
Go
package agent
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"fmt"
|
||
"io"
|
||
"net/http"
|
||
"net/http/httptest"
|
||
"strings"
|
||
"sync/atomic"
|
||
"testing"
|
||
"time"
|
||
|
||
"example.com/ueino/adk/internal/config"
|
||
"example.com/ueino/pkg/model"
|
||
)
|
||
|
||
type roundTripperFunc func(*http.Request) (*http.Response, error)
|
||
|
||
func (f roundTripperFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||
|
||
func TestChatWeatherAndHistory(t *testing.T) {
|
||
previous := http.DefaultTransport
|
||
var weatherCalls atomic.Int32
|
||
today := time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60)).Format(time.DateOnly)
|
||
http.DefaultTransport = roundTripperFunc(func(r *http.Request) (*http.Response, error) {
|
||
var body string
|
||
switch r.URL.Host {
|
||
case "geocoding-api.open-meteo.com":
|
||
if r.URL.Query().Get("name") != "北京" {
|
||
t.Errorf("天气地点错误: %s", r.URL)
|
||
}
|
||
body = `{"results":[{"name":"北京","country":"中国","latitude":39.9,"longitude":116.4}]}`
|
||
case "api.open-meteo.com":
|
||
if r.URL.Query().Get("start_date") != today || r.URL.Query().Get("end_date") != today {
|
||
t.Errorf("默认天气日期错误: %s", r.URL)
|
||
}
|
||
body = fmt.Sprintf(`{"daily":{"time":[%q],"weather_code":[0],"temperature_2m_min":[10],"temperature_2m_max":[20],"precipitation_probability_max":[0]}}`, today)
|
||
default:
|
||
return previous.RoundTrip(r)
|
||
}
|
||
weatherCalls.Add(1)
|
||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header), Request: r}, nil
|
||
})
|
||
t.Cleanup(func() { http.DefaultTransport = previous })
|
||
var step atomic.Int32
|
||
requests := make(chan model.ChatCompletionRequest, 3)
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
var request model.ChatCompletionRequest
|
||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||
t.Error(err)
|
||
}
|
||
requests <- request
|
||
w.Header().Set("Content-Type", "text/event-stream")
|
||
switch step.Add(1) {
|
||
case 1:
|
||
fmt.Fprint(w, `data: {"choices":[{"index":0,"delta":{"role":"assistant","content":"查询中","tool_calls":[{"index":0,"id":"weather-1","type":"function","function":{"name":"get_weather","arguments":"{\"location\":\"北京\"}"}}]},"finish_reason":"tool_calls"}]}
|
||
|
||
data: [DONE]
|
||
|
||
`)
|
||
default:
|
||
fmt.Fprint(w, "data: {\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"北京晴天\"},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n")
|
||
}
|
||
}))
|
||
defer server.Close()
|
||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||
defer cancel()
|
||
chat, err := New(ctx, config.Config{Chat: config.ModelConfig{BaseURL: server.URL, Model: "test-model", APIKey: "test-key"}, MaxToken: 4096})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
var output strings.Builder
|
||
if err := chat.Chat(ctx, "北京天气", func(text string) { output.WriteString(text) }, nil, nil); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if !strings.Contains(output.String(), "北京晴天") || strings.Contains(output.String(), "temperature_2m_max") {
|
||
t.Fatalf("终端输出 = %q", output.String())
|
||
}
|
||
if err := chat.Chat(ctx, "继续", func(string) {}, nil, nil); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if step.Load() != 3 || weatherCalls.Load() != 2 {
|
||
t.Fatalf("请求次数:模型 %d,天气 %d", step.Load(), weatherCalls.Load())
|
||
}
|
||
first, second, third := <-requests, <-requests, <-requests
|
||
if len(first.Tools) != 1 || first.Tools[0].Function.Name != "get_weather" {
|
||
t.Fatalf("工具定义 = %+v", first.Tools)
|
||
}
|
||
last := second.Messages[len(second.Messages)-1]
|
||
if last.Role != "tool" || last.ToolCallID != "weather-1" {
|
||
t.Fatalf("工具结果 = %+v", last)
|
||
}
|
||
var forecast model.WeatherForecast
|
||
if err := json.Unmarshal([]byte(last.Content.(string)), &forecast); err != nil || len(forecast.Days) != 1 || forecast.Days[0].Date != today || forecast.Days[0].Condition != "晴" {
|
||
t.Fatalf("工具预报结果不正确: %+v,%v", forecast, err)
|
||
}
|
||
if len(third.Messages) != 4 || third.Messages[1].Content != "北京天气" || third.Messages[2].Content != "北京晴天" || third.Messages[3].Content != "继续" {
|
||
t.Fatalf("对话历史 = %+v", third.Messages)
|
||
}
|
||
}
|
||
|
||
// 使用命令行默认配置检查注册结果,避免只测手工构造的 Config。
|
||
func TestDefaultImageCapability(t *testing.T) {
|
||
for _, enabled := range []bool{true, false} {
|
||
t.Run(fmt.Sprintf("启用=%v", enabled), func(t *testing.T) {
|
||
var requests atomic.Int32
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
requests.Add(1)
|
||
var request model.ChatCompletionRequest
|
||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||
t.Error(err)
|
||
}
|
||
hasImage, hasTravel := false, false
|
||
for _, tool := range request.Tools {
|
||
if tool.Function.Name == "generate_image" {
|
||
hasImage = true
|
||
}
|
||
if tool.Function.Name == travelToolName {
|
||
hasTravel = true
|
||
}
|
||
}
|
||
if hasImage != enabled || hasTravel != enabled {
|
||
t.Errorf("生图工具 注册状态 = %v,期望 %v", hasImage, enabled)
|
||
}
|
||
if enabled && !strings.Contains(request.Messages[0].Content.(string), "用户只询问能否生图") {
|
||
t.Error("应区分能力问答与实际生图请求")
|
||
}
|
||
writeCompletion(w, request.Stream, "能力说明", nil)
|
||
}))
|
||
defer server.Close()
|
||
args := []string{"--base-url", server.URL}
|
||
if !enabled {
|
||
args = append(args, "--image-model", "")
|
||
}
|
||
cfg, err := config.Parse(args)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||
defer cancel()
|
||
chat, err := New(ctx, cfg)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if err := chat.Chat(ctx, "你可以生成图片么", nil, nil, nil); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if requests.Load() != 1 {
|
||
t.Fatalf("能力问答应只有一次聊天请求,实际 %d", requests.Load())
|
||
}
|
||
})
|
||
}
|
||
}
|