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>
209 lines
9.5 KiB
Go
209 lines
9.5 KiB
Go
package agent
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"errors"
|
||
"fmt"
|
||
"io"
|
||
"net/http"
|
||
"net/http/httptest"
|
||
"os"
|
||
"strings"
|
||
"sync"
|
||
"sync/atomic"
|
||
"testing"
|
||
"time"
|
||
|
||
"example.com/ueino/adk/internal/config"
|
||
"example.com/ueino/pkg/model"
|
||
)
|
||
|
||
func TestTravelGuideGraph(t *testing.T) {
|
||
for _, mode := range []string{"确认生成", "拒绝", "预报缺失", "日期超范围", "规划失败", "生图失败", "取消生图", "确认EOF", "无确认入口", "确认时取消"} {
|
||
t.Run(mode, func(t *testing.T) {
|
||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||
defer cancel()
|
||
today := time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60))
|
||
start, end := today.AddDate(0, 0, 1).Format(time.DateOnly), today.AddDate(0, 0, 2).Format(time.DateOnly)
|
||
request := model.TravelRequest{Location: "成都", StartDate: start, EndDate: end, Requirements: "休闲游,蓝色攻略图"}
|
||
if mode == "日期超范围" {
|
||
request.StartDate, request.EndDate = "2999-01-01", "2999-01-02"
|
||
}
|
||
plan := start + ":小雨,上午博物馆,下午宽窄巷子,晚上品尝川菜。\n" + end + ":晴,上午人民公园,下午武侯祠,晚上锦里。雨天改为室内参观。"
|
||
var weatherCalls, plannerCalls, imageCalls, mainCalls atomic.Int32
|
||
var output strings.Builder
|
||
planDisplayed := make(chan struct{})
|
||
var displayedOnce sync.Once
|
||
firstPart := strings.SplitN(plan, "\n", 2)[0] + "\n"
|
||
previous := http.DefaultTransport
|
||
http.DefaultTransport = roundTripperFunc(func(r *http.Request) (*http.Response, error) {
|
||
var response any
|
||
switch r.URL.Host {
|
||
case "geocoding-api.open-meteo.com":
|
||
if r.URL.Query().Get("name") != "成都" {
|
||
t.Errorf("地点错误: %s", r.URL)
|
||
}
|
||
response = map[string]any{"results": []map[string]any{{"name": "成都", "country": "中国", "latitude": 30.67, "longitude": 104.07}}}
|
||
case "api.open-meteo.com":
|
||
if r.URL.Query().Get("start_date") != start || r.URL.Query().Get("end_date") != end {
|
||
t.Errorf("预报日期错误: %s", r.URL)
|
||
}
|
||
if mode == "预报缺失" {
|
||
response = map[string]any{}
|
||
} else {
|
||
response = map[string]any{"daily": map[string]any{"time": []string{start, end}, "weather_code": []int{61, 0}, "temperature_2m_min": []int{8, 9}, "temperature_2m_max": []int{16, 19}, "precipitation_probability_max": []int{80, 0}}}
|
||
}
|
||
default:
|
||
return previous.RoundTrip(r)
|
||
}
|
||
weatherCalls.Add(1)
|
||
data, _ := json.Marshal(response)
|
||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(data))), Header: make(http.Header), Request: r}, nil
|
||
})
|
||
t.Cleanup(func() { http.DefaultTransport = previous })
|
||
directory := t.TempDir()
|
||
images := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
imageCalls.Add(1)
|
||
var body model.ImageGenerationRequest
|
||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||
t.Error(err)
|
||
}
|
||
if !strings.Contains(body.Prompt, plan) || !strings.Contains(body.Prompt, start) || !strings.Contains(body.Prompt, "休闲游,蓝色攻略图") {
|
||
t.Errorf("绘图提示词未保留行程和用户约束: %s", body.Prompt)
|
||
}
|
||
if mode == "取消生图" {
|
||
cancel()
|
||
<-r.Context().Done()
|
||
return
|
||
}
|
||
if mode == "生图失败" {
|
||
http.Error(w, "图片服务不可用", 502)
|
||
return
|
||
}
|
||
json.NewEncoder(w).Encode(model.ImageGenerationResponse{Data: []model.ImageGenerationData{{Base64: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jKioAAAAASUVORK5CYII="}}})
|
||
}))
|
||
defer images.Close()
|
||
weatherUnavailable := mode == "预报缺失" || mode == "日期超范围"
|
||
main := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
var body model.ChatCompletionRequest
|
||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||
t.Error(err)
|
||
}
|
||
if len(body.Tools) == 0 {
|
||
plannerCalls.Add(1)
|
||
if !body.Stream {
|
||
t.Error("规划应流式输出给用户")
|
||
}
|
||
var guide model.TravelGuide
|
||
if len(body.Messages) != 2 {
|
||
t.Errorf("规划消息不正确: %+v", body.Messages)
|
||
}
|
||
if err := json.Unmarshal([]byte(body.Messages[1].Content.(string)), &guide); err != nil || len(guide.Weather.Days) != 2 || guide.Weather.Days[0].Condition != "小雨" || guide.Request.Requirements != request.Requirements {
|
||
t.Errorf("规划未收到真实预报和偏好: %+v,%v", guide, err)
|
||
}
|
||
if mode == "规划失败" {
|
||
writeCompletion(w, body.Stream, "", nil)
|
||
} else if mode == "确认生成" {
|
||
// 先发送半段行程,等终端消费后再继续,验证不是结束后才回放。
|
||
w.Header().Set("Content-Type", "text/event-stream")
|
||
chunk, _ := json.Marshal(model.ChatCompletionResponse{Choices: []model.ChatCompletionChoice{{Delta: model.ChatCompletionDelta{Content: firstPart}}}})
|
||
fmt.Fprintf(w, "data: %s\n\n", chunk)
|
||
w.(http.Flusher).Flush()
|
||
select {
|
||
case <-planDisplayed:
|
||
case <-time.After(2 * time.Second):
|
||
t.Error("规划尚未结束时,前半段内容没有展示给用户")
|
||
}
|
||
writeCompletion(w, true, strings.TrimPrefix(plan, firstPart), nil)
|
||
} else {
|
||
writeCompletion(w, body.Stream, plan, nil)
|
||
}
|
||
return
|
||
}
|
||
if mainCalls.Add(1) != 1 {
|
||
t.Error("攻略流程应直接返回,不应再次请求主模型")
|
||
}
|
||
args, _ := json.Marshal(request)
|
||
writeCompletion(w, body.Stream, "", []model.ToolCall{{ID: "travel-1", Type: "function", Function: model.ToolFunction{Name: travelToolName, Arguments: string(args)}}})
|
||
}))
|
||
defer main.Close()
|
||
chat, err := New(ctx, config.Config{
|
||
Chat: config.ModelConfig{BaseURL: main.URL, Model: "chat-model"},
|
||
Image: config.ImageConfig{ModelConfig: config.ModelConfig{BaseURL: images.URL, Model: "image-model"}, OutputDir: directory},
|
||
MaxToken: 4096,
|
||
})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
confirmCalls := 0
|
||
confirm := func(prompt string) (bool, error) {
|
||
confirmCalls++
|
||
shown := output.String()
|
||
weatherAt, planAt, nextAt := strings.Index(shown, "查到成都"), strings.Index(shown, plan), strings.Index(shown, "接下来我会")
|
||
if weatherAt < 0 || planAt <= weatherAt || nextAt <= planAt {
|
||
t.Errorf("确认前应依次展示天气、行程和绘图说明: %q", shown)
|
||
}
|
||
if imageCalls.Load() != 0 || plannerCalls.Load() != 1 || weatherCalls.Load() != 2 || mainCalls.Load() != 1 || !strings.Contains(prompt, plan) {
|
||
t.Errorf("确认前的流程执行不正确:天气 %d,规划 %d,生图 %d,主助手 %d", weatherCalls.Load(), plannerCalls.Load(), imageCalls.Load(), mainCalls.Load())
|
||
}
|
||
if mode == "确认EOF" {
|
||
return false, io.EOF
|
||
}
|
||
if mode == "确认时取消" {
|
||
cancel()
|
||
}
|
||
return mode != "拒绝", nil
|
||
}
|
||
if mode == "无确认入口" {
|
||
confirm = nil
|
||
}
|
||
err = chat.Chat(ctx, "这周末去成都,查天气、规划怎么玩并生成旅游攻略图", func(s string) {
|
||
output.WriteString(s)
|
||
if strings.Contains(output.String(), firstPart) {
|
||
displayedOnce.Do(func() { close(planDisplayed) })
|
||
}
|
||
}, nil, confirm)
|
||
success := mode == "确认生成" || weatherUnavailable
|
||
if success && err != nil || !success && err == nil {
|
||
t.Fatalf("执行结果不正确: %v", err)
|
||
}
|
||
if mode == "拒绝" && !errors.Is(err, ErrImageRejected) || mode == "确认EOF" && !errors.Is(err, io.EOF) || (mode == "确认时取消" || mode == "取消生图") && !errors.Is(err, context.Canceled) {
|
||
t.Fatalf("确认结果没有正确透传: %v", err)
|
||
}
|
||
if len(chat.checkpoints.data) != 0 {
|
||
t.Fatal("轮次结束应清理内外两层 checkpoint")
|
||
}
|
||
if mode == "确认生成" {
|
||
if strings.Count(output.String(), plan) != 1 || strings.Count(output.String(), "查到成都") != 1 || strings.Count(output.String(), "攻略图:") != 1 {
|
||
t.Fatalf("恢复和完成后不应重复播报天气、行程或路径: %q", output.String())
|
||
}
|
||
files, err := os.ReadDir(directory)
|
||
if err != nil || len(files) != 1 || !strings.Contains(output.String(), directory) {
|
||
t.Fatalf("攻略图未保存或未展示实际路径: %v,%v,%q", files, err, output.String())
|
||
}
|
||
if imageCalls.Load() != 1 || plannerCalls.Load() != 1 || weatherCalls.Load() != 2 || mainCalls.Load() != 1 || !strings.Contains(output.String(), plan) || len(chat.memory.LoadHistory()) != 2 {
|
||
t.Fatalf("恢复后重复执行或未返回结果:天气%d,规划%d,生图%d,主助手%d", weatherCalls.Load(), plannerCalls.Load(), imageCalls.Load(), mainCalls.Load())
|
||
}
|
||
history := chat.memory.LoadHistory()
|
||
if len(history) != 2 || !strings.Contains(history[1].Content.(string), "查到成都") || !strings.Contains(history[1].Content.(string), plan) || !strings.Contains(history[1].Content.(string), directory) {
|
||
t.Fatal("成功后应保存完整天气、行程和图片路径,而不只是最后一条通知")
|
||
}
|
||
} else if mode != "生图失败" && mode != "取消生图" && imageCalls.Load() != 0 {
|
||
t.Fatal("失败或未确认时不能请求图片接口")
|
||
}
|
||
if weatherUnavailable || mode == "规划失败" {
|
||
if confirmCalls != 0 {
|
||
t.Fatal("尚未规划完成不能请求确认")
|
||
}
|
||
}
|
||
if weatherUnavailable && (plannerCalls.Load() != 0 || !strings.Contains(output.String(), "无法获取出行日期的天气预报")) {
|
||
t.Fatal("没有目标日期预报时不能规划")
|
||
}
|
||
if !success && len(chat.memory.LoadHistory()) != 0 {
|
||
t.Fatal("失败或取消的任务不应写入历史")
|
||
}
|
||
})
|
||
}
|
||
}
|