feat: initialize Eino examples and ADK applications
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>
This commit is contained in:
commit
81deca8c8e
75 files changed
+7048
No files matched your search
@@ -0,0 +1,133 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"example.com/ueino/adk/internal/config"
|
||||
"example.com/ueino/pkg/memory"
|
||||
"example.com/ueino/pkg/opt"
|
||||
"example.com/ueino/pkg/provider"
|
||||
"example.com/ueino/pkg/tool"
|
||||
|
||||
"github.com/cloudwego/eino-ext/components/model/openai"
|
||||
"github.com/cloudwego/eino/adk"
|
||||
einotool "github.com/cloudwego/eino/components/tool"
|
||||
"github.com/cloudwego/eino/compose"
|
||||
"github.com/cloudwego/eino/schema"
|
||||
)
|
||||
|
||||
const mainAgentName = "terminal_chat"
|
||||
|
||||
// Agent 管理主助手的执行和会话历史。
|
||||
type Agent struct {
|
||||
runner *adk.Runner
|
||||
memory *memory.Memory
|
||||
checkpoints *checkpointStore
|
||||
}
|
||||
|
||||
func New(ctx context.Context, cfg config.Config) (*Agent, error) {
|
||||
chat, err := newChatModel(ctx, cfg.Chat)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
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)
|
||||
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}, ReturnDirectly: returnDirectly},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Agent{
|
||||
runner: adk.NewRunner(ctx, adk.RunnerConfig{Agent: mainAgent, EnableStreaming: true, CheckPointStore: store}),
|
||||
memory: memory.NewMemory(cfg.MaxToken),
|
||||
checkpoints: store,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func newChatModel(ctx context.Context, cfg config.ModelConfig) (*openai.ChatModel, error) {
|
||||
return openai.NewChatModel(ctx, &openai.ChatModelConfig{
|
||||
BaseURL: strings.TrimRight(cfg.BaseURL, "/"), Model: cfg.Model, APIKey: cfg.APIKey,
|
||||
})
|
||||
}
|
||||
|
||||
// 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()
|
||||
var messages []*schema.Message
|
||||
for _, message := range a.memory.LoadHistory() {
|
||||
messages = append(messages, &schema.Message{Role: schema.RoleType(message.Role), Content: message.Content.(string)})
|
||||
}
|
||||
messages = append(messages, schema.UserMessage(input))
|
||||
// 终端顺序处理一轮,结束时清理 Runner 和内部 Graph 的 checkpoint。
|
||||
const checkpointID = "chat"
|
||||
defer a.checkpoints.Clear()
|
||||
events := a.runner.Run(ctx, messages, adk.WithCheckPointID(checkpointID))
|
||||
for {
|
||||
reply, interrupted, err := readResponse(events, onText, onStatus)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if interrupted == nil {
|
||||
if reply != "" {
|
||||
a.memory.Save(input, reply)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if confirm == nil {
|
||||
return fmt.Errorf("生图需要用户确认,当前未提供确认入口")
|
||||
}
|
||||
targets := make(map[string]any)
|
||||
for _, point := range interrupted.InterruptContexts {
|
||||
if !point.IsRootCause {
|
||||
continue
|
||||
}
|
||||
prompt, ok := point.Info.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("无法识别的生图确认信息")
|
||||
}
|
||||
approved, err := confirm(prompt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
targets[point.ID] = approved
|
||||
}
|
||||
if len(targets) == 0 {
|
||||
return fmt.Errorf("没有可恢复的生图确认点")
|
||||
}
|
||||
events, err = a.runner.ResumeWithParams(ctx, checkpointID, &adk.ResumeParams{Targets: targets})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
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())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// checkpointStore 只保存当前终端进程中的暂停状态,退出后不再保留。
|
||||
type checkpointStore struct {
|
||||
mu sync.Mutex
|
||||
data map[string][]byte
|
||||
}
|
||||
|
||||
func (s *checkpointStore) Get(_ context.Context, id string) ([]byte, bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
data, ok := s.data[id]
|
||||
return data, ok, nil
|
||||
}
|
||||
|
||||
func (s *checkpointStore) Set(_ context.Context, id string, data []byte) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.data[id] = data
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *checkpointStore) Clear() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
clear(s.data)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
|
||||
einotool "github.com/cloudwego/eino/components/tool"
|
||||
)
|
||||
|
||||
var ErrImageRejected = errors.New("已取消生图")
|
||||
|
||||
// confirmedImage 将确认策略放在 ADK 应用层,公共生图工具仍只负责执行。
|
||||
type confirmedImage struct {
|
||||
einotool.InvokableTool
|
||||
}
|
||||
|
||||
func (i *confirmedImage) InvokableRun(ctx context.Context, arguments string, opts ...einotool.Option) (string, error) {
|
||||
var args model.ImageArguments
|
||||
if err := json.Unmarshal([]byte(arguments), &args); err != nil {
|
||||
return "", fmt.Errorf("生图参数无效: %w", err)
|
||||
}
|
||||
if strings.TrimSpace(args.Prompt) == "" {
|
||||
return "", fmt.Errorf("生图提示词不能为空")
|
||||
}
|
||||
wasInterrupted, _, _ := einotool.GetInterruptState[any](ctx)
|
||||
if !wasInterrupted {
|
||||
return "", einotool.Interrupt(ctx, args.Prompt)
|
||||
}
|
||||
target, hasData, approved := einotool.GetResumeContext[bool](ctx)
|
||||
if !target || !hasData {
|
||||
return "", einotool.Interrupt(ctx, args.Prompt)
|
||||
}
|
||||
if !approved {
|
||||
return "", ErrImageRejected
|
||||
}
|
||||
return i.InvokableTool.InvokableRun(ctx, arguments, opts...)
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"example.com/ueino/adk/internal/config"
|
||||
"example.com/ueino/pkg/model"
|
||||
)
|
||||
|
||||
// 主助手直接调用生图工具,确认前不能请求图片服务。
|
||||
func TestImageTool(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
failImage bool
|
||||
reject bool
|
||||
confirmError error
|
||||
noConfirm bool
|
||||
cancelConfirm bool
|
||||
}{
|
||||
{name: "确认生成"},
|
||||
{name: "图片服务失败", failImage: true},
|
||||
{name: "拒绝生成", reject: true},
|
||||
{name: "确认时输入结束", confirmError: io.EOF},
|
||||
{name: "没有确认入口", noConfirm: true},
|
||||
{name: "确认时取消", cancelConfirm: true},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
failed := tt.failImage || tt.reject || tt.confirmError != nil || tt.noConfirm || tt.cancelConfirm
|
||||
pngBase64 := "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jKioAAAAASUVORK5CYII="
|
||||
var imageCalls, mainCalls atomic.Int32
|
||||
var savedPath atomic.Value
|
||||
images := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
imageCalls.Add(1)
|
||||
var request model.ImageGenerationRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if r.URL.Path != "/v1/images/generations" || r.Header.Get("Authorization") != "Bearer image-key" || request.Model != "picture-model" || request.Prompt != "专业构图的程序员活动海报" || request.N != 1 {
|
||||
t.Errorf("图片请求不正确: %s, %+v", r.URL, request)
|
||||
}
|
||||
if tt.failImage {
|
||||
http.Error(w, "图片服务不可用", 502)
|
||||
return
|
||||
}
|
||||
json.NewEncoder(w).Encode(model.ImageGenerationResponse{Data: []model.ImageGenerationData{{Base64: pngBase64}}})
|
||||
}))
|
||||
defer images.Close()
|
||||
main := 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)
|
||||
}
|
||||
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)
|
||||
if n == 1 {
|
||||
writeCompletion(w, request.Stream, "", []model.ToolCall{{ID: "generate-1", Type: "function", Function: model.ToolFunction{Name: "generate_image", Arguments: `{"prompt":"专业构图的程序员活动海报"}`}}})
|
||||
return
|
||||
}
|
||||
if failed {
|
||||
if len(request.Messages) != 2 || request.Messages[1].Content != "继续" {
|
||||
t.Errorf("失败的任务不应写入记忆: %+v", request.Messages)
|
||||
}
|
||||
writeCompletion(w, request.Stream, "继续聊天", nil)
|
||||
return
|
||||
}
|
||||
if n == 2 {
|
||||
if len(request.Messages) != 4 || request.Messages[3].Role != "tool" || request.Messages[3].ToolCallID != "generate-1" {
|
||||
t.Errorf("主助手没有接到工具结果: %+v", request.Messages)
|
||||
}
|
||||
var result model.ImageResult
|
||||
if err := json.Unmarshal([]byte(request.Messages[3].Content.(string)), &result); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
png, err := os.ReadFile(result.Path)
|
||||
expected, _ := base64.StdEncoding.DecodeString(pngBase64)
|
||||
if err != nil || string(png) != string(expected) {
|
||||
t.Errorf("图片未保存: %q, %v", result.Path, err)
|
||||
}
|
||||
savedPath.Store(result.Path)
|
||||
writeCompletion(w, request.Stream, "最终回复:"+savedPath.Load().(string), nil)
|
||||
return
|
||||
}
|
||||
if len(request.Messages) != 4 || request.Messages[1].Content != "帮我制作海报" || request.Messages[2].Content != "最终回复:"+savedPath.Load().(string) || request.Messages[3].Content != "继续" {
|
||||
t.Errorf("只应记住主 Agent 最终回复: %+v", request.Messages)
|
||||
}
|
||||
writeCompletion(w, request.Stream, "继续聊天", nil)
|
||||
}))
|
||||
defer main.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
directory := t.TempDir()
|
||||
chat, err := New(ctx, config.Config{
|
||||
Chat: config.ModelConfig{BaseURL: main.URL + "/v1", Model: "main-model", APIKey: "main-key"},
|
||||
Image: config.ImageConfig{ModelConfig: config.ModelConfig{BaseURL: images.URL + "/v1", Model: "picture-model", APIKey: "image-key"}, OutputDir: directory},
|
||||
MaxToken: 4096,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var output strings.Builder
|
||||
var statuses []string
|
||||
confirmCalls := 0
|
||||
confirm := func(prompt string) (bool, error) {
|
||||
confirmCalls++
|
||||
if imageCalls.Load() != 0 || prompt != "专业构图的程序员活动海报" {
|
||||
t.Errorf("确认前不能调用图片接口,提示词 = %q", prompt)
|
||||
}
|
||||
if mainCalls.Load() != 1 {
|
||||
t.Error("恢复不应重新规划")
|
||||
}
|
||||
if len(chat.memory.LoadHistory()) != 0 {
|
||||
t.Error("暂停的任务不应写入记忆")
|
||||
}
|
||||
if tt.cancelConfirm {
|
||||
cancel()
|
||||
}
|
||||
return !tt.reject, tt.confirmError
|
||||
}
|
||||
if tt.noConfirm {
|
||||
confirm = nil
|
||||
}
|
||||
err = chat.Chat(ctx, "帮我制作海报", func(text string) { output.WriteString(text) }, func(status string) { statuses = append(statuses, status) }, confirm)
|
||||
if tt.noConfirm {
|
||||
if confirmCalls != 0 || err == nil || !strings.Contains(err.Error(), "确认入口") {
|
||||
t.Fatalf("缺少确认入口时应停止: %v", err)
|
||||
}
|
||||
} else if confirmCalls != 1 {
|
||||
t.Fatalf("确认次数 = %d", confirmCalls)
|
||||
}
|
||||
if tt.reject && !errors.Is(err, ErrImageRejected) {
|
||||
t.Fatalf("拒绝错误 = %v", err)
|
||||
}
|
||||
if tt.confirmError != nil && !errors.Is(err, tt.confirmError) {
|
||||
t.Fatalf("确认错误 = %v", err)
|
||||
}
|
||||
if tt.cancelConfirm && !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("取消错误 = %v", err)
|
||||
}
|
||||
|
||||
if failed {
|
||||
if err == nil || strings.Contains(output.String(), "已保存") {
|
||||
t.Fatalf("生图失败不应成功: %q, %v", output.String(), err)
|
||||
}
|
||||
files, _ := os.ReadDir(directory)
|
||||
if len(files) != 0 {
|
||||
t.Fatal("失败不应留下图片")
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if output.String() != "最终回复:"+savedPath.Load().(string) {
|
||||
t.Fatalf("工具结果不应直接进入正文: %q", output.String())
|
||||
}
|
||||
if !strings.Contains(strings.Join(statuses, "\n"), "generate_image") || !strings.Contains(strings.Join(statuses, "\n"), savedPath.Load().(string)) {
|
||||
t.Fatalf("缺少真实执行状态: %v", statuses)
|
||||
}
|
||||
if savedPath.Load() == nil {
|
||||
t.Fatal("没有生成图片")
|
||||
}
|
||||
}
|
||||
nextCtx, nextCancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer nextCancel()
|
||||
if err := chat.Chat(nextCtx, "继续", nil, nil, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expectedMain := int32(3)
|
||||
if failed {
|
||||
expectedMain = 2
|
||||
}
|
||||
expectedImages := int32(1)
|
||||
if tt.reject || tt.confirmError != nil || tt.noConfirm || tt.cancelConfirm {
|
||||
expectedImages = 0
|
||||
}
|
||||
if len(chat.checkpoints.data) != 0 {
|
||||
t.Fatal("轮次结束应清理 checkpoint")
|
||||
}
|
||||
if imageCalls.Load() != expectedImages || mainCalls.Load() != expectedMain {
|
||||
t.Fatalf("调用次数:图片 %d,模型 %d", imageCalls.Load(), mainCalls.Load())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func writeCompletion(w http.ResponseWriter, stream bool, text string, calls []model.ToolCall) {
|
||||
reason := "stop"
|
||||
if len(calls) > 0 {
|
||||
reason = "tool_calls"
|
||||
}
|
||||
choice := model.ChatCompletionChoice{FinishReason: reason}
|
||||
if stream {
|
||||
for i := range calls {
|
||||
index := i
|
||||
calls[i].Index = &index
|
||||
}
|
||||
choice.Delta = model.ChatCompletionDelta{Content: text, ToolCalls: calls}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
data, _ := json.Marshal(model.ChatCompletionResponse{Choices: []model.ChatCompletionChoice{choice}})
|
||||
fmt.Fprintf(w, "data: %s\n\ndata: [DONE]\n\n", data)
|
||||
} else {
|
||||
choice.Message = model.ChatMessage{Role: "assistant", Content: text, ToolCalls: calls}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(model.ChatCompletionResponse{Choices: []model.ChatCompletionChoice{choice}})
|
||||
}
|
||||
}
|
||||
|
||||
func TestImageToolCancellation(t *testing.T) {
|
||||
started := make(chan struct{})
|
||||
images := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var request model.ImageGenerationRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
close(started)
|
||||
<-r.Context().Done()
|
||||
}))
|
||||
defer images.Close()
|
||||
main := 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)
|
||||
}
|
||||
writeCompletion(w, request.Stream, "", []model.ToolCall{{ID: "generate-1", Type: "function", Function: model.ToolFunction{Name: "generate_image", Arguments: `{"prompt":"画猫"}`}}})
|
||||
}))
|
||||
defer main.Close()
|
||||
directory := t.TempDir()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
chat, err := New(ctx, config.Config{
|
||||
Chat: config.ModelConfig{BaseURL: main.URL, Model: "main-model"},
|
||||
Image: config.ImageConfig{ModelConfig: config.ModelConfig{BaseURL: images.URL, Model: "picture-model"}, OutputDir: directory},
|
||||
MaxToken: 4096,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
finished := make(chan error, 1)
|
||||
go func() {
|
||||
finished <- chat.Chat(ctx, "画猫", nil, nil, func(string) (bool, error) { return true, nil })
|
||||
}()
|
||||
select {
|
||||
case <-started:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("生图请求未开始")
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case err := <-finished:
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("取消错误 = %v", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("取消未传递到生图工具")
|
||||
}
|
||||
if len(chat.memory.LoadHistory()) != 0 {
|
||||
t.Fatal("取消的任务不应进入记忆")
|
||||
}
|
||||
files, err := os.ReadDir(directory)
|
||||
if err != nil || len(files) != 0 {
|
||||
t.Fatalf("取消后不应保存图片: %v, %v", files, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/cloudwego/eino/adk"
|
||||
"github.com/cloudwego/eino/schema"
|
||||
)
|
||||
|
||||
func genModelInput(_ context.Context, instruction string, input *adk.AgentInput) ([]adk.Message, error) {
|
||||
messages := []adk.Message{schema.SystemMessage(timedInstruction(instruction, time.Now()))}
|
||||
return append(messages, input.Messages...), nil
|
||||
}
|
||||
|
||||
// timedInstruction 每轮生成时间信息,避免使用进程启动时的旧日期。
|
||||
func timedInstruction(instruction string, now time.Time) string {
|
||||
now = now.In(time.FixedZone("Asia/Shanghai", 8*60*60))
|
||||
weekdays := [...]string{"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}
|
||||
// 按周一至周日确定当前周,给模型明确的日期参照。
|
||||
weekday := (int(now.Weekday()) + 6) % 7
|
||||
saturday := now.AddDate(0, 0, 5-weekday)
|
||||
return instruction + fmt.Sprintf(`
|
||||
当前日期:%s,%s,时区:Asia/Shanghai(UTC+08:00)。
|
||||
明天:%s;本周六:%s;本周日:%s。
|
||||
查询天气时将相对时间换算为 YYYY-MM-DD,日期参数只能是一个完整日期,不要把多个日期拼进同一个字段。
|
||||
查询本周末两天时,日期参数示例:{"start_date":"%s","end_date":"%s"},location 使用用户指定的地点。日期存在歧义时先询问。
|
||||
未提供查询地点且历史中也没有时,先询问,不要猜测。收到预报后直接根据结果回答,不重复查询相同日期;无法获取时如实说明,不用今天的预报代替其他目标日期的预报。`,
|
||||
now.Format(time.DateOnly), weekdays[now.Weekday()], now.AddDate(0, 0, 1).Format(time.DateOnly),
|
||||
saturday.Format(time.DateOnly), saturday.AddDate(0, 0, 1).Format(time.DateOnly),
|
||||
saturday.Format(time.DateOnly), saturday.AddDate(0, 0, 1).Format(time.DateOnly))
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/cloudwego/eino/adk"
|
||||
"github.com/cloudwego/eino/schema"
|
||||
)
|
||||
|
||||
func TestTimedInstruction(t *testing.T) {
|
||||
// 同一进程跨越北京时间午夜后,日期与星期都必须更新。
|
||||
before := time.Date(2026, 11, 18, 15, 59, 0, 0, time.UTC)
|
||||
after := before.Add(time.Minute)
|
||||
for _, tt := range []struct {
|
||||
now time.Time
|
||||
date string
|
||||
day string
|
||||
}{
|
||||
{before, "2026-11-18", "星期三"},
|
||||
{after, "2026-11-19", "星期四"},
|
||||
} {
|
||||
prompt := timedInstruction("原有指令", tt.now)
|
||||
for _, expected := range []string{"原有指令", tt.date, tt.day, "Asia/Shanghai", "YYYY-MM-DD", "先询问", `"start_date":"2026-11-21","end_date":"2026-11-22"`} {
|
||||
if !strings.Contains(prompt, expected) {
|
||||
t.Errorf("系统消息缺少 %q", expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenModelInput(t *testing.T) {
|
||||
user := schema.UserMessage("明天北京的天气")
|
||||
input := &adk.AgentInput{Messages: []adk.Message{user}}
|
||||
messages, err := genModelInput(context.Background(), "原有指令", input)
|
||||
if err != nil || len(messages) != 2 || messages[0].Role != schema.System || messages[1] != user || len(input.Messages) != 1 {
|
||||
t.Fatalf("模型输入 = %+v,错误 = %v", messages, err)
|
||||
}
|
||||
date := time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60)).Format(time.DateOnly)
|
||||
if !strings.Contains(messages[0].Content, date) {
|
||||
t.Fatal("系统消息缺少当前日期")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package agent
|
||||
|
||||
const imagePrompt = `
|
||||
你可以通过 generate_image 工具生成图片。用户只询问能否生图或有哪些能力时,说明支持图片创作,并请用户提供画面需求,不调用工具。
|
||||
用户明确要求普通图片创作时,结合当前对话中的需求和约束,整理包含主体、构图、风格的完整提示词后调用 generate_image。未指定风格时使用合理默认值,不进行多轮追问。
|
||||
每个任务只生成一张图片,不自行重试。工具成功后准确保留实际图片路径并简短回复;失败时如实说明,不编造成功结果或文件路径。`
|
||||
|
||||
const travelPrompt = `
|
||||
用户要求结合天气规划旅游并生成攻略图时,调用 create_travel_guide,一次传入城市、具体日期范围和完整用户偏好,由固定流程完成。不要拆成单独天气和生图调用。
|
||||
工具成功后直接返回文字行程和图片路径,不需要再次规划。预报不可用时解释原因,不绕过该流程自行生成攻略图。普通生图需求仍使用 generate_image。`
|
||||
|
||||
const travelPlanPrompt = `你是旅游行程规划助手。输入包含具体出行日期、城市、用户偏好和真实逐日天气。
|
||||
先用一两句话根据真实天气评价出游条件,说明适合的活动和推荐理由,不重复列出完整预报,不推断未提供的天气变化(例如不能把晴说成多云转晴);接着输出简洁的中文 Markdown 行程,控制在约400字,逐日明确日期、天气和气温、上午/下午/晚上的游玩顺序、天气依据及雨天室内备选。优先安排同一片区的景点,避免明显来回折返。博物馆等场馆安排在白天,晚上优先安排街区散步和美食,不假设场馆夜间开放。
|
||||
遵守用户约束,不追问未给出的偏好,采用普通休闲游默认安排。只使用提供的天气,不编造预报、实时票价、营业时间、预约状态或精确交通时间。全篇使用中文,不编造景点、展品或外文地名。直接输出可供用户阅读和绘图的行程,不输出工具调用。
|
||||
成都示例资料:市中心片区可安排天府广场、成都博物馆、人民公园、宽窄巷子;武侯祠与锦里相邻;春熙路与太古里相邻。成都未指定景点时只从上述真实地点选择;用户明确指定其他景点时保留其需求,但不编造信息。按片区安排,不把春熙路称为锦里,也不声称宽窄巷子与锦里相邻。雨天室内备选可选成都博物馆,不编造馆内展览。`
|
||||
@@ -0,0 +1,125 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
|
||||
"github.com/cloudwego/eino/adk"
|
||||
"github.com/cloudwego/eino/schema"
|
||||
)
|
||||
|
||||
// readResponse 消费事件流,正文或流程结果与执行状态分别输出。
|
||||
func readResponse(events *adk.AsyncIterator[*adk.AgentEvent], onText, onStatus func(string)) (string, *adk.InterruptInfo, error) {
|
||||
var interrupted *adk.InterruptInfo
|
||||
reply := ""
|
||||
status := func(text string) {
|
||||
if onStatus != nil {
|
||||
onStatus(text)
|
||||
}
|
||||
}
|
||||
for {
|
||||
event, ok := events.Next()
|
||||
if !ok {
|
||||
return reply, interrupted, nil
|
||||
}
|
||||
if event.Err != nil {
|
||||
if !errors.Is(event.Err, ErrImageRejected) {
|
||||
status(fmt.Sprintf("%s 执行失败", event.AgentName))
|
||||
}
|
||||
return "", nil, event.Err
|
||||
}
|
||||
if event.Action != nil && event.Action.Interrupted != nil {
|
||||
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
|
||||
}
|
||||
output := event.Output.MessageOutput
|
||||
isMain := event.AgentName == mainAgentName && output.Role == schema.Assistant
|
||||
var callback func(string)
|
||||
if isMain {
|
||||
callback = onText
|
||||
}
|
||||
text, err := readText(output, callback)
|
||||
if err != nil {
|
||||
status(fmt.Sprintf("%s 执行失败", event.AgentName))
|
||||
return "", nil, err
|
||||
}
|
||||
if isMain {
|
||||
reply = text
|
||||
}
|
||||
if output.Role == schema.Tool {
|
||||
message := fmt.Sprintf("%s:%s 执行完成", event.AgentName, output.ToolName)
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func readText(output *adk.MessageVariant, onText func(string)) (string, error) {
|
||||
var text strings.Builder
|
||||
emit := func(content string) {
|
||||
text.WriteString(content)
|
||||
if onText != nil && content != "" {
|
||||
onText(content)
|
||||
}
|
||||
}
|
||||
if !output.IsStreaming {
|
||||
if output.Message != nil {
|
||||
emit(output.Message.Content)
|
||||
}
|
||||
return text.String(), nil
|
||||
}
|
||||
defer output.MessageStream.Close()
|
||||
for {
|
||||
chunk, err := output.MessageStream.Recv()
|
||||
if err == io.EOF {
|
||||
return text.String(), nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
emit(chunk.Content)
|
||||
}
|
||||
}
|
||||
@@ -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("失败或取消的任务不应写入历史")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
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"
|
||||
)
|
||||
|
||||
func TestChatForecast(t *testing.T) {
|
||||
for _, days := range []int{1, 2} {
|
||||
t.Run(fmt.Sprintf("预报%d天", days), func(t *testing.T) {
|
||||
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, days).Format(time.DateOnly)
|
||||
previous := http.DefaultTransport
|
||||
var weatherCalls atomic.Int32
|
||||
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": 39.9, "longitude": 116.4}}}
|
||||
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)
|
||||
}
|
||||
dates, codes := []string{}, []int{}
|
||||
maxTemps, minTemps, rain := []int{}, []int{}, []int{}
|
||||
for i := 1; i <= days; i++ {
|
||||
dates = append(dates, today.AddDate(0, 0, i).Format(time.DateOnly))
|
||||
codes, maxTemps, minTemps, rain = append(codes, 61), append(maxTemps, 18), append(minTemps, 8), append(rain, 70)
|
||||
}
|
||||
response = map[string]any{"daily": map[string]any{"time": dates, "weather_code": codes, "temperature_2m_max": maxTemps, "temperature_2m_min": minTemps, "precipitation_probability_max": rain}}
|
||||
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 })
|
||||
var modelCalls atomic.Int32
|
||||
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)
|
||||
}
|
||||
if !strings.Contains(request.Messages[0].Content.(string), today.Format(time.DateOnly)) || !strings.Contains(request.Messages[0].Content.(string), "Asia/Shanghai") {
|
||||
t.Error("系统消息缺少当前日期或时区")
|
||||
}
|
||||
properties := request.Tools[0].Function.Parameters["properties"].(map[string]any)
|
||||
if properties["start_date"] == nil || properties["end_date"] == nil {
|
||||
t.Error("Eino 工具定义缺少日期参数")
|
||||
}
|
||||
if modelCalls.Add(1) == 1 {
|
||||
arguments, _ := json.Marshal(model.WeatherArguments{Location: "北京", StartDate: start, EndDate: end})
|
||||
writeCompletion(w, request.Stream, "", []model.ToolCall{{ID: "forecast-1", Type: "function", Function: model.ToolFunction{Name: "get_weather", Arguments: string(arguments)}}})
|
||||
return
|
||||
}
|
||||
last := request.Messages[len(request.Messages)-1]
|
||||
var forecast model.WeatherForecast
|
||||
if last.Role != "tool" || last.ToolCallID != "forecast-1" {
|
||||
t.Errorf("工具消息不正确: %+v", last)
|
||||
} else if err := json.Unmarshal([]byte(last.Content.(string)), &forecast); err != nil || len(forecast.Days) != days || forecast.Days[0].Date != start || forecast.Days[0].Condition != "小雨" {
|
||||
t.Errorf("预报没有正确回传: %+v,%v", forecast, err)
|
||||
}
|
||||
writeCompletion(w, request.Stream, start+" 北京小雨,记得带伞。", nil)
|
||||
}))
|
||||
defer server.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
chat, err := New(ctx, config.Config{Chat: config.ModelConfig{BaseURL: server.URL, Model: "test-model"}, MaxToken: 4096})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var output strings.Builder
|
||||
if err := chat.Chat(ctx, "查询北京的预报", func(s string) { output.WriteString(s) }, nil, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if modelCalls.Load() != 2 || weatherCalls.Load() != 2 || !strings.Contains(output.String(), start) || !strings.Contains(output.String(), "小雨") {
|
||||
t.Fatalf("模型调用=%d,天气请求=%d,输出=%q", modelCalls.Load(), weatherCalls.Load(), output.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user