Go AI Agent 实战 31|手写一个完整的 Go Agent
本系列共 10 阶段,面向有 Go 后端基础的开发者,全程用 Go 手写实现。
当前进度:阶段四 Agent 核心原理 · 第 7 课(31)
上一篇:Human-in-the-loop:关键操作前的人工确认
前面几课分别实现了执行循环、步骤状态、预算控制、失败恢复和人工确认。这一课把它们组合成一个可运行的最小 Agent。
示例使用模拟 Planner 和模拟工具,重点验证控制结构。它不会调用真实模型,也不会修改真实博客数据。
一、本课学习目标
学完本课,你应该能够:
- 组合 Planner、工具注册表、任务状态和 Agent 控制循环。
- 限制轮数、工具次数和总执行时间。
- 对明确临时错误做有限重试。
- 在工具执行前检查白名单、预算和风险等级。
- 高风险操作进入
waiting_approval。 - 用批准 ID 和预算恢复已审批动作。
二、整体架构
用户任务
↓
Agent Controller
├── 读取任务状态
├── 调用 Planner
├── 校验动作
├── 检查预算
├── 执行低风险工具
├── 暂停高风险工具
└── 记录停止原因
↓
Tool Registry → 业务服务
人工审批 → 重新检查预算/状态 → 执行已批准动作
职责边界:
| 组件 | 负责 | 不负责 |
|---|---|---|
| Planner | 提出下一步 | 授权高权限操作 |
| Controller | 循环、预算、停止 | 具体业务 SQL |
| Registry | 白名单与风险分级 | 业务权限最终判断 |
| Tool | 调用业务能力 | 无限重试副作用 |
| Approval | 人工授权 | 绕过预算或版本校验 |
三、完整 Go 示例
package main
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"time"
)
var ErrTemporary = errors.New("temporary error")
type TaskStatus string
const (
TaskRunning TaskStatus = "running"
TaskWaitingApproval TaskStatus = "waiting_approval"
TaskSucceeded TaskStatus = "succeeded"
TaskFailed TaskStatus = "failed"
TaskCancelled TaskStatus = "cancelled"
)
type ActionType string
const (
ActionTool ActionType = "tool"
ActionFinal ActionType = "final"
)
type Decision struct {
Type ActionType
ToolName string
Input string
FinalText string
}
type Planner interface {
Next(ctx context.Context, history []string) (Decision, error)
}
type ScriptPlanner struct {
decisions []Decision
index int
}
func (p *ScriptPlanner) Next(
ctx context.Context,
history []string,
) (Decision, error) {
if err := ctx.Err(); err != nil {
return Decision{}, err
}
if p.index >= len(p.decisions) {
return Decision{}, errors.New("没有更多模拟决策")
}
d := p.decisions[p.index]
p.index++
return d, nil
}
type ToolRisk int
const (
RiskLow ToolRisk = iota
RiskHigh
)
type Tool struct {
Name string
Risk ToolRisk
Execute func(context.Context, string) (string, error)
}
type ToolRegistry struct {
mu sync.RWMutex
tools map[string]Tool
}
func NewToolRegistry() *ToolRegistry {
return &ToolRegistry{tools: make(map[string]Tool)}
}
func (r *ToolRegistry) Register(tool Tool) error {
if strings.TrimSpace(tool.Name) == "" || tool.Execute == nil {
return errors.New("工具定义无效")
}
r.mu.Lock()
defer r.mu.Unlock()
if _, exists := r.tools[tool.Name]; exists {
return errors.New("工具名称重复")
}
r.tools[tool.Name] = tool
return nil
}
func (r *ToolRegistry) Get(name string) (Tool, bool) {
r.mu.RLock()
defer r.mu.RUnlock()
tool, ok := r.tools[name]
return tool, ok
}
type AgentConfig struct {
MaxRounds int
MaxToolCalls int
MaxToolAttempts int
TotalTimeout time.Duration
RetryDelay time.Duration
}
type PendingApproval struct {
ID string
Tool Tool
Input string
}
type Task struct {
ID string
Goal string
Status TaskStatus
StopReason string
History []string
Answer string
Error string
Rounds int
ToolCalls int
PendingApproval *PendingApproval
}
type Agent struct {
Planner Planner
Tools *ToolRegistry
Config AgentConfig
}
func (a *Agent) Run(parent context.Context, task *Task) {
if task == nil || a.Planner == nil || a.Tools == nil {
return
}
if a.Config.MaxRounds <= 0 ||
a.Config.MaxToolCalls < 0 ||
a.Config.MaxToolAttempts <= 0 ||
a.Config.TotalTimeout <= 0 ||
a.Config.RetryDelay < 0 {
task.Status = TaskFailed
task.StopReason = "invalid_config"
task.Error = "Agent 配置无效"
return
}
ctx, cancel := context.WithTimeout(parent, a.Config.TotalTimeout)
defer cancel()
task.Status = TaskRunning
task.History = append(task.History, "任务开始:"+task.Goal)
for round := 1; round <= a.Config.MaxRounds; round++ {
if err := ctx.Err(); err != nil {
setContextStop(parent, ctx, task)
return
}
task.Rounds = round
decision, err := a.Planner.Next(ctx, task.History)
if err != nil {
task.Status = TaskFailed
task.StopReason = "planner_error"
task.Error = err.Error()
return
}
switch decision.Type {
case ActionFinal:
if strings.TrimSpace(decision.FinalText) == "" {
task.Status = TaskFailed
task.StopReason = "invalid_action"
task.Error = "最终回答为空"
return
}
task.Status = TaskSucceeded
task.StopReason = "final_answer"
task.Answer = decision.FinalText
task.History = append(task.History, "生成最终回答")
return
case ActionTool:
if task.ToolCalls >= a.Config.MaxToolCalls {
task.Status = TaskFailed
task.StopReason = "max_tool_calls"
task.Error = "工具调用预算耗尽"
return
}
tool, ok := a.Tools.Get(decision.ToolName)
if !ok {
task.Status = TaskFailed
task.StopReason = "tool_error"
task.Error = "工具不存在"
return
}
if tool.Risk == RiskHigh {
task.Status = TaskWaitingApproval
task.StopReason = "waiting_approval"
task.PendingApproval = &PendingApproval{
ID: "approval-" + task.ID,
Tool: tool,
Input: decision.Input,
}
task.History = append(
task.History,
"等待确认工具:"+tool.Name,
)
return
}
output, err := a.executeWithRetry(ctx, tool, decision.Input)
task.ToolCalls++
if err != nil {
task.Status = TaskFailed
task.StopReason = "tool_error"
task.Error = err.Error()
return
}
task.History = append(
task.History,
fmt.Sprintf("工具 %s 返回:%s", tool.Name, output),
)
default:
task.Status = TaskFailed
task.StopReason = "invalid_action"
task.Error = "未知动作类型"
return
}
}
task.Status = TaskFailed
task.StopReason = "max_rounds"
task.Error = "模型轮数耗尽"
}
func (a *Agent) executeWithRetry(
ctx context.Context,
tool Tool,
input string,
) (string, error) {
var lastErr error
for attempt := 1; attempt <= a.Config.MaxToolAttempts; attempt++ {
if err := ctx.Err(); err != nil {
return "", err
}
output, err := tool.Execute(ctx, input)
if err == nil {
return output, nil
}
lastErr = err
if !errors.Is(err, ErrTemporary) ||
attempt == a.Config.MaxToolAttempts {
break
}
timer := time.NewTimer(a.Config.RetryDelay)
select {
case <-ctx.Done():
if !timer.Stop() {
select {
case <-timer.C:
default:
}
}
return "", ctx.Err()
case <-timer.C:
}
}
return "", fmt.Errorf(
"工具 %s 执行失败: %w",
tool.Name,
lastErr,
)
}
func (a *Agent) Approve(
parent context.Context,
task *Task,
approvalID string,
approved bool,
) error {
if task == nil ||
task.Status != TaskWaitingApproval ||
task.PendingApproval == nil {
return errors.New("任务当前不接受审批")
}
if task.PendingApproval.ID != approvalID {
return errors.New("审批 ID 不匹配")
}
if !approved {
task.Status = TaskCancelled
task.StopReason = "rejected"
task.PendingApproval = nil
return nil
}
if task.ToolCalls >= a.Config.MaxToolCalls {
task.Status = TaskFailed
task.StopReason = "max_tool_calls"
task.Error = "审批后工具预算不足"
return errors.New(task.Error)
}
ctx, cancel := context.WithTimeout(parent, a.Config.TotalTimeout)
defer cancel()
pending := task.PendingApproval
output, err := a.executeWithRetry(ctx, pending.Tool, pending.Input)
task.ToolCalls++
if err != nil {
task.Status = TaskFailed
task.StopReason = "tool_error"
task.Error = err.Error()
task.PendingApproval = nil
return err
}
task.Status = TaskSucceeded
task.StopReason = "approved_action_succeeded"
task.Answer = output
task.PendingApproval = nil
task.History = append(
task.History,
"审批通过:"+pending.Tool.Name+" 返回 "+output,
)
return nil
}
func setContextStop(
parent context.Context,
ctx context.Context,
task *Task,
) {
task.Status = TaskCancelled
if parent.Err() != nil {
task.StopReason = "cancelled"
task.Error = "调用方取消"
return
}
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
task.StopReason = "timeout"
task.Error = "任务超时"
return
}
task.StopReason = "cancelled"
task.Error = "任务取消"
}
func buildRegistry() *ToolRegistry {
registry := NewToolRegistry()
_ = registry.Register(Tool{
Name: "query_articles",
Risk: RiskLow,
Execute: func(ctx context.Context, input string) (string, error) {
return "找到文章 101 和 102", nil
},
})
_ = registry.Register(Tool{
Name: "publish_article",
Risk: RiskHigh,
Execute: func(ctx context.Context, input string) (string, error) {
return "已发布文章 " + input, nil
},
})
return registry
}
func defaultConfig() AgentConfig {
return AgentConfig{
MaxRounds: 5,
MaxToolCalls: 3,
MaxToolAttempts: 2,
TotalTimeout: 2 * time.Second,
RetryDelay: 20 * time.Millisecond,
}
}
func main() {
registry := buildRegistry()
analysisTask := &Task{
ID: "task-analysis",
Goal: "查询文章并回答",
}
analysisAgent := &Agent{
Planner: &ScriptPlanner{decisions: []Decision{
{ToolName: "query_articles", Input: "Go", Type: ActionTool},
{Type: ActionFinal, FinalText: "找到了相关文章。"},
}},
Tools: registry,
Config: defaultConfig(),
}
analysisAgent.Run(context.Background(), analysisTask)
fmt.Println("分析任务:", analysisTask.Status, analysisTask.Answer)
publishTask := &Task{
ID: "task-publish",
Goal: "发布文章 101",
}
publishAgent := &Agent{
Planner: &ScriptPlanner{decisions: []Decision{
{ToolName: "publish_article", Input: "101", Type: ActionTool},
}},
Tools: registry,
Config: defaultConfig(),
}
publishAgent.Run(context.Background(), publishTask)
fmt.Println(
"审批前:",
publishTask.Status,
publishTask.PendingApproval.Tool.Name,
)
err := publishAgent.Approve(
context.Background(),
publishTask,
publishTask.PendingApproval.ID,
true,
)
if err != nil {
fmt.Println("审批失败:", err)
return
}
fmt.Println("审批后:", publishTask.Status, publishTask.Answer)
}
运行:
go mod init agent-lesson-31
go run .
预期:
- 分析任务自动调用低风险查询工具并完成。
- 发布任务停在
waiting_approval。 - 批准后执行保存的发布工具并成功。
四、这个 Agent 的关键边界
1. Planner 不直接执行工具
模拟 Planner 返回工具名称与输入,Agent 仍然检查白名单、预算和风险等级。
接入真实模型时,可以把 Planner 替换成模型适配器,把 Tool Calling 响应转换为 Decision,Controller 不必重写。
2. 预算在动作之前检查
即使批准了发布动作,预算不足也不能执行。人工授权不自动增加工具、时间或 Token 额度。
3. 重试只处理明确临时错误
executeWithRetry 只对 ErrTemporary 重试。生产工具必须把底层错误映射成可靠分类。
写操作结果未知时不能直接重试。
4. 审批绑定保存的动作
PendingApproval 保存工具与输入。批准后执行这份快照,不重新接受模型临时生成的新参数。
真实系统还需要审批人身份、权限检查、资源版本、防重复提交和持久化。
五、距离生产环境还缺什么
| 当前实现 | 生产环境需要 |
|---|---|
| 脚本 Planner | 真实模型适配与工具调用解析 |
| 内存 Task | MySQL/Redis 持久化与锁 |
| 模拟工具 | 真实业务服务、权限和审计 |
| 简单风险枚举 | 操作级授权策略 |
| 固定重试延迟 | 退避、抖动、Retry-After |
| 内存审批 | 审批人身份、有效期与幂等 |
| 简单历史 | 结构化日志、Trace 与指标 |
| 无 Token 统计 | Token、费用和上下文预算 |
这一阶段的目标是理解控制逻辑,而不是一次完成生产级框架。
六、第四阶段总结
第四阶段完成了 Agent 核心控制链:
- Chat、Workflow、Agent 解决不同层次的问题。
- Observe、Think、Act 需要显式任务状态。
- 计划和步骤必须成为可检查的数据。
- 完成条件由程序验证,不能只听模型声明。
- 轮数、工具、时间和 Token 是不同预算。
- 只对安全可恢复错误做有限重试。
- 高风险动作必须暂停、审批、复检后执行。
下一阶段进入 Eino。我们会把这里理解的模型、组件、工作流、状态与 Agent 控制映射到框架的官方抽象中,并比较手写程序和框架实现的职责变化。
七、课后练习
练习 1:预算耗尽后审批
用户批准了发布操作,但工具预算已耗尽,应该执行吗?
参考答案:不应该。审批只授权具体操作,不能绕过预算。应记录明确停止原因,由业务决定新任务或人工处理。
练习 2:能否直接重试发布
发布工具超时后能否直接再次执行?
参考答案:不能。文章可能已经发布成功,应先查询文章状态或使用幂等键/唯一约束,再决定是否继续。
练习 3:为什么替换 Planner 不改 Controller
参考答案:Controller 依赖
Planner接口,只关心下一步决策及工具参数。真实模型适配器可以在内部处理请求、Tool Calling 和响应结构,只要输出统一Decision。
下一篇:Go AI Agent 实战 32|Eino 框架整体架构与核心抽象
专栏:Go 开发者学 AI Agent:从大模型到工程落地
更多推荐



所有评论(0)