Architecture

核心 SDK 架构 (pkg/)

核心 SDK 架构 (pkg/)

设计原则: 零 HTTP 框架依赖,纯业务逻辑 最后更新: 2024年11月17日


架构概览

pkg/
├── agent/               # Agent 核心逻辑
│   ├── agent.go
│   ├── dependencies.go
│   └── workflow/
├── memory/              # 记忆系统
│   ├── semantic.go
│   └── working.go
├── session/             # Session 管理
├── store/               # 持久化
│   ├── interface.go
│   └── json.go
├── backends/            # Backend 抽象层
├── middleware/          # Middleware 系统
├── tools/               # 工具系统
├── provider/            # LLM Provider
├── router/              # 模型路由
├── sandbox/             # 沙箱
└── types/               # 类型定义

核心组件

1. Agent 类型

aster 提供三种 Agent 类型,灵感来自 DeepAgents 项目:

Basic Agent

标准的单 Agent 模式,用于执行独立任务。

config := &types.AgentConfig{
    TemplateID: "assistant",
    LLMProvider: "openai",
    LLMModel: "gpt-4",
}

ag, _ := agent.Create(ctx, config, deps)
result, _ := ag.Chat(ctx, "Hello!")

Workflow Agent

编排多个子 Agent 的工作流模式:

Agent 类型执行模式使用场景
ParallelAgent并行执行所有子 Agent多方案比较、并行数据收集
SequentialAgent顺序执行子 Agent流水线处理、多阶段任务
LoopAgent循环执行直到条件满足迭代优化、多轮对话

特点:

  • 基于 stream.Reader 的流式接口
  • 内存占用 O(1) vs 传统 O(n)
  • 支持嵌套工作流
  • 丰富的事件元数据(branch、iteration、index)

SubAgent

主从协作模式,用于任务委托和上下文隔离。


2. Middleware 系统

洋葱模型的可组合中间件架构:

Request → M1 → M2 → M3 → Handler → M3 → M2 → M1 → Response
          ↓    ↓    ↓              ↑    ↑    ↑
      Before Before Before       After After After

Middleware 接口

type Middleware interface {
    Name() string
    Priority() int  // 0-100: 系统, 100-500: 功能, 500+: 用户
    Tools() []tools.Tool

    // 双向拦截
    WrapModelCall(ctx, req, handler) (*ModelResponse, error)
    WrapToolCall(ctx, req, handler) (*ToolCallResponse, error)

    // 生命周期钩子
    OnAgentStart(ctx, agentID) error
    OnAgentStop(ctx, agentID) error
}

内置 Middleware

SummarizationMiddleware
  • 优先级: 40
  • 功能:
    • 自动监控消息历史 token 数
    • 超过阈值时自动总结旧消息 (默认 170k tokens)
    • 保留最近 N 条消息 (默认 6 条)
FilesystemMiddleware
  • 优先级: 100
  • 工具: Read, Write, Ls, Edit, Glob, Grep
  • 功能:
    • 自动大结果驱逐 (>20k tokens)
    • 系统提示词增强
SubAgentMiddleware
  • 优先级: 200
  • 工具: task
  • 功能:
    • 任务委托到子代理
    • 上下文隔离
    • 并发执行支持

3. Backend 抽象层

统一的存储接口,支持多种后端实现:

BackendProtocol 接口

type BackendProtocol interface {
    ListInfo(ctx, path) ([]FileInfo, error)
    Read(ctx, path, offset, limit) (string, error)
    Write(ctx, path, content) (*WriteResult, error)
    Edit(ctx, path, old, new, replaceAll) (*EditResult, error)
    GrepRaw(ctx, pattern, path, glob) ([]GrepMatch, error)
    GlobInfo(ctx, pattern, path) ([]FileInfo, error)
}

四种 Backend 实现

Backend用途生命周期使用场景
StateBackend内存临时存储会话级临时文件、中间结果
StoreBackend持久化存储跨会话知识库、记忆
FilesystemBackend真实文件系统永久工作空间文件
CompositeBackend路由组合-混合存储策略

使用示例

// 单一后端
backend := backends.NewStateBackend()

// 组合后端(路由)
composite := backends.NewCompositeBackend(
    backends.NewStateBackend(), // 默认
    []backends.RouteConfig{
        {Prefix: "/memories/", Backend: storeBackend},
        {Prefix: "/workspace/", Backend: fsBackend},
    },
)

4. Session Store

