一个 FunctionAgent 既检索又写综述,prompt 会打架。AgentWorkflow 把多个 FunctionAgent 收成一个可 run 的工作流:每个 Agent 有 name、description、can_handoff_to,当前 Agent 决定把任务交给谁。这是消息交接,不是 StateGraph 的条件边。
段末注释:AgentWorkflow 在 Workflow 之上预构建多 Agent 调度;handoff = 把对话与工具权交给另一个具名 Agent。

1. 一句话定位
| 维度 | 内容 |
|---|---|
| 角色 | 知识层侧的多角色交接:谁说话、谁调哪套工具 |
| 输入 → 输出 | user_msg → 终态文本(内部多次 handoff + tool) |
| 典型调用入口 | FunctionAgent(name=, can_handoff_to=)、AgentWorkflow(agents=, root_agent=).run() |
| 与 LangChain / LangGraph | 近邻是 Subgraph / 手写 handoff;持久化会话、HITL 仍用 LangGraph |
出现背景:单 Agent 工具一多,模型乱调。拆成「检索员 / 执笔」后,用 description 让当前角色知道同事是干什么的,用 can_handoff_to 限制可交接对象,避免环形对吵失控。
2. 前置依赖与环境
1 | pip install -U llama-index-core llama-index-llms-ollama llama-index-embeddings-ollama |
- 每个 FunctionAgent 的 LLM 都要能 tool calling(handoff 也是一种工具)
runasync;多轮仍需显式Context- 本地 9B 级模型交接比单工具 round 更容易失败,先把 description 写死、temperature=0
3. 实现逻辑
1 | 1. 为每个角色建 FunctionAgent:name、description、tools、system_prompt、can_handoff_to |
字段级变形:
1 | user_msg = "根据资料写一句:实验对象是谁" |
4. 原理说明
主轴是:同一套 Workflow 运行时里切换「当前 Agent」;工具列表随角色变,而不是一个超级 tools 数组。
1 | 1. AgentWorkflow 校验恰好能解析 root_agent,且 handoff 目标 name 存在 |
FunctionAgent.name / description 出现在步骤 1。description 给其它 Agent 看,决定会不会被交接。
can_handoff_to 出现在步骤 1。列表为 name 字符串。空列表 = 不能交出去(叶子角色)。
AgentWorkflow(agents, root_agent=...) 出现在步骤 2。agents 里必须能唯一命中 root。
initial_state 出现在步骤 3。适合 report_draft 这类槽;不要把整个 Index 放进去。
单角色时 AgentWorkflow(agents=[one]) 等价于直接 FunctionAgent.run,不必叠这层。
5. 最小可运行示例
1 | pip install -U llama-index-core llama-index-llms-ollama llama-index-embeddings-ollama |
1 | import asyncio |
6. 重要配置参数
| 参数(API 名) | 类型 / 默认值 | 功能说明 | 作用与影响 | 参考起点 / 常用范围 | 配置指导 |
|---|---|---|---|---|---|
name |
str,必填语义 | Agent 稳定 ID,handoff 用 | 与 can_handoff_to 对不上则运行失败 | ASCII 短名 | 不要中文空格 |
description |
str | 给同事 Agent 的职责说明 | 写「通用助手」则乱交 | 一句话职责 + 不做的事 | 比 system_prompt 更影响选人 |
can_handoff_to |
list[str] | 允许交接的 name | 空 = 叶子;互相指向可能对吵 | 单向链先于全连通 | 先 Research→Writer 一条链 |
root_agent |
str | 第一次说话的人 | 填错则校验失败 | 有工具的检索角色 | 不要让 Writer 当 root |
tools |
list | 该角色能调的工具 | Writer 挂检索会跳过交接 | 检索工具只给 Research | 按职责拆 |
initial_state |
dict,可选 | 跨角色草稿槽 | 工具不读它则形同虚设 | 小字符串 | 显式在 tool 里 get/set |
timeout |
秒 | 整次交接+工具上限 | 对吵时靠它熔断 | 120~300 | 必设 |
7. 适用 / 不适用
| 维度 | 适用 | 不适用 |
|---|---|---|
| 任务形态 | 检索与写作职责冲突、要显式交接 | 一个 QE 一次问答 |
| 集成约束 | 模型能稳定 tool/handoff | 本地模型频繁选错人——改回单 Agent 或规则路由 |
| 工程阶段 | 原型多角色 | 审批、跨进程恢复——LangGraph |
8. 易踩坑
- 所有人 can_handoff_to 所有人:对吵到 timeout。
- Writer 也挂 paper_search:根本不交接。
- name 拼写与 can_handoff_to 不一致。
- 把 AgentWorkflow 当 HITL:没有 interrupt 语义。
小结
- 角色 = 自己的 tools + 允许交接的名字。
- root_agent 起步;description 给同事看。
- 单角色不必套 AgentWorkflow。
- 要环的可靠性与审批:知识工具留下,外壳换 LangGraph。