aster采用灵感来自DeepAgents的三层可扩展架构,通过清晰的分层和抽象实现高度可扩展性。
┌─────────────────────────────────────────────────────────┐
│ Agent Layer │
│ ┌──────────────────────────────────────────────────┐ │
│ │ Middleware Stack │ │
│ │ ┌────────────────────────────────────────────┐ │ │
│ │ │ SummarizationMiddleware (priority: 40) │ │ │
│ │ │ - Auto summarize (>170k tokens) │ │ │
│ │ │ - Keep recent 6 messages │ │ │
│ │ └────────────────────────────────────────────┘ │ │
│ │ ┌────────────────────────────────────────────┐ │ │
│ │ │ FilesystemMiddleware (priority: 100) │ │ │
│ │ │ - Tools: [fs_*, bash_*] │ │ │
│ │ │ - Auto eviction (>20k tokens) │ │ │
│ │ └────────────────────────────────────────────┘ │ │
│ │ ┌────────────────────────────────────────────┐ │ │
│ │ │ SubAgentMiddleware (priority: 200) │ │ │
│ │ │ - Tools: [task] │ │ │
│ │ │ - Context isolation │ │ │
│ │ └────────────────────────────────────────────┘ │ │
│ │ ┌────────────────────────────────────────────┐ │ │
│ │ │ CustomMiddleware (priority: 500+) │ │ │
│ │ └────────────────────────────────────────────┘ │ │
│ └──────────────────────────────────────────────────┘ │
│ │ WrapModelCall │ WrapToolCall │
│ ▼ ▼ │
│ ┌─────────────┐ ┌──────────────┐ │
│ │ Provider │ │ Tool Executor│ │
│ │ (Stream) │ │ (Execute) │ │
│ └─────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ Backend Layer │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ StateBackend │ │ StoreBackend │ │FilesystemBE │ │
│ │ (临时内存) │ │ (持久化) │ │ (真实FS) │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ ┌──────────────────┐ │
│ │ CompositeBackend │ │
│ │ (路由组合) │ │
│ └──────────────────┘ │
└─────────────────────────────────────────────────────────┘
负责Agent的核心运行时逻辑:
提供统一的存储抽象:
中间件系统是aster的核心设计,采用洋葱模型实现功能的灵活组合。
Request → M1 → M2 → M3 → Handler → M3 → M2 → M1 → Response
↓ ↓ ↓ ↑ ↑ ↑
Before Before Before After After After
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
}
功能:自动管理上下文长度
// 启用自动总结
config := &types.AgentConfig{
Middlewares: []string{"summarization"},
}
功能:提供文件系统操作工具
Read, Write, Edit, Ls, Glob, GrepfsMiddleware := middleware.NewFilesystemMiddleware(&middleware.FilesystemMiddlewareConfig{
Backend: backend,
EnableEviction: true,
TokenLimit: 20000,
})
功能:任务委派到子Agent
tasksubagentMiddleware := middleware.NewSubAgentMiddleware(&middleware.SubAgentMiddlewareConfig{
Specs: []middleware.SubAgentSpec{
{Name: "researcher", Description: "Research expert"},
{Name: "coder", Description: "Coding expert"},
},
Factory: subagentFactory,
EnableParallel: true,
})
// 创建栈(自动按优先级排序)
stack := middleware.NewStack([]middleware.Middleware{
fsMiddleware, // priority: 100
subagentMiddleware, // priority: 200
customMiddleware, // priority: 500
})
// 获取所有工具
tools := stack.Tools()
// 执行模型调用(经过所有中间件)
response := stack.WrapModelCall(ctx, request, finalHandler)
Backend提供统一的存储接口,支持多种实现。
type BackendProtocol interface {
// 文件操作
Read(ctx, path, offset, limit) (string, error)
Write(ctx, path, content) (*WriteResult, error)
Edit(ctx, path, old, new, replaceAll) (*EditResult, error)
// 目录操作
ListInfo(ctx, path) ([]FileInfo, error)
GlobInfo(ctx, pattern, path) ([]FileInfo, error)
// 搜索
GrepRaw(ctx, pattern, path, glob) ([]GrepMatch, error)
}
| Backend | 生命周期 | 使用场景 | 特点 |
|---|---|---|---|
| StateBackend | 会话级 | 临时文件、中间结果 | 内存存储,快速 |
| StoreBackend | 跨会话 | 知识库、记忆 | 持久化,可恢复 |
| FilesystemBackend | 永久 | 工作空间文件 | 真实文件系统 |
| CompositeBackend | - | 混合存储策略 | 路由组合 |
// 内存临时存储
backend := backends.NewStateBackend()
backend.Write(ctx, "/temp.txt", "content")
// 持久化存储
storeBackend := backends.NewStoreBackend(storeImpl, "agent-id")
storeBackend.Write(ctx, "/memory.txt", "persistent data")
// 真实文件系统
fsBackend := backends.NewFilesystemBackend(sandboxFS)
fsBackend.Write(ctx, "/workspace/output.txt", "result")
// 路由策略:不同路径使用不同后端
composite := backends.NewCompositeBackend(
backends.NewStateBackend(), // 默认后端
[]backends.RouteConfig{
{Prefix: "/memories/", Backend: storeBackend},
{Prefix: "/workspace/", Backend: fsBackend},
},
)
// /memories/* → 持久化存储
composite.Write(ctx, "/memories/user_profile.json", data)
// /workspace/* → 真实文件系统
composite.Write(ctx, "/workspace/output.py", code)
// 其他路径 → 内存临时存储
composite.Write(ctx, "/temp/cache.txt", temp)
aster采用事件驱动架构,通过三个独立通道分离不同类型的事件。
| 通道 | 用途 | 典型订阅者 | 事件类型 |
|---|---|---|---|
| Progress | 实时进度、UI展示 | 前端、聊天界面 | 文本流、工具执行 |
| Control | 审批、人机交互 | 审批服务、安全网关 | 工具审批请求 |
| Monitor | 监控、审计 | 监控系统、日志平台 | 错误、性能指标 |
// 订阅Progress通道
progressCh := ag.Subscribe([]types.AgentChannel{
types.ChannelProgress,
}, nil)
for envelope := range progressCh {
switch e := envelope.Event.(type) {
case *types.ProgressTextChunkEvent:
fmt.Print(e.Delta) // 流式输出
case *types.ProgressToolStartEvent:
fmt.Printf("[Tool] %s\n", e.Call.Name)
case *types.ProgressToolEndEvent:
fmt.Printf("[Result] %v\n", e.Result)
}
}
// 只订阅特定事件类型
eventCh := ag.Subscribe(
[]types.AgentChannel{types.ChannelProgress},
&types.EventFilter{
EventTypes: []string{
"progress.text_chunk",
"progress.tool_start",
},
},
)
type Tool interface {
Name() string
Description() string
InputSchema() map[string]interface{}
Execute(ctx context.Context, input map[string]interface{}) (interface{}, error)
}
// 创建注册表
registry := tools.NewRegistry()
// 注册所有内置工具
builtin.RegisterAll(registry)
// 或选择性注册
registry.Register(builtin.NewFileSystemTool())
registry.Register(builtin.NewBashTool())
// 注册自定义工具
registry.Register(&MyCustomTool{})
Read:读取文件(支持分页)Write:写入文件Edit:精确编辑(字符串替换)Ls:列出目录Glob:Glob模式匹配Grep:正则搜索Bash:执行Bash命令todo_list:列出待办事项todo_add:添加待办todo_update:更新待办状态http_fetch:HTTP请求WebSearch:网络搜索task:任务委派type Provider interface {
// 流式API
StreamMessages(ctx, request) (<-chan StreamEvent, error)
// 非流式API
Messages(ctx, request) (*Response, error)
// 模型信息
Name() string
SupportedModels() []string
}
| Provider | 模型 | 特点 |
|---|---|---|
| Anthropic | Claude 3/4系列 | 长上下文、工具调用优秀 |
| OpenAI | GPT-4/GPT-3.5 | 生态成熟 |
| DeepSeek | DeepSeek-V2 | 性价比高 |
| GLM | ChatGLM系列 | 中文优化 |
// Anthropic
p := provider.NewAnthropicProvider(apiKey)
// OpenAI
p := provider.NewOpenAIProvider(apiKey)
// DeepSeek
p := provider.NewDeepSeekProvider(apiKey)
// 统一接口调用
stream, _ := p.StreamMessages(ctx, request)
for event := range stream {
// 处理流式事件
}
| 类型 | 使用场景 | 隔离级别 | 配置 |
|---|---|---|---|
| LocalSandbox | 开发测试 | 进程级 | 本地Docker |
| AliyunSandbox | 生产环境 | 容器级 | AgentBay |
| VolcengineSandbox | 生产环境 | 容器级 | 火山引擎 |
| MockSandbox | 单元测试 | 无隔离 | 模拟执行 |
// 本地沙箱
Sandbox: &types.SandboxConfig{
Kind: types.SandboxKindLocal,
WorkDir: "./workspace",
}
// 阿里云沙箱
Sandbox: &types.SandboxConfig{
Kind: types.SandboxKindAliyun,
WorkDir: "/workspace",
Config: map[string]interface{}{
"region": "cn-hangzhou",
"accessKey": os.Getenv("ALIYUN_AK"),
"secretKey": os.Getenv("ALIYUN_SK"),
},
}
基于Apple M1, Go 1.21的性能测试:
| 操作 | 性能 | 内存分配 | 吞吐量 |
|---|---|---|---|
| Middleware Stack | 36.21 ns/op | 96 B/op | ~27M ops/s |
| Backend Write | 257.9 ns/op | 480 B/op | ~3.8M ops/s |
| Tool Execution | < 1ms | 1-5 KB | 1000+ ops/s |
// 定义协议
type BackendProtocol interface { ... }
// 工厂函数
type BackendFactory func(ctx) (BackendProtocol, error)
// 延迟初始化
backend := factory(ctx)
type Middleware interface {
WrapModelCall(ctx, req, next) (*Response, error)
}
// 自动组合
stack.WrapModelCall(ctx, req, finalHandler)
// 订阅事件
ch := ag.Subscribe(channels, filter)
// 发布事件
ag.Emit(event)
| 特性 | DeepAgents (Python) | aster (Go) |
|---|---|---|
| Backend Protocol | ✅ 4种 | ✅ 4种 |
| Middleware栈 | ✅ 洋葱模型 | ✅ 洋葱模型 |
| 文件工具 | ✅ 6个 | ✅ 6个 |
| 自动驱逐 | ✅ | ✅ |
| 子代理 | ✅ | ✅ |
| 性能 | 中等 | 极高 |
| 内存 | 高 | 低 |
| 并发 | GIL限制 | 真正并发 |
| 类型安全 | 动态 | 静态 |