持久化 Agent 会话和事件历史:

存储类型用途特点
Memory开发/测试无持久化、快速
PostgreSQL生产推荐JSONB、复杂查询、全文搜索
MySQL 8.0+生产可选JSON 类型、InnoDB、高可用

功能:

  • Session 元数据管理(app_name、user_id、status)
  • Event 持久化(消息历史、工具调用、元数据)
  • 高性能查询(时间范围、分页、过滤)
  • 批量操作优化(单事务插入多个事件)

数据模型:

sessions (1) ──<─ (N) session_events
  - id, app_name, user_id, agent_id
  - status, metadata, timestamps
              └─> - id, session_id, invocation_id
                  - content, actions, metadata

工具清单

文件系统工具 (FilesystemMiddleware)

工具描述主要用途
Read读取文件内容支持分页读取
Write写入文件覆盖写入
Ls列出目录显示大小、时间
Edit精确编辑字符串替换
GlobGlob 匹配**/*.go
Grep正则搜索显示行号、上下文

网络工具

工具描述主要用途
HttpRequestHTTP/HTTPS 请求GET/POST/PUT/DELETE/PATCH/HEAD
WebSearchWeb 搜索Tavily API (general/news/finance)

子代理工具 (SubAgentMiddleware)

工具描述主要用途
task任务委托启动子代理执行隔离任务

性能指标

基于 Apple M1, Go 1.21:

操作性能内存吞吐量
Middleware Stack36.21 ns/op96 B/op~27M ops/s
Backend Write257.9 ns/op480 B/op~3.8M ops/s

设计模式

1. Protocol + Factory 模式

// 定义协议
type BackendProtocol interface { ... }

// 工厂函数
type BackendFactory func(ctx) (BackendProtocol, error)

// 延迟初始化
backend := factory(ctx)

2. Middleware 洋葱模型

type Middleware interface {
    WrapModelCall(ctx, req, next) (*Response, error)
    WrapToolCall(ctx, req, next) (*Response, error)
}

// 自动链式调用
stack := NewStack(middlewares)  // 按 Priority 排序

3. 优先级排序

type Middleware interface {
    Priority() int  // 数值越小优先级越高
}

// 0-100: 系统核心功能
// 100-500: 通用功能(文件、子代理等)
// 500-1000: 业务逻辑

扩展指南

创建自定义 Backend

type MyBackend struct {
    // 你的存储逻辑
}

func (b *MyBackend) Read(ctx, path, offset, limit) (string, error) {
    // 实现读取
}

// ... 实现其他方法

创建自定义 Middleware

type MyMiddleware struct {
    *middleware.BaseMiddleware
}

func NewMyMiddleware() *MyMiddleware {
    return &MyMiddleware{
        BaseMiddleware: middleware.NewBaseMiddleware("my-middleware", 300),
    }
}

func (m *MyMiddleware) Tools() []tools.Tool {
    return []tools.Tool{&MyTool{}}
}

func (m *MyMiddleware) WrapToolCall(ctx, req, handler) (*ToolCallResponse, error) {
    // 前置处理
    log.Printf("Before: %s", req.ToolName)

    // 调用下一层
    resp, err := handler(ctx, req)

    // 后置处理
    log.Printf("After: %v", resp.Result)

    return resp, err
}

最佳实践

1. Backend 选择

  • 临时数据: StateBackend
  • 持久数据: StoreBackend
  • 工作文件: FilesystemBackend
  • 混合场景: CompositeBackend

2. Middleware 优先级

  • 0-100: 系统核心功能
  • 100-500: 通用功能(文件、子代理等)
  • 500-1000: 业务逻辑

3. 工具命名

  • 使用动词开头: Read, Write
  • 分组前缀: fs_*, git_*, api_*

4. 错误处理

// 工具返回结构化错误
return map[string]interface{}{
    "ok":    false,
    "error": "详细错误信息",
    "recommendations": []string{
        "建议1",
        "建议2",
    },
}, nil  // 不要返回 error,让 LLM 看到错误信息

对比 DeepAgents

特性DeepAgents (Python)aster (Go)
Backend Protocol✅ 4种✅ 4种
Middleware 栈✅ 洋葱模型✅ 洋葱模型
文件工具✅ 6个✅ 6个
自动驱逐
子代理
性能中等极高 (Go)
内存 (Go)
并发GIL限制真正并发 (Goroutine)

参考资料


版本: v2.0 最后更新: 2024年11月17日