Agno (原 Phidata)
一句话定位
Agno(原名 Phidata,~41k star)是一个 model-agnostic 的生产级 multi-agent 框架:真正的 agent loop 不在 agent 编排层,而藏在 model 适配层的 tool-calling while True 循环里,停止靠 tool_call_limit + 模型自停 + 多种 HITL break;system prompt 是声明式的 XML 段落拼装,各能力模块各贡献一段 snippet。它的差异化不在”更聪明的循环”,而在四套并存的”记忆/知识”分层(BETA 版 tool-result 压缩 / LLM 抽取的 user memory / learning stores / 跨 agent 的 culture 集体知识)、完整 HITL 三态 + @approval 审批门 + guardrails 前置护栏、Anthropic 式渐进披露 Agent Skills,以及 Team(LLM 运行时分派)与 Workflow(程序化 DAG)双编排、OpenTelemetry trace 落自有 DB。无 RL / 自我微调 / 强制沙箱——所谓”自进化”是学习型记忆 + 集体文化,隔离是 opt-in 的外部沙箱 toolkit。SDK 之外另有 AgentOS 自托管 runtime / 控制面(不在本调研的 SDK 源码范围内)。
核心架构总览(目录结构关键路径 + 引用的 commit)
分析基于 commit 805b8238a18f88e8df864ba1513ef3d070d13189(2026-07-10 12:04:38 -0400 feat: human-in-the-loop confirmation and user input over AG-UI (#8837),git clone --depth 1 浅克隆,克隆日期 2026-07-11)。纯 Python monorepo,核心库在 libs/agno/agno/;另有 libs/agno_infra、libs/agnoctl(CLI/infra),docs 站 https://docs.agno.com (v2)。产品形态是 SDK(Agent / Team / Workflow)+ AgentOS runtime,本调研聚焦 SDK 层 agent harness。
关键路径(相对 libs/agno/agno/):
models/base.py # 真正的 agent loop(tool-calling while 循环)+ run_function_calls + 压缩挂载点
agent/_run.py (271KB) # 单次 run 编排壳:session 读写 / pre-post hooks / tools 决定 / 后台 future / reasoning
agent/_messages.py # system prompt 组装(XML tag 段落)
compression/manager.py # tool result 压缩(BETA)
tools/{function,toolkit,decorator}.py # 工具定义 / JSON Schema / 注册 / @tool
approval/{decorator,types}.py # @approval 审批门
guardrails/{base,prompt_injection,pii,openai}.py # 输入护栏
skills/{agent_skills,skill}.py # Anthropic 式 Agent Skills(SKILL.md + 渐进披露)
learn/{machine,curate}.py # learning stores + curator(自进化最接近的模块)
culture/manager.py # 跨 agent 共享「文化知识」
memory/manager.py # 长期 user memory
team/{team,_task_tools,_default_tools}.py # 多 agent 编排(leader-member delegate)
workflow/{router,loop,parallel,condition,step}.py # 显式 workflow DAG 编排
tracing/{exporter,setup,schemas}.py # OpenTelemetry trace
reasoning/manager.py # reasoning 模式(原生 vs 独立 reasoning_model)
eval/{accuracy,performance,reliability,agent_as_judge}.py # 离线 eval 框架
db/ # 20+ session/trace 持久化后端
一个核心认知:编排壳(agent/_run.py)与真正的 tool 循环(models/base.py)是分离的。整条 run 本质是”一次 model.response()(内含完整 tool 循环)“的编排包装,_run.py 负责 session、hooks、reasoning、后台学习/记忆 future,而 tool-calling 的迭代发生在 model 层。
Agent Loop(主循环 / 何时继续何时停)
核心 loop 不在 agent 层,而在 model 层 models/base.py:
Model.response()从 L650 开始,主体是while True:(L703–871)。stream 版response_stream()(L1362)、async 版(L887 / L1647)四份同构。- 每一轮:可选压缩(L705)→
_process_model_response调模型(L716)→ 追加 assistant message(L734)→ 若assistant_message.tool_calls(L740)则run_function_calls逐个执行(L751)→format_function_call_results(L817)→continue回到循环顶(L868);若无 tool_calls 则 break(L871)。 - 停止条件(break):无 tool call(L871);任一结果标了
stop_after_tool_call(L836);HITL——requires_confirmation(L849)/external_execution_required(L853)/requires_user_input(L857)/ 未 resolve 的run_response.requirements(L863,team HITL 冒泡传播)。 - 迭代上限:
agent.tool_call_limit传入run_function_calls(function_call_limit=);run_function_calls(L2313)内current_function_call_count += 1,超限不抛错,而是给该 tool 追加一条create_tool_call_limit_error_result(L2326–2331)让模型看到”到上限了”从而自然收尾。没有独立的”最大轮数”参数,靠 tool_call_limit + 模型自停。 agent/_run.py_run()(L339)里的for attempt in range(num_attempts)(L400)是错误重试 / fallback,不是 agent 迭代——别把它误读成主循环。
记忆与上下文管理(压缩、长期记忆、会话持久化)
Agno 有四套并存的记忆/上下文机制,这是它相对轻量框架最显眼的地方:
- 上下文压缩
compression/manager.py(docs 标注 BETA):CompressionManager.should_compress(L69)用两种阈值触发——compress_token_limit(token 数,model.count_tokens)或compress_tool_results_limit(未压缩的 tool 消息条数)。compress()(L142)只压缩role=="tool"的结果,用一个(可单独指定的)model 按DEFAULT_COMPRESSION_PROMPT(L16,指令是”保留数字/日期/实体/ID,删掉 hedging/meta/格式”)逐条摘要,写进msg.compressed_content(不改原文,双存)。在 loop 顶 L705 触发。注意它不做全历史 summarization / 滑窗——只针对 tool 输出瘦身。 - 长期记忆
memory/manager.pyMemoryManager:create_user_memories(L377,LLM 从对话抽取事实)、get_user_memories(L174);enable_agentic_memory时暴露add_memory/update_memory两个 DB 工具(L1340 / L1371)给模型自主增删改。抽取出的 memory 注入 system prompt(见下节<memories_from_previous_interactions>)。memory/strategies/summarize.py提供优化策略。 - 会话持久化:
session/(agent/team/workflow session)+db/(20+ 后端:postgres / sqlite / mongo / redis / dynamo / firestore / gcs / clickhouse / singlestore / in_memory…)。agent/_run.pyread_or_create_session(L412)每 run 读写;history 通过add_history_to_context注入。 - learning 分层记忆(见”自进化”节):另有 session_context / entity_memory 等分层。
工具体系(定义/调用协议/注册/权限)
- 定义:
tools/function.pyFunction(BaseModel)(L132)——parameters是标准 JSON Schema(L142),Function.from_callable(L278)由函数签名 + docstring(parse_docstring)自动生成 schema,支持strict严格模式。运行期封装为FunctionCall。 @tool装饰器tools/decorator.py(L61):可设requires_confirmation/requires_user_input/external_execution/external_execution_silent/ cache 等,把普通函数变成Function。- Toolkit
tools/toolkit.pyclass Toolkit(L12):self.functions: OrderedDict(L67),支持include_tools/exclude_tools白/黑名单(L24–25)以及requires_confirmation_tools列表(L26)批量标审批。内置工具 120+ 个(tools/目录:websearch / github / slack / sql / python / shell / e2b / daytona / docker / mcp / …)。 - 注册 / dispatch:agent 层
get_tools→determine_tools_for_model(_run.pyL458–471)解析成 model 可用的_functions/_tool_dicts;执行在 model 层_prepare_function_calls(L742)+run_function_calls(L2313)。 - 协议:标准 OpenAI-style function-calling,各 provider adapter(
models/{anthropic,openai,...})各自转换。 - MCP:
tools/mcp/一等支持,MCP server 可直接作为工具源。 - 权限:见”安全与权限”节(
@approval+ toolkitrequires_confirmation_tools)。
Prompt 设计(系统提示结构、动态组装)
agent/_messages.py get_system_message(L106)——静态模板化拼接,按固定顺序生成 XML tag 段落(是声明式组装,不是动态 planner):
description(L236)→<your_role>(L239)→<instructions>(L243,callable instructions 会先执行 L167)→ 模型自带 instructions(get_instructions_for_modelL177)→<additional_information>(markdown / 当前时间 / 位置 / agent 名字,L182–261)→ tool instructions(L263)→<expected_output>(L277)→additional_context→<skills_system>(L282)→<memories_from_previous_interactions>(L299)+enable_agentic_memory时的<updating_user_memories>指令(L315)→<cultural_knowledge>(L353)→ learning / knowledge 段。use_instruction_tags(L242)控制是否用 XML 标签;resolve_in_context时format_message_with_state_variables(L269)对 session_state 变量做插值。- 结论:声明式、可组合、无 few-shot、无自动 prompt 优化;每个能力模块(skills / memory / culture / learning)各自贡献一段 snippet 拼进系统提示。
Router / 编排(任务分解、多 agent、子 agent)
两套编排抽象并存,定位不同:
- Team(
team/team.pyclass TeamL73):leader-member 模式,运行时 LLM 自主分派。members(L78)可含 Agent 或嵌套 Team。leader 通过默认工具delegate_task_to_member(member_id, task)(team/_default_tools.py_get_delegate_task_functionL441 / L595)把任务派给指定成员;_task_tools.py另有 task 看板式工具:create_task/execute_task(L403)/execute_tasks_parallel(L757,线程并行)/update_task_status/mark_all_complete。开关:respond_directly(L108,直接返回成员结果不再加工)、delegate_to_all_members(L109,广播)、determine_input_for_members(L112,leader 改写子任务输入)。HITL 可从 member 冒泡到 team(见 Agent Loop 节的 requirements)。 - Workflow(
workflow/):显式 DAG / 程序化编排,非 LLM 决策。原语有Step、Router(workflow/router.py,按输入动态选步骤,支持 CEL 表达式 selectorworkflow/cel.py)、Loop、Parallel、Condition、Steps、嵌套Workflow。步骤可以是函数 / Agent / Team;带HumanReview/OnReject(router.py import)。
一句话:Team = 运行时 LLM 自主分派,Workflow = 开发者写死流程,用户按控制程度自选。
Skill / 插件体系
两层:
- Agent Skills(
skills/,Anthropic Skills 同款范式):Skill= SKILL.md(name/description/instructions frontmatter)+scripts/+references/(skill.py)。Skills类(agent_skills.pyL16)由 loaders 加载(skills/loaders/);get_system_prompt_snippet(L90)只把 name + description + 文件清单塞进<skills_system>(渐进披露 / progressive disclosure),并暴露工具get_skill_instructions/get_skill_reference/get_skill_script(execute=False)(L115–117)让模型按需拉全文或执行脚本。脚本执行走skills/utils.run_script+ 路径安全path_safety.safe_join_relative_path(L13,越界抛PathSecurityError),另有validator.py硬校验。 - Toolkit 插件(见工具体系节):120+ 内置 toolkit 即插件生态;MCP toolbox(
tools/mcp_toolbox.py)作为外部工具通道。
自进化能力(自我改进 / 学习型记忆 / eval 驱动纠错)
Agno 没有 RL / 权重更新,但运行期的”学习型记忆”是它最接近自进化的部分:
learn/LearningMachine(learn/machine.pyL53):统一编排多个 learning store——user_profile/user_memory/session_context/entity_memory/learned_knowledge(有 knowledge base 时自动开,L143)/decision_log(L85,决策日志)。process/aprocess(L515 / L556)在每 run 后台 future 里抽取并写库(_run.pystart_learning_futureL505);recall(L589)检索并注入上下文;get_tools(L437)也能给模型自主写 learning 的工具。- Curator(
learn/curate.pyclass CuratorL28):记忆维护——prune(按 age/count 裁剪 L36)、deduplicate(近似去重 L84)。是”保持记忆整洁”,不是 eval 驱动纠错。 - Culture(
culture/manager.py):跨 agent / team 沉淀的共享”文化知识”(norms / lessons / guardrails),注入 system prompt 的<cultural_knowledge>(Prompt 节),add_culture_to_context时后台生成(_run.pystart_cultural_knowledge_futureL514)。这是 Agno 比较独特的”集体经验反哺”设计——多 agent 共享一份沉淀知识。 - eval 驱动纠错:
eval/是离线评测框架(AccuracyEval LLM-as-judge L148、performance、reliability、agent_as_judge),可作为 pre/post_hook 挂进 run(agent.pypre_hooks: List[... BaseEval]L191),但不构成”评测→改 prompt→重跑”的自动闭环。 - 结论:无自我改代码 / 无自我微调;“自进化” = 分层学习记忆 + 集体文化知识 + 记忆 curator。
可观测性(日志 / trace 格式)
- Tracing = OpenTelemetry:
tracing/setup.pysetup_tracing(L23)建 OTEL provider;tracing/exporter.pyDatabaseSpanExporter(SpanExporter)(L18)把 OTELReadableSpan转成自有Span(schemas.Span.from_otel_spanL59),按trace_id分组(L69)后写入 DB(_export_sync/_export_async)。即 trace 落自己的 DB(配合 AgentOS UI 展示),非外部 SaaS(但走标准 OTEL,可另接 collector)。 - metrics:
metrics.pyaccumulate_model_metrics(loop 内 L729)逐 run 累计 token / 时延;team 后台 future 做 metrics merge(_run.pyL578)。 - 日志:
utils/log.py,全程log_debug/log_info/log_error;message 有.log(metrics=True)(L737);debug_mode/debug.py。 - hooks 可观测:
agent/_hooks.py的 pre/post hooks 可插入自定义观测点。
安全与权限(审批门、密钥管理)
- 审批门
@approval(approval/decorator.pyL20 +approval/types.py):ApprovalType.required= 阻塞(run 暂停到 approvals API resolve 才继续);ApprovalType.audit= 非阻塞审计记录(L57)。required会自动置requires_confirmation=True(L54–56)。可与@tool任意顺序组合。 - HITL 三态:
requires_confirmation/requires_user_input/external_execution(tools/function.pyL171 / L181);执行时run_function_calls(L2336–2446)生成paused_tool_executions并 yieldtool_call_paused,loop break 挂起。本次分析的 commit(#8837)正是把 confirmation + user_input 接到 AG-UI。Toolkit 级requires_confirmation_tools批量标记(toolkit.pyL26)。 - Guardrails(
guardrails/):BaseGuardrail.check(run_input)(L12)。内置PromptInjectionGuardrail(关键词匹配注入模式,prompt_injection.pyL38–45,命中抛InputCheckError)、PIIDetectionGuardrail(pii.py)、OpenAIModerationGuardrail(openai.py)。作为 pre_hooks / post_hooks 挂载(agent.pyL191–193);_hooks.py(L73–88)保证 guardrail 同步先跑、全过才放行后续 hook(background 模式下 PII masking 在 deepcopy 前生效)。 - 密钥管理:无自建 secret store;工具走 env var / 参数传
api_key(如tools/e2b.py的api_key)。 - 路径安全:skills 脚本走
path_safety(Skill 节);tools/python.pyrestrict_to_base_dir(L60_check_path)限制文件访问。
沙箱与执行隔离
- 框架默认无隔离:
tools/python.pyPythonTools.save_to_file_and_run(L43)用runpy.run_path(L71)在本进程内 exec(safe_globals/safe_locals只是命名,非真沙箱);tools/shell.pyrun_shell_command(L26)直接subprocess.run(L40)。 - 真隔离靠外部沙箱 toolkit(opt-in):
tools/e2b.py(E2BSandbox.createL49,云端 code interpreter)、tools/daytona.py(DaytonaToolsL55,持久化云沙箱,run_code,auto_create_sandboxL71)、tools/docker.py(Docker 容器)。这些把执行推到隔离环境,但是用户自选工具,非框架默认。 - 结论:框架本身不强制沙箱,隔离是 opt-in 的 tool 选择。AgentOS 部署侧另有云隔离(不在 SDK 源码内,官方未在本仓详细披露)。
与模型的协同设计
- Provider 适配层
models/:30+ provider(anthropic / openai / aws / azure / gemini / groq / cerebras / cohere / deepseek / ollama / …),统一Model.response()接口,各 adapter 转 function-calling 协议。 - Model 可反向影响 prompt / 工具:
Model.get_instructions_for_model(tools)(models/base.pyL3072)让模型注入自己需要的 system 指令(_messages.pyL177 拼进 instructions);_tool_choice有默认值。 - Reasoning 协同(
reasoning/manager.pyL110):区分原生 reasoning 模型(DeepSeek R1 / Anthropic thinking / OpenAI o 系 / Gemini / Groq / Ollama / VertexAI / AzureAIFoundry,各is_*_reasoning_model探测 L123–132)与用独立reasoning_model做显式推理步骤(reasoning/step.py)。_run.pyhandle_reasoning(L523)在 model 调用前插入。 - Fallback:
call_model_with_fallback(_run.pyL531)+agent.fallback_config多模型降级。 - 压缩 / 解析 / 输出模型可分离:compression model(记忆节)、
output_model/parser_model(_run.pyL555 / L558)各用不同模型。 - 结论:model-agnostic 抽象层,无为特定模型协同训练;“协同”靠 adapter + reasoning 探测 + 可插拔多模型分工来实现。
轨迹利用(session/trajectory 是否反哺训练/评测)
- session / trajectory 全量持久化:每 run 的 messages / tool_executions / metrics 存
db/(_run.py/_storage.py),OTEL span 存 trace DB(可观测性节)。可回放 / 审计 /continue_run(_run.pyL3246 断点续跑)。 - 反哺训练?无。轨迹不用于微调 / RL,没有 trajectory→training 管线。
- 反哺评测 / 记忆:轨迹 → learning stores(后台抽取)、→ memory、→ culture、→
decision_log;eval/可对历史 run 跑离线评测。即”轨迹反哺上下文 / 记忆”,而非”反哺权重”。 - 结论:轨迹用于持久化 / 续跑 / 记忆学习 / 离线 eval;不进训练闭环。
与同类 harness 的关键差异(1-3 条)
- agent loop 下沉到 model 层:多数框架(OpenManus / CrewAI 等)把 ReAct / tool 循环写在 agent 层;Agno 把真正的 tool-calling
while True放进models/base.py,agent 层只是编排壳。停止条件不靠”最大轮数”抛错,而是tool_call_limit超限后塞 error result 让模型自停(L2326–2331)——这是它区别于大多数 harness 的实现取向。 - 四套并行的记忆/知识分层 + 跨 agent culture:compression(BETA,只压 tool 结果)/ LLM 抽取的 user memory / learning stores(含 decision_log)/ 跨 agent 共享的 culture 集体知识,四者并存且各注入一段 system prompt。尤其”culture 集体经验反哺”在同类框架里少见。
- 生产化护栏一应俱全但都是可插拔 hook:
@approval阻塞/审计双态、HITL 三态、三类 guardrails(注入/PII/moderation)作为 pre/post hook 前置强跑——安全能力比轻量框架完整,但沙箱隔离仍是 opt-in 外部 toolkit,框架默认在本进程内 exec。
原始源码定位
- repo: https://github.com/agno-agi/agno (官方,agno-agi org,~41k star,原名 Phidata)
- commit/version analyzed:
805b8238a18f88e8df864ba1513ef3d070d13189(2026-07-10 12:04:38 -0400 feat: human-in-the-loop confirmation and user input over AG-UI (#8837);git clone --depth 1,2026-07-11) - 关键文件列表(相对
libs/agno/agno/):models/base.py— 真正的 agent loop(tool-calling while 循环)、run_function_calls、tool_call_limit、HITL break、compression 挂载点agent/_run.py— 单次 run 编排:session 读写、pre/post hooks、tools 决定、memory/learning/culture 后台 future、reasoning、fallbackagent/_messages.py— system prompt 组装(XML tag 段落)compression/manager.py— tool result 压缩(BETA)tools/function.pytools/toolkit.pytools/decorator.py— 工具定义 / schema / 注册 /@toolapproval/decorator.pyapproval/types.py—@approval审批门guardrails/{base,prompt_injection,pii,openai}.py— 输入护栏skills/agent_skills.pyskills/skill.py— Agent Skills(SKILL.md + 渐进披露)learn/machine.pylearn/curate.py— learning stores + curatorculture/manager.py— 跨 agent 共享文化知识memory/manager.pymemory/strategies/— 长期 user memoryteam/{team,_task_tools,_default_tools}.py— 多 agent 编排(leader-member delegate)workflow/{router,loop,parallel,condition,step}.py— 程序化 workflow 编排tracing/{exporter,setup,schemas}.py— OpenTelemetry tracereasoning/manager.py— reasoning 模式eval/{accuracy,performance,reliability,agent_as_judge}.py— 离线 eval 框架db/— 20+ session/trace 持久化后端
一手源存档(sources/)
存于 /Users/zhao/projects/self-wiki/ai-research/sources/harness/agno/:
NOTES.md— 12 维度逐条带文件 + 行号证据的调研笔记(一手)src/(13 个核心文件留档,重命名为扁平模块_文件.py):models_base.py、agent_run.py、agent_messages.pycompression_manager.pytools_function.py、tools_toolkit.py、tools_decorator.pyapproval_decorator.pyguardrails_prompt_injection.pyskills_agent_skills.pylearn_machine.pyteam_task_tools.pytracing_exporter.py