01_quickstart/02_respond_directly_router_team.py
01_quickstart/02_respond_directly_router_team.py
Status: PASS
Description: Executed .venvs/demo/bin/python cookbook/03_teams/01_quickstart/02_respond_directly_router_team.py.
Result: Executed successfully.
- `###` 后为示例文件相对路径(相对 `cookbook/03_teams/`);
- `Status` 为 `PASS` 或 `FAIL`;
- `Description` 说明执行方式;FAIL 时标注 `Validation issue: style` 或 `Validation issue: runtime`;
- `Result` 给出运行结果;失败时附带完整 Traceback。
以 [01_quickstart/05_team_history.py](https://gitcode.com/GitHub_Trending/ag/agno/blob/a330bd5d33fb989df1c9847b99ced954d79950f1/cookbook/03_teams/01_quickstart/05_team_history.py?utm_source=gitcode_repo_files) 为例,其失败记录完整呈现了 API 变更导致的运行时错误:
TypeError: Team.init() got an unexpected keyword argument 'pass_user_input_to_members'
这说明该示例编写时所依赖的 `Team` 构造参数(`pass_user_input_to_members`)在当前仓库版本的 [libs/agno/agno/team/team.py](https://gitcode.com/GitHub_Trending/ag/agno/blob/a330bd5d33fb989df1c9847b99ced954d79950f1/libs/agno/agno/team/team.py?utm_source=gitcode_repo_files) 中已被移除或改名。对比当前示例源码([05_team_history.py](https://gitcode.com/GitHub_Trending/ag/agno/blob/a330bd5d33fb989df1c9847b99ced954d79950f1/cookbook/03_teams/01_quickstart/05_team_history.py?utm_source=gitcode_repo_files#L33-L48))可见,现行参数为 `respond_directly=True`、`determine_input_for_members=False`、`add_team_history_to_members=True` —— 日志记录与示例源码形成了"历史版本 vs 当前版本"的对照证据。
## 四、团队执行模式(TeamMode)源码解析
TEST_LOG 中 `02_modes/` 目录下的示例按 `broadcast`、`coordinate`、`route`、`tasks` 四个子目录组织,这正是 `TeamMode` 枚举定义的四种执行模式。查看 [libs/agno/agno/team/mode.py](https://gitcode.com/GitHub_Trending/ag/agno/blob/a330bd5d33fb989df1c9847b99ced954d79950f1/libs/agno/agno/team/mode.py?utm_source=gitcode_repo_files#L6-L25) 源码:
```python
class TeamMode(str, Enum):
"""Execution mode for a Team.
Controls how the team leader coordinates work with member agents.
"""
coordinate = "coordinate"
"""Default supervisor pattern. Leader picks members, crafts tasks, synthesizes responses."""
route = "route"
"""Router pattern. Leader routes to a specialist and returns the member's response directly."""
broadcast = "broadcast"
"""Broadcast pattern. Leader delegates the same task to every member.
``arun`` runs the members concurrently; ``run`` runs them in sequence."""
tasks = "tasks"
"""Autonomous task-based execution. Leader decomposes goals into a shared task list,
delegates tasks to members, and loops until all work is complete."""
四种模式的核心语义:
- coordinate(默认):经典 supervisor 模式,leader 挑选成员、构造任务、综合各成员响应后统一输出;
- route:路由模式,leader 将请求转发给最合适的专家成员,并直接返回该成员的响应;
- broadcast:广播模式,leader 将同一任务分发给所有成员;
arun(异步)并发执行,run(同步)串行执行; - tasks:自主任务模式,leader 将目标分解为共享任务列表,逐项委派给成员并循环直至全部完成。
TEST_LOG 的验证结果印证了这些模式的代码路径均可正常执行:01_quickstart/broadcast_mode.py、01_quickstart/task_mode.py、01_quickstart/nested_teams.py 均标记 PASS(02_modes/ 下 16 个专项示例则全部因风格校验失败而标记 FAIL,但 Run: completed 表明运行层面是完成的)。
五、Quickstart 核心示例深度解读
01_quickstart/ 是 TEST_LOG 中验证最密集的目录(12 个示例,10 个 PASS)。下面结合示例源码逐类说明。
5.1 基础协调:01_basic_coordination.py
01_basic_coordination.py 演示最简双成员团队:Planner(规划任务、拆分步骤)与 Writer(根据讨论撰写摘要)共同协作。团队配置要点:
team = Team(
model=OpenAIResponses(id="gpt-5-mini"),
name="Planning Team",
members=[planner, writer],
instructions=[
"Coordinate with the two members to answer the user question.",
"First plan the response, then generate a clear final summary.",
],
markdown=True,
show_members_responses=True,
)
关键参数:members 定义团队成员;instructions 指导 leader 的编排策略;show_members_responses=True 在输出中展示成员响应过程。该示例在 TEST_LOG 中标记 FAIL,但失败原因为风格校验(code_before_first_section_banner,即代码块出现在首个章节横幅之前),运行层面 Run: completed,不影响功能理解。
5.2 路由团队:02_respond_directly_router_team.py(PASS)
02_respond_directly_router_team.py 构建了一个多语言路由团队,是 mode=TeamMode.route 的典型实现:6 个成员分别只使用一种语言作答,leader 根据输入语言将请求路由到对应成员:
multi_language_team = Team(
name="Multi Language Team",
model=OpenAIResponses(id="gpt-5-mini"),
mode=TeamMode.route,
members=[english_agent, spanish_agent, japanese_agent, french_agent, german_agent, chinese_agent],
markdown=True,
instructions=[
"You are a language router that directs questions to the appropriate language agent.",
"If the user asks in a language whose agent is not a team member, respond in English with: "
"'I can only answer in the following languages: ...'",
"Always check the language of the user's input before routing to an agent.",
],
show_members_responses=True,
)
示例同时演示同步(print_response)与异步(aprint_response + asyncio.run)两种调用方式,并通过 stream=True 开启流式输出。该示例在 TEST_LOG 中 PASS。
5.3 广播协作:03_delegate_to_all_members.py(PASS)
03_delegate_to_all_members.py 演示 TeamMode.broadcast:Reddit Researcher 与 HackerNews Researcher 两个成员同时研究同一主题,leader 作为"讨论主持人"在达成共识时结束讨论。要点:成员通过 tools=[WebSearchTools()]、tools=[HackerNewsTools()] 获得外部检索能力,并通过 add_name_to_context=True 将自身名称注入上下文。
5.4 带历史的路由团队:04_respond_directly_with_history.py(PASS)
04_respond_directly_with_history.py 演示路由模式 + 会话历史的组合:
geo_search_team = Team(
name="Geo Search Team",
model=OpenAIResponses(id="gpt-5-mini"),
mode=TeamMode.route,
members=[weather_agent, news_agent, activities_agent],
instructions="You are a geo search agent that can answer questions about the weather, news and activities in a city.",
use_instruction_tags=True,
db=SqliteDb(db_file="tmp/geo_search_team.db"), # 存储会话历史
add_history_to_context=True, # 确保 leader 知晓之前的请求
)
连续三次提问(天气 → 该城市新闻 → 该城市活动)验证了 leader 能跨轮次记住"正在研究东京"这一上下文。两个核心参数:db=SqliteDb(...) 持久化历史(历史功能正常工作的前提),add_history_to_context=True 将历史注入 leader 上下文。
5.5 团队历史共享:05_team_history.py(FAIL,API 变更)
05_team_history.py 演示 add_team_history_to_members=True(将用户与团队的全部交互同步给成员)。TEST_LOG 记录其因 pass_user_input_to_members 参数已不被 Team.__init__ 接受而运行时失败——这是验证日志中最具价值的一类信息:它标记了 cookbook 示例与当前 SDK 之间的 API 漂移。当前源码中该文件已改用 respond_directly + determine_input_for_members + add_team_history_to_members 组合,读者以现行源码为准。
六、PASS 示例分布:通过率最高的功能域
TEST_LOG 共记录 125 个示例条目,其中 62 个 PASS、63 个 FAIL(约 46 个为纯风格校验问题,约 17 个涉及运行时错误,其中 4 个同时命中风格与运行时)。以下功能域在验证中全部通过,可作为低风险的上手路径:
- 会话持久化(07_session):
chat_history.py、custom_session_summary.py、persistent_session.py、search_past_sessions.py、session_summary.py、share_session_with_agent.py共 6 个全 PASS(仅session_options.py因未设置OPENAI_API_KEY失败,属环境问题); - 上下文管理(09_context_management):
additional_context.py、custom_system_message.py、few_shot_learning.py、filter_tool_calls_from_history.py、introduction.py、location_context.py共 6 个全 PASS; - 团队记忆(06_memory):
01_team_with_memory_manager.py、02_team_with_agentic_memory.py、03_memories_in_context.py、learning_machine.py共 4 个全 PASS; - 守卫(18_guardrails):
openai_moderation.py、pii_detection.py、prompt_injection.py共 3 个全 PASS; - 依赖注入(17_dependencies):
dependencies_in_context.py、dependencies_in_tools.py、dependencies_to_members.py共 3 个全 PASS; - 流式(08_streaming):
team_events.py、team_streaming.py共 2 个全 PASS; - 上下文压缩(10_context_compression):
tool_call_compression.py、tool_call_compression_with_manager.py共 2 个全 PASS; - 运行控制(14_run_control):
cancel_run.py、model_inheritance.py、remote_team.py、retries.py共 4 个 PASS; - 共享状态(21_state):
agentic_session_state.py、change_state_on_run.py、overwrite_stored_session_state.py、state_sharing.py共 4 个 PASS; - 多模态(19_multimodal):
audio_sentiment_analysis.py、audio_to_text.py、generate_image_with_team.py、image_to_text.py共 4 个 PASS; - 团队指标(22_metrics):
01_team_metrics.pyPASS; - 人机协同(20_human_in_the_loop):
confirmation_required.py、external_tool_execution.py、user_input_required.py共 3 个 PASS; - 工具(03_tools):
member_information.py、member_tool_hooks.py、tool_hooks.py共 3 个 PASS; - 分布式 RAG(15_distributed_rag):
01_distributed_rag_pgvector.pyPASS(PgVector 路径无额外依赖)。
七、FAIL 失败模式分析:四类典型问题与修复方向
7.1 模式一:风格校验失败(数量最多,运行本身完成)
这是 FAIL 的最大来源,特征是 Validation issue: style 且 Run: completed,即脚本能跑通但未通过代码风格规则。TEST_LOG 中出现的规则名及含义:
missing_docstring_underline:docstring 下方的下划线分隔线缺失(常见于02_modes/全部 16 个示例、12_learning/全部 6 个示例及20_human_in_the_loop/9 个示例);code_before_first_section_banner:第一个章节横幅之前出现了代码块(常见于01_quickstart/01_basic_coordination.py、13_hooks/2 个示例、05_knowledge/2 个示例等);import_after_first_section_banner:import 语句位于章节横幅之后(如21_state/nested_shared_state.py、02_modes/coordinate/03_structured_output.py)。
修复方向:为示例文件补齐 """docstring""" + ======= 横幅规范、调整 import 与代码块的顺序。功能层面无需改动。
7.2 模式二:可选依赖未安装(运行时 ImportError)
TEST_LOG 中多条运行时失败源于示例使用的外部库未安装,且错误信息直接给出了安装命令。可归纳为下表:
| 缺失依赖 | 触发路径 | 安装命令(来自报错) | 相关示例 |
|---|---|---|---|
tantivy |
libs/agno/agno/vectordb/lancedb/lance_db.py 全文检索初始化 | pip install tantivy |
15_distributed_rag/02、03;05_knowledge/01;16_search_coordination/01、02 |
fal_client |
libs/agno/agno/tools/fal.py FalTools 导入 |
pip install fal-client |
19_multimodal/image_to_image_transformation.py |
moviepy |
libs/agno/agno/tools/moviepy_video.py MoviePyVideoTools 导入 |
pip install moviepy ffmpeg |
19_multimodal/video_caption_generation.py |
e2b_code_interpreter |
libs/agno/agno/tools/e2b.py E2BTools 导入 |
pip install e2b_code_interpreter |
11_reasoning/reasoning_multi_purpose_team.py |
infinity_client |
libs/agno/agno/knowledge/reranker/infinity.py InfinityReranker 导入 |
pip install infinity_client |
16_search_coordination/03_distributed_infinity_search.py |
agentql |
libs/agno/agno/tools/agentql.py AgentQLTools 导入 |
pip install agentql |
03_tools/async_tools.py |
这类失败的判定方法:Traceback 中若出现 ModuleNotFoundError: No module named 'xxx' 且随后 raise ImportError("...not installed. Please install using ..."),即为可选依赖缺失,按提示安装后即可复跑。其中 tantivy 出现次数最多(5 个示例),凡使用 LanceDb 向量库的示例都依赖它提供全文检索能力。
7.3 模式三:模型 API Key 未配置(环境问题)
07_session/session_options.py、04_structured_input_output/json_schema_output.py 等 5 个示例报 OPENAI_API_KEY not set。日志中呈现的报错链路为:Model authentication error from OpenAI API → Error in Team run → 断言失败(如 AssertionError),其中 session_options.py 还在 set_session_name(autogenerate=True) 调用链(libs/agno/agno/team/_session.py → libs/agno/agno/utils/agent.py 的 set_session_name_util)中中断。修复方式:按 cookbook/03_teams/README.md 要求用 direnv allow 加载 OPENAI_API_KEY 后重跑。
7.4 模式四:API 兼容性变更(示例滞后于 SDK)
01_quickstart/05_team_history.py 报 Team.__init__() got an unexpected keyword argument 'pass_user_input_to_members',属于示例代码使用了已被移除的构造参数。这类失败无法通过装依赖或配环境解决,需对照当前 libs/agno/agno/team/team.py 的 Team 签名更新示例参数(该文件现行用法见 05_team_history.py)。
八、如何复现验证:运行命令与操作流程
TEST_LOG 中每条 PASS 记录都给出了可直接复用的运行命令,统一模式为:
# 1. 加载环境变量(例如 OPENAI_API_KEY)
direnv allow
# 2. 使用 demo 虚拟环境运行目标示例
.venvs/demo/bin/python cookbook/03_teams/01_quickstart/02_respond_directly_router_team.py
# 3. 如需复现失败示例(例如分布式 RAG 全文检索),先补齐依赖
pip install tantivy
.venvs/demo/bin/python cookbook/03_teams/15_distributed_rag/02_distributed_rag_lancedb.py