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,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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user