基于 Elixir/OTP 的生产级 AI Agent 框架,提供 Human-in-the-Loop 审批、子代理委托、中间件组合与 Phoenix LiveView 实时集成,支持分布式集群部署。
项目概述#
Sagents 是构建在 Elixir LangChain 之上的生产级 AI Agent 编排框架,专为需要实时交互和人机协作的场景设计。当前版本 v0.2.1,采用 Apache-2.0 许可证。
核心能力#
OTP 原生架构#
- 每个代理作为受监督的 GenServer 进程运行,具备自动故障恢复
- 通过
Sagents.Supervisor管理完整的监督树 - 支持 Registry-Based Discovery 进行进程发现
- 使用
:rest_for_one监督策略
Human-in-the-Loop (HITL)#
- 可配置的权限系统,对敏感操作(文件删除、API 调用)暂停执行并等待人工审批
- 支持三种决策类型:
approve(批准)、edit(修改参数后执行)、reject(拒绝)
SubAgents 委托#
- 将复杂任务委托给专用子代理
- 实现高效上下文管理与并行执行
- 独立的 SubAgentsDynamicSupervisor 管理子代理生命周期
中间件系统#
可扩展插件架构,实现 Sagents.Middleware behaviour 添加能力。预置中间件包括:
TodoList:任务管理,追踪多步骤工作FileSystem:虚拟文件系统(ls、read_file、write_file、edit_file、search_text、edit_lines、delete_file)HumanInTheLoop:人工审批拦截SubAgent:任务委托Summarization:token 限制接近时自动压缩对话PatchToolCalls:修复中断对话中挂起的工具调用ConversationTitle:自动生成会话标题
Phoenix LiveView 集成#
- 通过 PubSub 实时推送代理状态、消息和事件流
- Phoenix.Presence 智能资源管理,无客户端查看时自动关闭空闲代理
- 支持多 LiveView 订阅者同步
集群感知分发#
- 可选 Horde 分布式支持
- 跨节点运行代理并自动状态迁移
- 配置:
config :sagents, :distribution, :horde
状态持久化与虚拟文件系统#
- 可选 behaviour 模块保存和恢复代理会话
- 隔离的内存文件操作,支持可选持久化
- 独立文件系统作用域管理
架构设计#
Sagents.Supervisor
├── Sagents.ProcessRegistry (Registry 或 Horde.Registry)
├── Sagents.ProcessSupervisor (DynamicSupervisor 或 Horde.DynamicSupervisor)
│ └── AgentSupervisor
│ ├── AgentServer
│ └── SubAgentsDynamicSupervisor
└── FileSystemSupervisor
└── FileSystemServer
双视图会话模式#
- Agent State:LLM 思考内容,完整消息历史、todos、中间件状态
- Display Messages:用户所见,UI 友好记录,优化渲染与流式传输
安装与配置#
# mix.exs
def deps do
[{:sagents, "~> 0.2.1"}]
end
LLM 提供商配置#
支持 Anthropic (Claude)、OpenAI (GPT)、Google (Gemini),通过环境变量配置 API Key。
快速创建代理#
alias Sagents.{Agent, AgentServer, State}
alias Sagents.Middleware.{TodoList, FileSystem, HumanInTheLoop}
{:ok, agent} = Agent.new(%{
agent_id: "my-agent-1",
model: ChatAnthropic.new!(%{model: "claude-sonnet-4-5-20250929"}),
base_system_prompt: "You are a helpful coding assistant.",
middleware: [TodoList, FileSystem, {HumanInTheLoop, [interrupt_on: %{"write_file" => true, "delete_file" => true}]}]
})
{:ok, _pid} = AgentServer.start_link(
agent: agent,
initial_state: State.new!(%{messages: [Message.new_user!("Create a hello world program")]}),
pubsub: {Phoenix.PubSub, :my_app_pubsub},
inactivity_timeout: 3_600_000
)
代码生成器 CLI#
# 生成会话基础设施
mix sagents.setup MyApp.Conversations --scope MyApp.Accounts.Scope --owner-type user
# 生成 LiveView 助手
mix sagents.gen.live_helpers MyAppWeb.AgentLiveHelpers --context MyApp.Conversations
适用场景#
- 实时对话 AI 应用(流式响应、状态同步)
- 敏感操作审批流(文件操作、外部 API)
- 多代理协作系统
- 需要会话持久化的交互应用
- 分布式部署场景
不适用场景#
- 简单 CLI 工具或批处理管道(建议直接使用 LangChain)
- 非 BEAM 平台部署
依赖关系#
- 核心依赖:Elixir LangChain
- 灵感来源:LangChain Deep Agents 项目
- 可选依赖:Horde(分布式支持)