chore: 为部分文件添加注释
This commit is contained in:
@@ -42,6 +42,9 @@ func NewFactory() *Factory {
|
||||
return &Factory{plugins: defaultPlugins()}
|
||||
}
|
||||
|
||||
// UseToolRouter 注入工具路由器.
|
||||
//
|
||||
// 该路由器会被后续创建的所有 Agent 共享, Agent 在模型请求工具调用时通过它执行工具.
|
||||
func (f *Factory) UseToolRouter(router ports.ToolRouter) {
|
||||
f.router = router
|
||||
}
|
||||
@@ -103,19 +106,28 @@ func newWorkflowAgent(kind string, config model.AgentWorkflowConfig, subAgents [
|
||||
}, 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)
|
||||
@@ -128,6 +140,10 @@ func (a *Agent) runWithVars(ctx context.Context, content model.ChatContent, vars
|
||||
}
|
||||
}
|
||||
|
||||
// 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":
|
||||
@@ -148,36 +164,54 @@ func (a *Agent) stream(ctx context.Context, content model.ChatContent, out chan<
|
||||
}
|
||||
}
|
||||
|
||||
// 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 {
|
||||
@@ -191,6 +225,7 @@ func (a *Agent) streamLLM(ctx context.Context, content model.ChatContent, out ch
|
||||
if ev.Done {
|
||||
done = true
|
||||
}
|
||||
// 文本增量: 写入完整文本并转发给下游
|
||||
if ev.Delta != "" {
|
||||
finalText.WriteString(ev.Delta)
|
||||
select {
|
||||
@@ -213,12 +248,15 @@ func (a *Agent) streamLLM(ctx context.Context, content model.ChatContent, out ch
|
||||
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 {
|
||||
@@ -229,7 +267,12 @@ func (a *Agent) streamLLM(ctx context.Context, content model.ChatContent, out ch
|
||||
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)
|
||||
}
|
||||
@@ -239,6 +282,7 @@ func (a *Agent) executeToolCalls(ctx context.Context, calls []ports.ChatToolCall
|
||||
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,
|
||||
@@ -249,19 +293,29 @@ func (a *Agent) executeToolCalls(ctx context.Context, calls []ports.ChatToolCall
|
||||
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
|
||||
}
|
||||
@@ -269,22 +323,33 @@ func (a *Agent) runSequential(ctx context.Context, content model.ChatContent, va
|
||||
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 {
|
||||
@@ -293,6 +358,9 @@ func cloneVars(vars map[string]string) map[string]string {
|
||||
return out
|
||||
}
|
||||
|
||||
// applyVars 将模板中的 {key} 占位符替换为 vars 中对应的值.
|
||||
//
|
||||
// 模板为空或变量表为空时直接返回模板; 替换使用简单的字符串匹配, 不做转义处理.
|
||||
func applyVars(template string, vars map[string]string) string {
|
||||
if template == "" || len(vars) == 0 {
|
||||
return template
|
||||
@@ -304,6 +372,10 @@ func applyVars(template string, vars map[string]string) string {
|
||||
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) != "" {
|
||||
@@ -313,14 +385,21 @@ func initialMessages(instruction, userText string) []ports.ChatMessage {
|
||||
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")
|
||||
@@ -328,6 +407,7 @@ func (r *Runner) Run(userID, sessionID string, content model.ChatContent) ([]str
|
||||
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())
|
||||
@@ -342,6 +422,10 @@ func (r *Runner) Run(userID, sessionID string, content model.ChatContent) ([]str
|
||||
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)
|
||||
@@ -356,6 +440,7 @@ func (r *Runner) Stream(userID, sessionID string, content model.ChatContent) (<-
|
||||
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())
|
||||
@@ -368,6 +453,10 @@ func (r *Runner) Stream(userID, sessionID string, content model.ChatContent) (<-
|
||||
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 {
|
||||
@@ -380,6 +469,9 @@ func (r *Runner) notifyPlugins(userID, sessionID string, content model.ChatConte
|
||||
return nil
|
||||
}
|
||||
|
||||
// firstText 返回 ChatContent 中的第一段文本.
|
||||
//
|
||||
// 当前模型调用主要使用文本输入, 文件与内联数据暂未参与消息构造.
|
||||
func firstText(content model.ChatContent) string {
|
||||
if len(content.Texts) == 0 {
|
||||
return ""
|
||||
@@ -387,6 +479,9 @@ func firstText(content model.ChatContent) string {
|
||||
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,
|
||||
@@ -400,6 +495,9 @@ func defaultPlugins() map[string]func() (ports.RunnerPlugin, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// resolvePlugins 根据插件名列表解析并创建 RunnerPlugin 实例.
|
||||
//
|
||||
// 列表中不存在的插件名会直接返回错误, 保证装配阶段就能发现配置问题.
|
||||
func (f *Factory) resolvePlugins(names []string) ([]ports.RunnerPlugin, error) {
|
||||
if len(names) == 0 {
|
||||
return nil, nil
|
||||
@@ -411,6 +509,7 @@ func (f *Factory) resolvePlugins(names []string) ([]ports.RunnerPlugin, error) {
|
||||
continue
|
||||
}
|
||||
builder, ok := f.plugins[pluginName]
|
||||
// 未注册的插件名在装配阶段直接报错
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("runner plugin %q is not registered", pluginName)
|
||||
}
|
||||
@@ -429,15 +528,18 @@ func newMyTestPlugin() (ports.RunnerPlugin, error) {
|
||||
|
||||
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
|
||||
@@ -448,10 +550,12 @@ type adkRunnerPlugin struct {
|
||||
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))
|
||||
@@ -459,6 +563,7 @@ func (p adkRunnerPlugin) OnUserMessage(_ context.Context, _, _, _ string, _ port
|
||||
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())
|
||||
|
||||
Reference in New Issue
Block a user