随着 LLM 工作流增长,单个 Agent 如果积累了 30 多个工具、臃肿的系统提示词和多项职责,表现会开始下降:选错工具、产生幻觉、耗尽上下文窗口。解决方式是把工作分给多个各有专长的 Agent,由“管理者”Agent、你自己的 Rust 代码,或点对点消息来协调。
你需要多 Agent 吗?#
如果工作流只涉及一个领域,工具集也较集中,例如少于 10–15 个,通常应先改善提示词和提供给模型的上下文,再考虑引入多个 Agent。这里的工具数量是原文的经验参考,不是 Rig 的限制,也不是所有模型通用的阈值。先尝试:
- 使用结构化输出减少歧义
- 改进检索,例如优化分块、使用更相关的数据集
- 收紧约束,更清楚地定义角色
以下情况适合多 Agent 系统:
- Agent 需要 20 多个工具,并开始选错工具
- 跨领域协作,例如文档撰写与产品开发
- 单靠检索无法解决上下文窗口耗尽
- 角色委派边界清楚
如果不能明确说明为什么需要多个 Agent,就保持单 Agent 的简单设计。如何衡量和改进已构建的系统,见可观测性。
主 Agent 分派任务(Manager–Worker)#
在这种模式中,主 Agent 将子任务交给子 Agent,再汇总结果。在 Rig 中,用 Agent::into_tool() 将子 Agent 包装为工具,再由主 Agent 通过 .dynamic_tool(..) 注册。
graph TD
A[User Request] --> B[Manager Agent]
B --> C{Task Planning}
C --> D[Decompose into Subtasks]
D --> E[Worker 1]
D --> F[Worker 2]
D --> G[Worker 3]
E --> K[Manager Agent<br/>Aggregation]
F --> K
G --> K
K --> M[Final Response]
style B fill:#D97E4A,color:#191F18
style E fill:#242424,color:#F6F3EC
style F fill:#242424,color:#F6F3EC
style G fill:#242424,color:#F6F3EC
style K fill:#D97E4A,color:#191F18这里 Alice 管理 Bob。Bob 被转换成工具,Alice 的模型就可以调用他:
use rig::prelude::*;
use rig::providers::openai::{self, OpenAI};
/// Manager-worker pattern with two agents, Alice (manager) and Bob (worker).
async fn manager_worker_agent() -> anyhow::Result<()> {
// Erase the model once and clone the handle for each agent.
let model = OpenAI::from_env()?.completion(openai::GPT_5_5).erase();
let bob = AgentBuilder::new(model.clone())
.name("bob")
.description("An employee who works in admin at FooBar Inc.")
.preamble(
"You are Bob, an employee in admin at FooBar Inc. Alice, your manager, \
may ask you to do things. You need to do them.",
)
.build();
let alice = AgentBuilder::new(model)
.name("alice")
.preamble("You are a manager in the admin department at FooBar Inc. You manage Bob.")
.dynamic_tool(bob.into_tool()?)
.default_max_turns(3)
.build();
let res = alice
.prompt("Ask Bob to write an email for you and let me know what he has written.")
.await?;
println!("Response: {}", res.output());
Ok(())
}该工具只接收一个 prompt 字符串参数。Alice 的模型调用它时,Rig 用该提示词运行 Bob,并继承调用方的工具上下文;将 Bob 的文本输出作为工具结果返回后,Alice 继续自己的轮次。Bob 运行失败会变成 Alice 模型可见的工具错误,而不会直接中止 Alice 的运行。
说明
into_tool() 根据工作者的名称、描述和系统提示词构建工具定义,因此应通过 AgentBuilder::name() 和 AgentBuilder::description() 同时设置名称与描述。Agent 名称会成为工具名;未命名 Agent 的工具名是 agent_tool,所以同一管理者注册两个未命名工作者会发生冲突。给管理者足够的轮次预算(default_max_turns),让它能调用工作者后再回答。
自定义工作者工具#
如果管理者应传递结构化参数,或你需要控制给工作者的提示词,可把工作者包装成自己的 Tool:
struct Translator(Agent);
#[derive(Deserialize)]
struct TranslatorArgs {
text: String,
}
impl Tool for Translator {
const NAME: &'static str = "translator";
type Args = TranslatorArgs;
type Output = String;
type Error = PromptError;
fn description(&self) -> String {
"Translate any text to English.".to_string()
}
fn parameters(&self) -> serde_json::Value {
json!({
"type": "object",
"properties": { "text": { "type": "string", "description": "Text to translate" } },
"required": ["text"]
})
}
async fn call(&self, _ctx: &mut ToolContext, args: Self::Args) -> Result<String, PromptError> {
Ok(self.0.prompt(args.text).await?.output())
}
}通过 .tool(Translator(translator_agent)) 注册到管理者。
用 Rust 编排 Agent#
管理 Agent 让模型决定谁做什么。如果步骤已经确定,直接用普通 Rust 编排更省钱、更快,也更容易测试。顺序步骤只需 .await,独立步骤可用 tokio::join! 或 futures::future::join_all 并发执行。通用模式见工作流。
use rig::prelude::*;
use rig::providers::openai::{self, OpenAI};
async fn research_and_write(topic: &str) -> anyhow::Result<String> {
let model = OpenAI::from_env()?.completion(openai::GPT_5_5).erase();
let historian = AgentBuilder::new(model.clone())
.preamble("You summarize the history of a topic in five bullet points.")
.build();
let economist = AgentBuilder::new(model.clone())
.preamble("You summarize the economics of a topic in five bullet points.")
.build();
let writer = AgentBuilder::new(model)
.preamble("You turn research notes into a short, readable article.")
.build();
// Two independent workers, run concurrently.
let (history, economics) = tokio::join!(historian.prompt(topic), economist.prompt(topic));
// One dependent step that combines their output.
let notes = format!(
"History:\n{}\n\nEconomics:\n{}",
history?.output(),
economics?.output()
);
Ok(writer.prompt(notes).await?.output())
}用 Actor 模式实现群体行为#
Rig 没有内置 swarm 原语,但可以用 Actor 模式构建:每个 Agent 运行自己的循环,通过通道接收同伴消息,也可以被外部事件触发。下面只展示 Rig 相关部分,通道与运行循环的连接使用标准 Tokio 即可。
先定义 Agent 之间交换的消息,以及持有 Rig Agent 的 Actor:
use rig::prelude::*;
use std::sync::Arc;
use tokio::sync::{mpsc, RwLock};
/// Messages exchanged between agents.
#[derive(Debug, Clone)]
enum AgentMessage {
Task(String),
Response(String, String), // (from_agent_id, content)
Trigger(String),
Shutdown,
}
/// An actor-based autonomous agent. Each holds its own Rig agent, an inbox,
/// its history, and channels to its peers.
struct AutonomousAgent {
id: String,
agent: Agent,
history: Vec<String>,
inbox: mpsc::Receiver<AgentMessage>,
peers: Arc<RwLock<Vec<mpsc::Sender<AgentMessage>>>>,
}为每个参与者创建一次 Agent,分别配置系统提示词、工具、RAG 上下文或记忆,再交给 Actor。运行循环用 tokio::select! 响应传入消息或定期自检计时器,以先触发者为准。收到 Task 时,Agent 调用模型、记录结果并广播给同伴;收到 Shutdown 时退出循环:
use tokio::time::{interval, Duration};
impl AutonomousAgent {
/// Broadcast a message to every registered peer.
async fn broadcast(&self, message: AgentMessage) {
for peer in self.peers.read().await.iter() {
let _ = peer.send(message.clone()).await;
}
}
async fn run(mut self) {
let mut tick = interval(Duration::from_secs(10));
loop {
tokio::select! {
Some(msg) = self.inbox.recv() => match msg {
AgentMessage::Shutdown => break,
AgentMessage::Task(task) => {
if let Ok(response) = self.agent.prompt(task).await {
let result = response.output();
self.history.push(result.clone());
self.broadcast(AgentMessage::Response(self.id.clone(), result)).await;
}
}
AgentMessage::Trigger(msg) => {
let _ = self.agent.prompt(msg).await;
}
AgentMessage::Response(from, content) => {
self.history.push(format!("From {from}: {content}"));
}
},
// Autonomous periodic self-check (external trigger)
_ = tick.tick() => {
// e.g. summarize progress, enqueue follow-up work, etc.
}
}
}
}
}要连接成 swarm,为每个 Agent 创建一个 mpsc::channel,把各 Agent 的 sender 注册给同伴,用 tokio::spawn 启动每个 run() future,再发送 Task 开始工作,最终用 Shutdown 消息结束。这些都是普通 Tokio 编排。
说明
生产环境的 swarm 可以考虑 ractor。它是最受欢迎的 Rust Actor 框架,在该模式上提供监督和集群支持。
另请参阅#
- Agent:配置各模式使用的专门 Agent。
- 工具:将 Agent 当作工具所依赖的
Tooltrait 和动态工具。 - 工作流:用普通 Rust 实现顺序、并行和路由模式。
- 可观测性:衡量与调试多 Agent 系统。
- 可运行示例:
agent_with_agent_tool、multi_agent、agent_orchestrator。