feat: add travel guide Graph with progressive output and image confirmation
This commit is contained in:
1 parent
fd3dcbe104
commit
73f6f0901e
13 files changed
+577
-26
No files matched your search
@@ -33,26 +33,34 @@ func New(ctx context.Context, cfg config.Config) (*Agent, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tools := []einotool.BaseTool{tool.NewWeather()}
|
||||
store := &checkpointStore{data: make(map[string][]byte)}
|
||||
weather := tool.NewWeather()
|
||||
tools := []einotool.BaseTool{weather}
|
||||
instruction := opt.SYSTEM_PROMPT
|
||||
var returnDirectly map[string]bool
|
||||
|
||||
if cfg.Image.Model != "" {
|
||||
image := provider.NewImage(cfg.Image.BaseURL, cfg.Image.Model, cfg.Image.APIKey, cfg.Image.OutputDir)
|
||||
tools = append(tools, &confirmedImage{InvokableTool: tool.NewImage(image)})
|
||||
instruction += imagePrompt
|
||||
imageTool := &confirmedImage{InvokableTool: tool.NewImage(image)}
|
||||
travel, err := newTravelTool(ctx, chat, weather, imageTool, store)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("创建旅游攻略流程失败: %w", err)
|
||||
}
|
||||
tools = append(tools, imageTool, travel)
|
||||
instruction += imagePrompt + travelPrompt
|
||||
returnDirectly = map[string]bool{travelToolName: true}
|
||||
}
|
||||
|
||||
mainAgent, err := adk.NewChatModelAgent(ctx, &adk.ChatModelAgentConfig{
|
||||
Name: mainAgentName, Instruction: instruction, Model: chat, MaxIterations: opt.MAX_TOOL_ROUND,
|
||||
GenModelInput: genModelInput,
|
||||
ToolsConfig: adk.ToolsConfig{ToolsNodeConfig: compose.ToolsNodeConfig{Tools: tools}},
|
||||
ToolsConfig: adk.ToolsConfig{ToolsNodeConfig: compose.ToolsNodeConfig{Tools: tools}, ReturnDirectly: returnDirectly},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
store := &checkpointStore{data: make(map[string][]byte)}
|
||||
return &Agent{
|
||||
runner: adk.NewRunner(ctx, adk.RunnerConfig{Agent: mainAgent, EnableStreaming: true, CheckPointStore: store}),
|
||||
memory: memory.NewMemory(cfg.MaxToken),
|
||||
@@ -66,7 +74,7 @@ func newChatModel(ctx context.Context, cfg config.ModelConfig) (*openai.ChatMode
|
||||
})
|
||||
}
|
||||
|
||||
// Chat 只输出主助手正文,状态单独回调;只有成功完成的最终回复才写入记忆。
|
||||
// Chat 输出助手正文或流程结果,状态单独回调;只保存成功完成的最终回复。
|
||||
func (a *Agent) Chat(ctx context.Context, input string, onText, onStatus func(string), confirm func(string) (bool, error)) error {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
@@ -75,9 +83,9 @@ func (a *Agent) Chat(ctx context.Context, input string, onText, onStatus func(st
|
||||
messages = append(messages, &schema.Message{Role: schema.RoleType(message.Role), Content: message.Content.(string)})
|
||||
}
|
||||
messages = append(messages, schema.UserMessage(input))
|
||||
// 示例只允许终端顺序处理一轮,轮次结束后清理对应的 checkpoint。
|
||||
// 终端顺序处理一轮,结束时清理 Runner 和内部 Graph 的 checkpoint。
|
||||
const checkpointID = "chat"
|
||||
defer a.checkpoints.Delete(context.Background(), checkpointID)
|
||||
defer a.checkpoints.Clear()
|
||||
events := a.runner.Run(ctx, messages, adk.WithCheckPointID(checkpointID))
|
||||
for {
|
||||
reply, interrupted, err := readResponse(events, onText, onStatus)
|
||||
|
||||
@@ -98,13 +98,16 @@ func TestDefaultImageCapability(t *testing.T) {
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
hasImage := false
|
||||
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 {
|
||||
if hasImage != enabled || hasTravel != enabled {
|
||||
t.Errorf("生图工具 注册状态 = %v,期望 %v", hasImage, enabled)
|
||||
}
|
||||
if enabled && !strings.Contains(request.Messages[0].Content.(string), "用户只询问能否生图") {
|
||||
|
||||
@@ -25,9 +25,8 @@ func (s *checkpointStore) Set(_ context.Context, id string, data []byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *checkpointStore) Delete(_ context.Context, id string) error {
|
||||
func (s *checkpointStore) Clear() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
delete(s.data, id)
|
||||
return nil
|
||||
clear(s.data)
|
||||
}
|
||||
@@ -62,7 +62,7 @@ func TestImageTool(t *testing.T) {
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if r.URL.Path != "/v1/chat/completions" || r.Header.Get("Authorization") != "Bearer main-key" || request.Model != "main-model" || len(request.Tools) != 2 || request.Tools[0].Function.Name != "get_weather" || request.Tools[1].Function.Name != "generate_image" {
|
||||
if r.URL.Path != "/v1/chat/completions" || r.Header.Get("Authorization") != "Bearer main-key" || request.Model != "main-model" || len(request.Tools) != 3 || request.Tools[0].Function.Name != "get_weather" || request.Tools[1].Function.Name != "generate_image" {
|
||||
t.Errorf("主 Agent 请求不正确: %+v", request)
|
||||
}
|
||||
n := mainCalls.Add(1)
|
||||
|
||||
@@ -2,5 +2,14 @@ package agent
|
||||
|
||||
const imagePrompt = `
|
||||
你可以通过 generate_image 工具生成图片。用户只询问能否生图或有哪些能力时,说明支持图片创作,并请用户提供画面需求,不调用工具。
|
||||
用户明确要求创作图片时,结合当前对话中的需求和约束,整理包含主体、构图、风格的完整提示词后调用 generate_image。未指定风格时使用合理默认值,不进行多轮追问。
|
||||
用户明确要求普通图片创作时,结合当前对话中的需求和约束,整理包含主体、构图、风格的完整提示词后调用 generate_image。未指定风格时使用合理默认值,不进行多轮追问。
|
||||
每个任务只生成一张图片,不自行重试。工具成功后准确保留实际图片路径并简短回复;失败时如实说明,不编造成功结果或文件路径。`
|
||||
|
||||
const travelPrompt = `
|
||||
用户要求结合天气规划旅游并生成攻略图时,调用 create_travel_guide,一次传入城市、具体日期范围和完整用户偏好,由固定流程完成。不要拆成单独天气和生图调用。
|
||||
工具成功后直接返回文字行程和图片路径,不需要再次规划。预报不可用时解释原因,不绕过该流程自行生成攻略图。普通生图需求仍使用 generate_image。`
|
||||
|
||||
const travelPlanPrompt = `你是旅游行程规划助手。输入包含具体出行日期、城市、用户偏好和真实逐日天气。
|
||||
先用一两句话根据真实天气评价出游条件,说明适合的活动和推荐理由,不重复列出完整预报,不推断未提供的天气变化(例如不能把晴说成多云转晴);接着输出简洁的中文 Markdown 行程,控制在约400字,逐日明确日期、天气和气温、上午/下午/晚上的游玩顺序、天气依据及雨天室内备选。优先安排同一片区的景点,避免明显来回折返。博物馆等场馆安排在白天,晚上优先安排街区散步和美食,不假设场馆夜间开放。
|
||||
遵守用户约束,不追问未给出的偏好,采用普通休闲游默认安排。只使用提供的天气,不编造预报、实时票价、营业时间、预约状态或精确交通时间。全篇使用中文,不编造景点、展品或外文地名。直接输出可供用户阅读和绘图的行程,不输出工具调用。
|
||||
成都示例资料:市中心片区可安排天府广场、成都博物馆、人民公园、宽窄巷子;武侯祠与锦里相邻;春熙路与太古里相邻。成都未指定景点时只从上述真实地点选择;用户明确指定其他景点时保留其需求,但不编造信息。按片区安排,不把春熙路称为锦里,也不声称宽窄巷子与锦里相邻。雨天室内备选可选成都博物馆,不编造馆内展览。`
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
"github.com/cloudwego/eino/schema"
|
||||
)
|
||||
|
||||
// readResponse 消费事件流,主助手正文和工具执行状态分别输出。
|
||||
// readResponse 消费事件流,正文或流程结果与执行状态分别输出。
|
||||
func readResponse(events *adk.AsyncIterator[*adk.AgentEvent], onText, onStatus func(string)) (string, *adk.InterruptInfo, error) {
|
||||
var interrupted *adk.InterruptInfo
|
||||
reply := ""
|
||||
@@ -37,6 +37,14 @@ func readResponse(events *adk.AsyncIterator[*adk.AgentEvent], onText, onStatus f
|
||||
interrupted = event.Action.Interrupted
|
||||
continue
|
||||
}
|
||||
if event.Output != nil {
|
||||
if progress, ok := event.Output.CustomizedOutput.(travelProgress); ok {
|
||||
if onText != nil {
|
||||
onText(string(progress))
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
if event.Output == nil || event.Output.MessageOutput == nil {
|
||||
continue
|
||||
}
|
||||
@@ -56,13 +64,35 @@ func readResponse(events *adk.AsyncIterator[*adk.AgentEvent], onText, onStatus f
|
||||
}
|
||||
if output.Role == schema.Tool {
|
||||
message := fmt.Sprintf("%s:%s 执行完成", event.AgentName, output.ToolName)
|
||||
if output.ToolName == "generate_image" {
|
||||
if output.ToolName == "generate_image" || output.ToolName == travelToolName {
|
||||
var result model.ImageResult
|
||||
if json.Unmarshal([]byte(text), &result) == nil && result.Path != "" {
|
||||
message += ",图片:" + result.Path
|
||||
}
|
||||
}
|
||||
status(message)
|
||||
if output.ToolName == travelToolName {
|
||||
// 固定流程直接返回结果,避免模型再次改写或省略已完成的行程。
|
||||
var guide model.TravelGuide
|
||||
if err := json.Unmarshal([]byte(text), &guide); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
reply = guide.Problem
|
||||
if reply == "" {
|
||||
if guide.Plan == "" || guide.Path == "" {
|
||||
return "", nil, fmt.Errorf("攻略流程未返回完整行程和图片路径")
|
||||
}
|
||||
reply = travelWeatherText(guide.Weather) + guide.Plan + "\n\n攻略图:" + guide.Path
|
||||
}
|
||||
if onText != nil {
|
||||
if guide.Problem != "" {
|
||||
onText(guide.Problem)
|
||||
} else {
|
||||
// 天气和行程已在确认前展示,完成后只补充实际图片路径。
|
||||
onText("\n攻略图:" + guide.Path)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
"example.com/ueino/pkg/tool"
|
||||
|
||||
einomodel "github.com/cloudwego/eino/components/model"
|
||||
einotool "github.com/cloudwego/eino/components/tool"
|
||||
"github.com/cloudwego/eino/compose"
|
||||
"github.com/cloudwego/eino/schema"
|
||||
)
|
||||
|
||||
const travelToolName = "create_travel_guide"
|
||||
|
||||
func init() {
|
||||
// Graph 暂停时,节点之间传递的数据需要能写入 checkpoint。
|
||||
schema.RegisterName[*model.TravelGuide]("sample_travel_guide")
|
||||
schema.RegisterName[travelProgress]("sample_travel_progress")
|
||||
}
|
||||
|
||||
// travelTool 将固定 Graph 作为主助手的一项普通工具能力。
|
||||
type travelTool struct {
|
||||
graph compose.Runnable[*model.TravelGuide, *model.TravelGuide]
|
||||
}
|
||||
|
||||
func newTravelTool(ctx context.Context, chat einomodel.BaseChatModel, weather *tool.Weather, image einotool.InvokableTool, store *checkpointStore) (*travelTool, error) {
|
||||
graph := compose.NewGraph[*model.TravelGuide, *model.TravelGuide]()
|
||||
for _, err := range []error{
|
||||
graph.AddLambdaNode("weather", compose.InvokableLambda(func(ctx context.Context, guide *model.TravelGuide) (*model.TravelGuide, error) {
|
||||
args, _ := json.Marshal(model.WeatherArguments{Location: guide.Request.Location, StartDate: guide.Request.StartDate, EndDate: guide.Request.EndDate})
|
||||
result, err := weather.Execute(ctx, string(args))
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
if err == nil {
|
||||
err = json.Unmarshal([]byte(result), &guide.Weather)
|
||||
}
|
||||
if err != nil {
|
||||
guide.Problem = "无法获取出行日期的天气预报,未规划或生成图片:" + err.Error()
|
||||
} else if err := emitTravelText(ctx, travelWeatherText(guide.Weather)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return guide, nil
|
||||
})),
|
||||
graph.AddLambdaNode("plan", compose.InvokableLambda(func(ctx context.Context, guide *model.TravelGuide) (*model.TravelGuide, error) {
|
||||
data, _ := json.Marshal(guide)
|
||||
stream, err := chat.Stream(ctx, []*schema.Message{
|
||||
schema.SystemMessage(travelPlanPrompt), schema.UserMessage(string(data)),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer stream.Close()
|
||||
var plan strings.Builder
|
||||
for {
|
||||
chunk, err := stream.Recv()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if chunk.Content != "" {
|
||||
plan.WriteString(chunk.Content)
|
||||
if err := emitTravelText(ctx, chunk.Content); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
guide.Plan = strings.TrimSpace(plan.String())
|
||||
if guide.Plan == "" {
|
||||
return nil, fmt.Errorf("模型未生成旅游行程,未生成图片")
|
||||
}
|
||||
if err := emitTravelText(ctx, "\n\n接下来我会把这份行程制作成旅游攻略图,请先确认绘图提示词。\n"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return guide, nil
|
||||
})),
|
||||
graph.AddLambdaNode("image", compose.InvokableLambda(func(ctx context.Context, guide *model.TravelGuide) (*model.TravelGuide, error) {
|
||||
wasInterrupted, hasState, saved := compose.GetInterruptState[*model.TravelGuide](ctx)
|
||||
if wasInterrupted {
|
||||
if !hasState {
|
||||
return nil, fmt.Errorf("缺少已规划的行程,无法恢复生图")
|
||||
}
|
||||
guide = saved
|
||||
}
|
||||
if guide.ImagePrompt == "" {
|
||||
guide.ImagePrompt = "制作一张清晰、美观的中文旅游攻略信息图,按实际日期分区,突出主要景点、游玩顺序和天气提醒。不要伪造精确地图,避免密集小字。遵循用户偏好:" + guide.Request.Requirements + "\n" + travelWeatherText(guide.Weather) + "行程:\n" + guide.Plan
|
||||
}
|
||||
// 内部中断不会自动保存节点输入,显式保留已完成的行程和提示词。
|
||||
target, hasData, approved := compose.GetResumeContext[bool](ctx)
|
||||
if !wasInterrupted || !target || !hasData {
|
||||
return nil, compose.StatefulInterrupt(ctx, guide.ImagePrompt, guide)
|
||||
}
|
||||
if approved {
|
||||
if err := emitTravelText(ctx, "已确认,正在生成旅游攻略图,请稍候……\n"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
args, _ := json.Marshal(model.ImageArguments{Prompt: guide.ImagePrompt})
|
||||
result, err := image.InvokableRun(ctx, string(args))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var generated model.ImageResult
|
||||
if err := json.Unmarshal([]byte(result), &generated); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
guide.Path = generated.Path
|
||||
return guide, nil
|
||||
})),
|
||||
graph.AddLambdaNode("unavailable", compose.InvokableLambda(func(_ context.Context, guide *model.TravelGuide) (*model.TravelGuide, error) {
|
||||
return guide, nil
|
||||
})),
|
||||
graph.AddEdge(compose.START, "weather"),
|
||||
graph.AddBranch("weather", compose.NewGraphBranch(func(_ context.Context, guide *model.TravelGuide) (string, error) {
|
||||
if guide.Problem != "" {
|
||||
return "unavailable", nil
|
||||
}
|
||||
return "plan", nil
|
||||
}, map[string]bool{"plan": true, "unavailable": true})),
|
||||
graph.AddEdge("plan", "image"),
|
||||
graph.AddEdge("image", compose.END),
|
||||
graph.AddEdge("unavailable", compose.END),
|
||||
} {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
runnable, err := graph.Compile(ctx, compose.WithCheckPointStore(store))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &travelTool{graph: runnable}, nil
|
||||
}
|
||||
|
||||
func (t *travelTool) Info(context.Context) (*schema.ToolInfo, error) {
|
||||
return &schema.ToolInfo{
|
||||
Name: travelToolName,
|
||||
Desc: "结合指定城市和出行日期的真实天气,规划游玩行程并生成一张旅游攻略图。用户同时要求天气、游玩规划和攻略图时调用本工具,一次完成,不必再单独调用天气或生图工具。日期须根据当前时间转换为 YYYY-MM-DD;缺少城市或无法确定日期时先询问。",
|
||||
ParamsOneOf: schema.NewParamsOneOfByParams(map[string]*schema.ParameterInfo{
|
||||
"location": {Type: schema.String, Required: true, Desc: "旅游城市,例如成都"},
|
||||
"start_date": {Type: schema.String, Required: true, Desc: "出行开始日期,YYYY-MM-DD"},
|
||||
"end_date": {Type: schema.String, Desc: "出行结束日期,YYYY-MM-DD,含当天;不传则只玩一天"},
|
||||
"requirements": {Type: schema.String, Desc: "用户完整的旅游需求和偏好,例如休闲、美食、同行人及绘图风格"},
|
||||
}),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (t *travelTool) InvokableRun(ctx context.Context, arguments string, _ ...einotool.Option) (string, error) {
|
||||
var request model.TravelRequest
|
||||
if err := json.Unmarshal([]byte(arguments), &request); err != nil {
|
||||
return "", fmt.Errorf("旅游参数无效: %w", err)
|
||||
}
|
||||
request.Location = strings.TrimSpace(request.Location)
|
||||
request.StartDate = strings.TrimSpace(request.StartDate)
|
||||
request.EndDate = strings.TrimSpace(request.EndDate)
|
||||
if request.Location == "" || request.StartDate == "" {
|
||||
return "", fmt.Errorf("请提供旅游城市和具体出行日期")
|
||||
}
|
||||
if request.EndDate == "" {
|
||||
request.EndDate = request.StartDate
|
||||
}
|
||||
_, hasState, checkpointID := einotool.GetInterruptState[string](ctx)
|
||||
if !hasState {
|
||||
checkpointID = "travel-" + rand.Text()
|
||||
}
|
||||
guide, err := t.graph.Invoke(ctx, &model.TravelGuide{Request: request}, compose.WithCheckPointID(checkpointID))
|
||||
if _, interrupted := compose.ExtractInterruptInfo(err); interrupted {
|
||||
// 保存内部 Graph 的 checkpoint ID,把生图确认透传到外层 Runner。
|
||||
return "", einotool.CompositeInterrupt(ctx, nil, checkpointID, err)
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
data, err := json.Marshal(guide)
|
||||
return string(data), err
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
"github.com/cloudwego/eino/adk"
|
||||
)
|
||||
|
||||
// travelProgress 是流程中的用户可见正文,不是内部日志。
|
||||
type travelProgress string
|
||||
|
||||
func emitTravelText(ctx context.Context, text string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
return adk.SendEvent(ctx, &adk.AgentEvent{
|
||||
Output: &adk.AgentOutput{CustomizedOutput: travelProgress(text)},
|
||||
})
|
||||
}
|
||||
|
||||
func travelWeatherText(weather model.WeatherForecast) string {
|
||||
var text strings.Builder
|
||||
fmt.Fprintf(&text, "查到%s的天气:\n", weather.Location)
|
||||
for _, day := range weather.Days {
|
||||
fmt.Fprintf(&text, "%s:%s,%g~%g°C,最高降雨概率%g%%。\n",
|
||||
day.Date, day.Condition, day.MinTemperatureC, day.MaxTemperatureC, day.PrecipitationChancePct)
|
||||
}
|
||||
text.WriteString("\n")
|
||||
return text.String()
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
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("失败或取消的任务不应写入历史")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,7 @@ func (cfg *Config) BindFlags(flags *pflag.FlagSet) {
|
||||
flags.StringVar(&cfg.chatKeyEnv, "api-key-env", "AI_KEY", "主助手密钥环境变量")
|
||||
flags.IntVar(&cfg.MaxToken, "max-token", 4096, "历史记忆预算")
|
||||
flags.StringVar(&cfg.Image.BaseURL, "image-base-url", "", "图片接口地址,默认沿用主助手")
|
||||
flags.StringVar(&cfg.Image.Model, "image-model", "z-image-turbo", "图片模型,设为空字符串可关闭生图工具")
|
||||
flags.StringVar(&cfg.Image.Model, "image-model", "z-image-turbo", "图片模型,设为空字符串可关闭生图及攻略图工具")
|
||||
flags.StringVar(&cfg.imageKeyEnv, "image-api-key-env", "", "图片接口密钥环境变量,默认沿用主助手")
|
||||
flags.StringVar(&cfg.Image.OutputDir, "image-dir", "./generated", "图片保存目录")
|
||||
flags.StringVar(&cfg.ASR.BaseURL, "asr-base-url", "wss://ai.loveuer.com/v1", "实时语音识别接口地址")
|
||||
|
||||
Reference in new issue
Block a user