Files
ai-agent-scaffold-go/internal/infrastructure/adk/adapter.go

573 lines
19 KiB
Go

package adk
import (
"context"
"fmt"
"strings"
"sync/atomic"
"ai-agent-scaffold-go/internal/domain/agent/model"
"ai-agent-scaffold-go/internal/domain/agent/ports"
"google.golang.org/adk/plugin"
"google.golang.org/adk/plugin/loggingplugin"
)
const maxToolCallIterations = 4
type Factory struct {
sessionCounter atomic.Uint64
plugins map[string]func() (ports.RunnerPlugin, error)
router ports.ToolRouter
}
type Agent struct {
name string
kind string
description string
instruction string
outputKey string
chatModel ports.ChatModel
router ports.ToolRouter
subAgents []ports.Agent
}
type Runner struct {
appName string
agent ports.Agent
plugins []ports.RunnerPlugin
counter *atomic.Uint64
}
func NewFactory() *Factory {
return &Factory{plugins: defaultPlugins()}
}
// UseToolRouter 注入工具路由器.
//
// 该路由器会被后续创建的所有 Agent 共享, Agent 在模型请求工具调用时通过它执行工具.
func (f *Factory) UseToolRouter(router ports.ToolRouter) {
f.router = router
}
func (f *Factory) NewLLMAgent(_ context.Context, config model.AgentConfig, chatModel ports.ChatModel) (ports.Agent, error) {
if strings.TrimSpace(config.Name) == "" {
return nil, fmt.Errorf("agent name is required")
}
if chatModel == nil {
return nil, fmt.Errorf("agent %q requires a chat model", config.Name)
}
return &Agent{
name: config.Name,
kind: "llm",
description: config.Description,
instruction: config.Instruction,
outputKey: config.OutputKey,
chatModel: chatModel,
router: f.router,
}, nil
}
func (f *Factory) NewLoopAgent(_ context.Context, config model.AgentWorkflowConfig, subAgents []ports.Agent) (ports.Agent, error) {
return newWorkflowAgent("loop", config, subAgents, f.router)
}
func (f *Factory) NewParallelAgent(_ context.Context, config model.AgentWorkflowConfig, subAgents []ports.Agent) (ports.Agent, error) {
return newWorkflowAgent("parallel", config, subAgents, f.router)
}
func (f *Factory) NewSequentialAgent(_ context.Context, config model.AgentWorkflowConfig, subAgents []ports.Agent) (ports.Agent, error) {
return newWorkflowAgent("sequential", config, subAgents, f.router)
}
func (f *Factory) NewRunner(_ context.Context, appName string, agent ports.Agent, pluginNames []string) (model.Runner, error) {
if strings.TrimSpace(appName) == "" {
return nil, fmt.Errorf("app name is required")
}
if agent == nil {
return nil, fmt.Errorf("agent is required")
}
plugins, err := f.resolvePlugins(pluginNames)
if err != nil {
return nil, err
}
return &Runner{appName: appName, agent: agent, plugins: plugins, counter: &f.sessionCounter}, nil
}
func newWorkflowAgent(kind string, config model.AgentWorkflowConfig, subAgents []ports.Agent, router ports.ToolRouter) (ports.Agent, error) {
if strings.TrimSpace(config.Name) == "" {
return nil, fmt.Errorf("%s agent name is required", kind)
}
return &Agent{
name: config.Name,
kind: kind,
description: config.Description,
subAgents: subAgents,
router: router,
}, nil
}
// Name 返回 Agent 名称, 实现 ports.Agent 接口.
func (a *Agent) Name() string {
return a.name
}
// Description 返回 Agent 描述信息, 主要用于日志和外部展示.
func (a *Agent) Description() string {
return a.description
}
// run 以空变量作用域执行 Agent.
//
// 包内普通执行入口, 调用 runWithVars 并传入空的模板变量表.
func (a *Agent) run(ctx context.Context, content model.ChatContent) (string, error) {
return a.runWithVars(ctx, content, map[string]string{})
}
// runWithVars 根据 Agent 类型分派到具体执行逻辑.
//
// vars 保存 Sequential 工作流传入的模板变量, 供 instruction 中的 {output-key} 占位符替换使用.
func (a *Agent) runWithVars(ctx context.Context, content model.ChatContent, vars map[string]string) (string, error) {
// 按 kind 分派到 LLM / 串行 / 并行 / 循环执行策略
switch a.kind {
case "llm":
return a.runLLM(ctx, content, vars)
case "sequential":
return a.runSequential(ctx, content, vars)
case "loop", "parallel":
return a.runFanOut(ctx, content, vars)
default:
return "", fmt.Errorf("agent %q has unknown kind %q", a.name, a.kind)
}
}
// stream 以流式方式执行 Agent.
//
// 仅 llm 类型支持真正的逐 token 流式输出;
// workflow 类型没有独立的模型流, 因此先完整执行, 再把最终结果一次性写入 out.
func (a *Agent) stream(ctx context.Context, content model.ChatContent, out chan<- string) error {
switch a.kind {
case "llm":
return a.streamLLM(ctx, content, out, map[string]string{})
default:
text, err := a.run(ctx, content)
if err != nil {
return err
}
if text != "" {
select {
case out <- text:
case <-ctx.Done():
return ctx.Err()
}
}
return nil
}
}
// runLLM 执行非流式 Tool-Calling Loop.
//
// 每次循环调用一次模型:
// 1. 模型未返回工具调用时, 直接返回最终文本;
// 2. 模型返回工具调用时, 先追加 assistant 消息, 再执行工具并把 tool 结果追加到消息列表;
// 3. 重复上述过程, 最多迭代 maxToolCallIterations 次.
func (a *Agent) runLLM(ctx context.Context, content model.ChatContent, vars map[string]string) (string, error) {
messages := initialMessages(applyVars(a.instruction, vars), firstText(content))
// 最多执行 maxToolCallIterations 轮 模型调用 -> 工具执行 -> 结果回灌
for iter := 0; iter < maxToolCallIterations; iter++ {
reply, err := a.chatModel.Generate(ctx, messages)
if err != nil {
return "", err
}
// 没有工具调用, 模型已给出最终答案
if len(reply.ToolCalls) == 0 {
return reply.Content, nil
}
// 追加 assistant 消息, 保留模型请求的 tool_calls
messages = append(messages, ports.ChatMessage{Role: ports.ChatRoleAssistant, Content: reply.Content, ToolCalls: reply.ToolCalls})
toolMessages, err := a.executeToolCalls(ctx, reply.ToolCalls)
if err != nil {
return "", err
}
// 把工具结果回灌到消息列表, 供下一轮模型使用
messages = append(messages, toolMessages...)
}
return "", fmt.Errorf("agent %q exceeded tool-call iteration limit %d", a.name, maxToolCallIterations)
}
// streamLLM 执行流式 Tool-Calling Loop.
//
// 与 runLLM 的区别是: 模型返回的文本增量会实时写入 out;
// 同时使用 finalText 暂存本轮完整文本, 用于在模型请求工具调用时构造 assistant 消息.
// 工具调用执行完成后结果会被追加到消息列表, 并进入下一轮模型调用, 最多迭代 maxToolCallIterations 次.
func (a *Agent) streamLLM(ctx context.Context, content model.ChatContent, out chan<- string, vars map[string]string) error {
messages := initialMessages(applyVars(a.instruction, vars), firstText(content))
// 最多执行 maxToolCallIterations 轮流式 Tool-Calling
for iter := 0; iter < maxToolCallIterations; iter++ {
events, errs := a.chatModel.Stream(ctx, messages)
// finalText 暂存本轮完整文本; toolCalls 收集工具调用; done 标记流是否正常结束
var (
finalText strings.Builder
toolCalls []ports.ChatToolCall
done bool
)
streamErr := error(nil)
// 标签用于从嵌套 select 中直接跳出读取循环
streamLoop:
for {
select {
case <-ctx.Done():
streamErr = ctx.Err()
break streamLoop
case ev, ok := <-events:
if !ok {
break streamLoop
}
if ev.Done {
done = true
}
// 文本增量: 写入完整文本并转发给下游
if ev.Delta != "" {
finalText.WriteString(ev.Delta)
select {
case out <- ev.Delta:
case <-ctx.Done():
streamErr = ctx.Err()
break streamLoop
}
}
if len(ev.ToolCalls) > 0 {
toolCalls = append(toolCalls, ev.ToolCalls...)
}
case err, ok := <-errs:
if ok && err != nil {
streamErr = err
}
break streamLoop
}
}
if streamErr != nil {
return streamErr
}
// 没有工具调用, 本轮文本就是最终答案
if len(toolCalls) == 0 {
// 缺少 Done 标记, 视为流异常关闭
if !done {
return fmt.Errorf("agent %q stream closed without completion", a.name)
}
return nil
}
// 追加 assistant 消息, 保留文本和工具调用
messages = append(messages, ports.ChatMessage{Role: ports.ChatRoleAssistant, Content: finalText.String(), ToolCalls: toolCalls})
toolMessages, err := a.executeToolCalls(ctx, toolCalls)
if err != nil {
return err
}
messages = append(messages, toolMessages...)
}
return fmt.Errorf("agent %q exceeded tool-call iteration limit %d", a.name, maxToolCallIterations)
}
// executeToolCalls 依次执行模型请求的工具调用.
//
// 每个工具通过 ToolRouter 执行, 返回结果会被转换为 role=tool 的 ChatMessage,
// 并通过 ToolCallID 与 assistant 消息中的工具调用一一对应.
func (a *Agent) executeToolCalls(ctx context.Context, calls []ports.ChatToolCall) ([]ports.ChatMessage, error) {
// 模型请求了工具但未注入路由器, 属于非法状态
if a.router == nil {
return nil, fmt.Errorf("agent %q has no tool router but model requested tool calls", a.name)
}
out := make([]ports.ChatMessage, 0, len(calls))
for _, call := range calls {
result, err := a.router.CallTool(ctx, call.Name, call.Arguments)
if err != nil {
return nil, fmt.Errorf("tool %q: %w", call.Name, err)
}
// 包装为 role=tool 的消息, 通过 ToolCallID 与 assistant 消息对应
out = append(out, ports.ChatMessage{
Role: ports.ChatRoleTool,
Content: result,
ToolCallID: call.ID,
Name: call.Name,
})
}
return out, nil
}
// runSequential 执行串行工作流.
//
// 子 Agent 按配置顺序依次执行, 每个子 Agent 的输出在存在 output-key 时写入 scope;
// 后续子 Agent 的 instruction 可以通过 {output-key} 引用前面步骤的结果.
// 返回值是最后一个子 Agent 的输出.
func (a *Agent) runSequential(ctx context.Context, content model.ChatContent, vars map[string]string) (string, error) {
// 复制变量表, 避免污染外层作用域
scope := cloneVars(vars)
// 记录最后一个子 Agent 的输出作为工作流返回值
var last string
for _, sub := range a.subAgents {
// 当前实现要求子 Agent 必须是 adk.Agent
impl, ok := sub.(*Agent)
if !ok {
return "", fmt.Errorf("sub-agent %q is not a runnable agent", sub.Name())
}
// 使用当前 scope 执行, 使 instruction 能读取已产生的变量
text, err := impl.runWithVars(ctx, content, scope)
if err != nil {
return "", err
}
last = text
// 配置了 output-key 时把输出写入变量表
if key := strings.TrimSpace(impl.outputKey); key != "" {
scope[key] = text
}
}
return last, nil
}
// runFanOut 执行并行/循环工作流的聚合逻辑.
//
// 当前实现会依次执行所有子 Agent, 并把每个子 Agent 的输出以 [AgentName] 前缀拼接返回.
// 注意: 当前 loop 和 parallel 都复用该逻辑, 并未真正实现并发或循环迭代.
func (a *Agent) runFanOut(ctx context.Context, content model.ChatContent, vars map[string]string) (string, error) {
parts := make([]string, 0, len(a.subAgents))
// 依次执行所有子 Agent (当前实现并未真正并发)
for _, sub := range a.subAgents {
// 同样要求子 Agent 必须是 adk.Agent
impl, ok := sub.(*Agent)
if !ok {
return "", fmt.Errorf("sub-agent %q is not a runnable agent", sub.Name())
}
// 所有子 Agent 共享同一份输入变量
text, err := impl.runWithVars(ctx, content, vars)
if err != nil {
return "", err
}
// 输出带 Agent 名前缀, 方便上层区分来源
parts = append(parts, fmt.Sprintf("[%s] %s", sub.Name(), text))
}
return strings.Join(parts, "\n"), nil
}
// cloneVars 复制变量表.
//
// Sequential 工作流使用副本保存本步骤的输出, 避免修改调用方传入的原始变量.
func cloneVars(vars map[string]string) map[string]string {
out := make(map[string]string, len(vars)+4)
for k, v := range vars {
out[k] = v
}
return out
}
// applyVars 将模板中的 {key} 占位符替换为 vars 中对应的值.
//
// 模板为空或变量表为空时直接返回模板; 替换使用简单的字符串匹配, 不做转义处理.
func applyVars(template string, vars map[string]string) string {
if template == "" || len(vars) == 0 {
return template
}
out := template
for k, v := range vars {
out = strings.ReplaceAll(out, "{"+k+"}", v)
}
return out
}
// initialMessages 构造一次模型调用的初始消息列表.
//
// instruction 非空时作为 system 消息; 用户输入始终作为 user 消息.
// 当前实现不保存跨轮对话历史, 每次执行都从 system + user 重新开始.
func initialMessages(instruction, userText string) []ports.ChatMessage {
messages := make([]ports.ChatMessage, 0, 2)
if strings.TrimSpace(instruction) != "" {
messages = append(messages, ports.ChatMessage{Role: ports.ChatRoleSystem, Content: instruction})
}
messages = append(messages, ports.ChatMessage{Role: ports.ChatRoleUser, Content: userText})
return messages
}
// CreateSession 根据用户 ID 和应用名生成会话 ID.
//
// 会话 ID 格式为 appName:userID:序号, 序号来自 Factory 的全局原子计数器.
func (r *Runner) CreateSession(userID string) (string, error) {
if strings.TrimSpace(userID) == "" {
return "", fmt.Errorf("user id is required")
}
// 全局原子自增, 保证所有 Runner 的会话序号不冲突
next := r.counter.Add(1)
return fmt.Sprintf("%s:%s:%d", r.appName, userID, next), nil
}
// Run 以非流式方式执行 Runner 持有的入口 Agent.
//
// 执行前先通知插件, 然后把内容委托给 Agent.run, 并把最终文本包装为 []string 返回.
func (r *Runner) Run(userID, sessionID string, content model.ChatContent) ([]string, error) {
if strings.TrimSpace(userID) == "" || strings.TrimSpace(sessionID) == "" {
return nil, fmt.Errorf("user id and session id are required")
}
if err := r.notifyPlugins(userID, sessionID, content); err != nil {
return nil, err
}
// Runner 只能运行 adk.Agent, 这里做类型断言
impl, ok := r.agent.(*Agent)
if !ok {
return nil, fmt.Errorf("runner agent %q is not runnable", r.agent.Name())
}
output, err := impl.run(context.Background(), content)
if err != nil {
return nil, err
}
if output == "" {
return []string{}, nil
}
return []string{output}, nil
}
// Stream 以流式方式执行 Runner 持有的入口 Agent.
//
// 方法在 goroutine 中执行, 返回文本输出 channel 和错误 channel;
// 调用方通过这两个 channel 消费执行过程中的增量结果.
func (r *Runner) Stream(userID, sessionID string, content model.ChatContent) (<-chan string, <-chan error) {
outputs := make(chan string, 8)
errs := make(chan error, 1)
go func() {
defer close(outputs)
defer close(errs)
if strings.TrimSpace(userID) == "" || strings.TrimSpace(sessionID) == "" {
errs <- fmt.Errorf("user id and session id are required")
return
}
if err := r.notifyPlugins(userID, sessionID, content); err != nil {
errs <- err
return
}
// Runner 只能运行 adk.Agent, 这里做类型断言
impl, ok := r.agent.(*Agent)
if !ok {
errs <- fmt.Errorf("runner agent %q is not runnable", r.agent.Name())
return
}
if err := impl.stream(context.Background(), content, outputs); err != nil {
errs <- err
}
}()
return outputs, errs
}
// notifyPlugins 按配置顺序通知所有 RunnerPlugin.
//
// 对每个插件依次触发 OnUserMessage 和 BeforeAgent 两个生命周期回调,
// 任一回调返回错误都会中止后续执行.
func (r *Runner) notifyPlugins(userID, sessionID string, content model.ChatContent) error {
for _, item := range r.plugins {
if err := item.OnUserMessage(context.Background(), r.appName, userID, sessionID, r.agent, content); err != nil {
return fmt.Errorf("plugin %q on user message: %w", item.Name(), err)
}
if err := item.BeforeAgent(context.Background(), r.appName, userID, sessionID, r.agent); err != nil {
return fmt.Errorf("plugin %q before agent: %w", item.Name(), err)
}
}
return nil
}
// firstText 返回 ChatContent 中的第一段文本.
//
// 当前模型调用主要使用文本输入, 文件与内联数据暂未参与消息构造.
func firstText(content model.ChatContent) string {
if len(content.Texts) == 0 {
return ""
}
return content.Texts[0].Message
}
// defaultPlugins 返回内置的 RunnerPlugin 工厂表.
//
// key 是 YAML 中配置的插件名, value 用于按需创建插件实例.
func defaultPlugins() map[string]func() (ports.RunnerPlugin, error) {
return map[string]func() (ports.RunnerPlugin, error){
"myTestPlugin": newMyTestPlugin,
"myLogPlugin": func() (ports.RunnerPlugin, error) {
p, err := loggingplugin.New("myLogPlugin")
if err != nil {
return nil, err
}
return adkRunnerPlugin{name: "myLogPlugin", plugin: p}, nil
},
}
}
// resolvePlugins 根据插件名列表解析并创建 RunnerPlugin 实例.
//
// 列表中不存在的插件名会直接返回错误, 保证装配阶段就能发现配置问题.
func (f *Factory) resolvePlugins(names []string) ([]ports.RunnerPlugin, error) {
if len(names) == 0 {
return nil, nil
}
plugins := make([]ports.RunnerPlugin, 0, len(names))
for _, name := range names {
pluginName := strings.TrimSpace(name)
if pluginName == "" {
continue
}
builder, ok := f.plugins[pluginName]
// 未注册的插件名在装配阶段直接报错
if !ok {
return nil, fmt.Errorf("runner plugin %q is not registered", pluginName)
}
plugin, err := builder()
if err != nil {
return nil, fmt.Errorf("create runner plugin %q: %w", pluginName, err)
}
plugins = append(plugins, plugin)
}
return plugins, nil
}
func newMyTestPlugin() (ports.RunnerPlugin, error) {
return myTestPlugin{}, nil
}
type myTestPlugin struct{}
// Name 返回插件名, 用于错误信息和日志展示.
func (myTestPlugin) Name() string {
return "myTestPlugin"
}
// OnUserMessage 在用户消息到达时打印调试信息.
func (myTestPlugin) OnUserMessage(_ context.Context, _, _, _ string, _ ports.Agent, content model.ChatContent) error {
fmt.Printf("[myTestPlugin] 用户输入信息:%s\n", firstText(content))
return nil
}
// BeforeAgent 在 Agent 开始执行前打印 Agent 名称.
func (myTestPlugin) BeforeAgent(_ context.Context, _, _, _ string, agent ports.Agent) error {
fmt.Printf("[myTestPlugin] 智能体名称:%s\n", agent.Name())
return nil
}
type adkRunnerPlugin struct {
name string
plugin *plugin.Plugin
}
// Name 返回 ADK 插件包装器的名称.
func (p adkRunnerPlugin) Name() string {
return p.name
}
// OnUserMessage 在 ADK 插件注册了用户消息回调时打印调试信息.
func (p adkRunnerPlugin) OnUserMessage(_ context.Context, _, _, _ string, _ ports.Agent, content model.ChatContent) error {
if p.plugin.OnUserMessageCallback() != nil {
fmt.Printf("[%s] USER MESSAGE RECEIVED %s\n", p.name, firstText(content))
}
return nil
}
// BeforeAgent 在 ADK 插件注册了 Agent 开始回调时打印调试信息.
func (p adkRunnerPlugin) BeforeAgent(_ context.Context, _, _, _ string, agent ports.Agent) error {
if p.plugin.BeforeAgentCallback() != nil {
fmt.Printf("[%s] AGENT STARTING %s\n", p.name, agent.Name())
}
return nil
}