Files
example-eino/adk/internal/agent/response.go
T

101 lines
2.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 消费各 Agent 的事件流,子 Agent 的正文和工具结果不会混入主回复。
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)
}
}
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.AgentName == imageAgentName && !imageStarted {
status("主助手已委托 image_creator,生图 Agent 开始处理")
imageStarted = true
}
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 event.AgentName == imageAgentName && output.ToolName == "generate_image" {
var result model.ImageResult
if json.Unmarshal([]byte(text), &result) == nil && result.Path != "" {
message += ",图片:" + result.Path
}
}
status(message)
}
}
}
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)
}
}