96 lines
2.2 KiB
Go
96 lines
2.2 KiB
Go
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 || 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" {
|
||
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)
|
||
}
|
||
}
|