refactor: replace image sub-agent with direct tool calling
This commit is contained in:
1 parent
975352c7d6
commit
fd3dcbe104
11 files changed
+108
-180
No files matched your search
@@ -8,6 +8,7 @@ import (
|
||||
"example.com/ueino/adk/internal/config"
|
||||
"example.com/ueino/internal/opt"
|
||||
"example.com/ueino/pkg/memory"
|
||||
"example.com/ueino/pkg/provider"
|
||||
"example.com/ueino/pkg/tool"
|
||||
|
||||
"github.com/cloudwego/eino-ext/components/model/openai"
|
||||
@@ -18,7 +19,6 @@ import (
|
||||
)
|
||||
|
||||
const mainAgentName = "terminal_chat"
|
||||
const imageAgentName = "image_creator"
|
||||
|
||||
// Agent 管理主助手的执行和会话历史。
|
||||
type Agent struct {
|
||||
@@ -37,18 +37,15 @@ func New(ctx context.Context, cfg config.Config) (*Agent, error) {
|
||||
instruction := opt.SYSTEM_PROMPT
|
||||
|
||||
if cfg.Image.Model != "" {
|
||||
imageAgent, err := newImageAgent(ctx, cfg, chat)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tools = append(tools, adk.NewAgentTool(ctx, imageAgent))
|
||||
instruction += imageDelegationPrompt
|
||||
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
|
||||
}
|
||||
|
||||
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}, EmitInternalEvents: true},
|
||||
ToolsConfig: adk.ToolsConfig{ToolsNodeConfig: compose.ToolsNodeConfig{Tools: tools}},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
|
||||
@@ -100,12 +100,12 @@ func TestDefaultImageCapability(t *testing.T) {
|
||||
}
|
||||
hasImage := false
|
||||
for _, tool := range request.Tools {
|
||||
if tool.Function.Name == imageAgentName {
|
||||
if tool.Function.Name == "generate_image" {
|
||||
hasImage = true
|
||||
}
|
||||
}
|
||||
if hasImage != enabled {
|
||||
t.Errorf("生图 Agent 注册状态 = %v,期望 %v", hasImage, enabled)
|
||||
t.Errorf("生图工具 注册状态 = %v,期望 %v", hasImage, enabled)
|
||||
}
|
||||
if enabled && !strings.Contains(request.Messages[0].Content.(string), "用户只询问能否生图") {
|
||||
t.Error("应区分能力问答与实际生图请求")
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"example.com/ueino/adk/internal/config"
|
||||
"example.com/ueino/internal/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"
|
||||
)
|
||||
|
||||
func newImageAgent(ctx context.Context, cfg config.Config, chat *openai.ChatModel) (*adk.ChatModelAgent, error) {
|
||||
image := provider.NewImage(cfg.Image.BaseURL, cfg.Image.Model, cfg.Image.APIKey, cfg.Image.OutputDir)
|
||||
return adk.NewChatModelAgent(ctx, &adk.ChatModelAgentConfig{
|
||||
Name: imageAgentName,
|
||||
Description: "负责图片创作:把用户需求整理为构图、风格和完整提示词,调用生图工具,返回实际生成的图片路径及简短说明。委托时必须提供完整需求和相关约束。",
|
||||
Instruction: imageCreationPrompt,
|
||||
Model: chat,
|
||||
MaxIterations: opt.MAX_TOOL_ROUND,
|
||||
ToolsConfig: adk.ToolsConfig{ToolsNodeConfig: compose.ToolsNodeConfig{Tools: []einotool.BaseTool{&confirmedImage{InvokableTool: tool.NewImage(image)}}}},
|
||||
})
|
||||
}
|
||||
@@ -19,8 +19,8 @@ import (
|
||||
"example.com/ueino/pkg/model"
|
||||
)
|
||||
|
||||
// 主助手和子 Agent 共用聊天模型,通过各自的工具列表区分请求。
|
||||
func TestImageDelegation(t *testing.T) {
|
||||
// 主助手直接调用生图工具,确认前不能请求图片服务。
|
||||
func TestImageTool(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
failImage bool
|
||||
@@ -39,7 +39,7 @@ func TestImageDelegation(t *testing.T) {
|
||||
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, subCalls, mainCalls atomic.Int32
|
||||
var imageCalls, mainCalls atomic.Int32
|
||||
var savedPath atomic.Value
|
||||
images := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
imageCalls.Add(1)
|
||||
@@ -57,54 +57,17 @@ func TestImageDelegation(t *testing.T) {
|
||||
json.NewEncoder(w).Encode(model.ImageGenerationResponse{Data: []model.ImageGenerationData{{Base64: pngBase64}}})
|
||||
}))
|
||||
defer images.Close()
|
||||
handleSub := func(w http.ResponseWriter, r *http.Request, request model.ChatCompletionRequest) {
|
||||
if r.URL.Path != "/v1/chat/completions" || r.Header.Get("Authorization") != "Bearer main-key" || request.Model != "main-model" || len(request.Tools) != 1 || request.Tools[0].Function.Name != "generate_image" {
|
||||
t.Errorf("子 Agent 请求不正确: %+v", request)
|
||||
}
|
||||
if subCalls.Add(1) == 1 {
|
||||
if len(request.Messages) != 2 || request.Messages[1].Content != "制作一张程序员活动海报,简洁风格" {
|
||||
t.Errorf("应只接收完整委托任务: %+v", request.Messages)
|
||||
}
|
||||
writeCompletion(w, request.Stream, "子 Agent 内部文字", []model.ToolCall{{ID: "generate-1", Type: "function", Function: model.ToolFunction{Name: "generate_image", Arguments: `{"prompt":"专业构图的程序员活动海报"}`}}})
|
||||
return
|
||||
}
|
||||
if len(request.Messages) != 4 {
|
||||
t.Errorf("子 Agent 续接消息 = %+v", request.Messages)
|
||||
http.Error(w, "消息异常", 400)
|
||||
return
|
||||
}
|
||||
last := request.Messages[3]
|
||||
var result model.ImageResult
|
||||
if last.Role != "tool" || last.ToolCallID != "generate-1" {
|
||||
t.Errorf("子 Agent 工具结果 = %+v", last)
|
||||
}
|
||||
if err := json.Unmarshal([]byte(last.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, "子 Agent 图片说明:"+result.Path, nil)
|
||||
}
|
||||
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 len(request.Tools) == 1 && request.Tools[0].Function.Name == "generate_image" {
|
||||
handleSub(w, r, request)
|
||||
return
|
||||
}
|
||||
|
||||
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 != "image_creator" {
|
||||
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" {
|
||||
t.Errorf("主 Agent 请求不正确: %+v", request)
|
||||
}
|
||||
n := mainCalls.Add(1)
|
||||
if n == 1 {
|
||||
writeCompletion(w, request.Stream, "", []model.ToolCall{{ID: "delegate-1", Type: "function", Function: model.ToolFunction{Name: "image_creator", Arguments: `{"request":"制作一张程序员活动海报,简洁风格"}`}}})
|
||||
writeCompletion(w, request.Stream, "", []model.ToolCall{{ID: "generate-1", Type: "function", Function: model.ToolFunction{Name: "generate_image", Arguments: `{"prompt":"专业构图的程序员活动海报"}`}}})
|
||||
return
|
||||
}
|
||||
if failed {
|
||||
@@ -115,9 +78,19 @@ func TestImageDelegation(t *testing.T) {
|
||||
return
|
||||
}
|
||||
if n == 2 {
|
||||
if len(request.Messages) != 4 || request.Messages[3].Role != "tool" || request.Messages[3].ToolCallID != "delegate-1" || !strings.Contains(request.Messages[3].Content.(string), "子 Agent 图片说明:") {
|
||||
t.Errorf("主 Agent 没有接到子 Agent 结果: %+v", request.Messages)
|
||||
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
|
||||
}
|
||||
@@ -146,7 +119,7 @@ func TestImageDelegation(t *testing.T) {
|
||||
if imageCalls.Load() != 0 || prompt != "专业构图的程序员活动海报" {
|
||||
t.Errorf("确认前不能调用图片接口,提示词 = %q", prompt)
|
||||
}
|
||||
if mainCalls.Load() != 1 || subCalls.Load() != 1 {
|
||||
if mainCalls.Load() != 1 {
|
||||
t.Error("恢复不应重新规划")
|
||||
}
|
||||
if len(chat.memory.LoadHistory()) != 0 {
|
||||
@@ -191,9 +164,9 @@ func TestImageDelegation(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if output.String() != "最终回复:"+savedPath.Load().(string) {
|
||||
t.Fatalf("子 Agent 内容不应进入正文: %q", output.String())
|
||||
t.Fatalf("工具结果不应直接进入正文: %q", output.String())
|
||||
}
|
||||
if !strings.Contains(strings.Join(statuses, "\n"), "generate_image") || !strings.Contains(strings.Join(statuses, "\n"), "image_creator") {
|
||||
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 {
|
||||
@@ -205,9 +178,9 @@ func TestImageDelegation(t *testing.T) {
|
||||
if err := chat.Chat(nextCtx, "继续", nil, nil, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expectedSub, expectedMain := int32(2), int32(3)
|
||||
expectedMain := int32(3)
|
||||
if failed {
|
||||
expectedSub, expectedMain = 1, 2
|
||||
expectedMain = 2
|
||||
}
|
||||
expectedImages := int32(1)
|
||||
if tt.reject || tt.confirmError != nil || tt.noConfirm || tt.cancelConfirm {
|
||||
@@ -216,8 +189,8 @@ func TestImageDelegation(t *testing.T) {
|
||||
if len(chat.checkpoints.data) != 0 {
|
||||
t.Fatal("轮次结束应清理 checkpoint")
|
||||
}
|
||||
if imageCalls.Load() != expectedImages || subCalls.Load() != expectedSub || mainCalls.Load() != expectedMain {
|
||||
t.Fatalf("调用次数:图片 %d,子模型 %d,主模型 %d", imageCalls.Load(), subCalls.Load(), mainCalls.Load())
|
||||
if imageCalls.Load() != expectedImages || mainCalls.Load() != expectedMain {
|
||||
t.Fatalf("调用次数:图片 %d,模型 %d", imageCalls.Load(), mainCalls.Load())
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -245,7 +218,7 @@ func writeCompletion(w http.ResponseWriter, stream bool, text string, calls []mo
|
||||
}
|
||||
}
|
||||
|
||||
func TestImageAgentCancellation(t *testing.T) {
|
||||
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
|
||||
@@ -261,12 +234,7 @@ func TestImageAgentCancellation(t *testing.T) {
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if len(request.Tools) == 1 && request.Tools[0].Function.Name == "generate_image" {
|
||||
writeCompletion(w, request.Stream, "", []model.ToolCall{{ID: "generate-1", Type: "function", Function: model.ToolFunction{Name: "generate_image", Arguments: `{"prompt":"画猫"}`}}})
|
||||
return
|
||||
}
|
||||
|
||||
writeCompletion(w, request.Stream, "", []model.ToolCall{{ID: "delegate-1", Type: "function", Function: model.ToolFunction{Name: "image_creator", Arguments: `{"request":"画猫"}`}}})
|
||||
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()
|
||||
@@ -296,7 +264,7 @@ func TestImageAgentCancellation(t *testing.T) {
|
||||
t.Fatalf("取消错误 = %v", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("取消未传递到子 Agent")
|
||||
t.Fatal("取消未传递到生图工具")
|
||||
}
|
||||
if len(chat.memory.LoadHistory()) != 0 {
|
||||
t.Fatal("取消的任务不应进入记忆")
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
package agent
|
||||
|
||||
const imageDelegationPrompt = `
|
||||
你可以通过 image_creator 生成图片。用户只询问能否生图或有哪些能力时,说明支持图片创作,并请用户提供画面需求,不调用工具。
|
||||
用户明确要求创作图片时,委托 image_creator,并将当前对话中相关的需求和约束整理成完整任务。不要把普通图片知识问答当成生图任务。
|
||||
生成成功后,准确保留返回的本地图片路径并简短回复;工具或子 Agent 失败时如实说明,不编造成功结果或文件路径。`
|
||||
|
||||
const imageCreationPrompt = `你是图片创作助手,只负责根据收到的任务生成图片。
|
||||
理解用户的主体、用途及约束,补充合理的构图和风格,整理为完整的创作提示词。没有指定风格时使用合理默认值,不进行多轮追问。
|
||||
调用 generate_image 生成一张图片,每个任务只调用一次,不自行重试。工具成功后,准确返回其实际图片路径及简短说明。失败时如实说明,不编造文件路径。`
|
||||
const imagePrompt = `
|
||||
你可以通过 generate_image 工具生成图片。用户只询问能否生图或有哪些能力时,说明支持图片创作,并请用户提供画面需求,不调用工具。
|
||||
用户明确要求创作图片时,结合当前对话中的需求和约束,整理包含主体、构图、风格的完整提示词后调用 generate_image。未指定风格时使用合理默认值,不进行多轮追问。
|
||||
每个任务只生成一张图片,不自行重试。工具成功后准确保留实际图片路径并简短回复;失败时如实说明,不编造成功结果或文件路径。`
|
||||
@@ -13,11 +13,10 @@ import (
|
||||
"github.com/cloudwego/eino/schema"
|
||||
)
|
||||
|
||||
// readResponse 消费各 Agent 的事件流,子 Agent 的正文和工具结果不会混入主回复。
|
||||
// readResponse 消费事件流,主助手正文和工具执行状态分别输出。
|
||||
func readResponse(events *adk.AsyncIterator[*adk.AgentEvent], onText, onStatus func(string)) (string, *adk.InterruptInfo, error) {
|
||||
var interrupted *adk.InterruptInfo
|
||||
reply := ""
|
||||
imageStarted := false
|
||||
status := func(text string) {
|
||||
if onStatus != nil {
|
||||
onStatus(text)
|
||||
@@ -38,10 +37,6 @@ func readResponse(events *adk.AsyncIterator[*adk.AgentEvent], onText, onStatus f
|
||||
interrupted = event.Action.Interrupted
|
||||
continue
|
||||
}
|
||||
if event.AgentName == imageAgentName && !imageStarted {
|
||||
status("主助手已委托 image_creator,生图 Agent 开始处理")
|
||||
imageStarted = true
|
||||
}
|
||||
if event.Output == nil || event.Output.MessageOutput == nil {
|
||||
continue
|
||||
}
|
||||
@@ -61,7 +56,7 @@ 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 event.AgentName == imageAgentName && output.ToolName == "generate_image" {
|
||||
if output.ToolName == "generate_image" {
|
||||
var result model.ImageResult
|
||||
if json.Unmarshal([]byte(text), &result) == nil && result.Path != "" {
|
||||
message += ",图片:" + result.Path
|
||||
|
||||
Reference in new issue
Block a user