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 805b8238a18f88e8df864ba1513ef3d070d131892026-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_infralibs/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 有四套并存的记忆/上下文机制,这是它相对轻量框架最显眼的地方:

  1. 上下文压缩 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 输出瘦身。
  2. 长期记忆 memory/manager.py MemoryManagercreate_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 提供优化策略。
  3. 会话持久化session/(agent/team/workflow session)+ db/(20+ 后端:postgres / sqlite / mongo / redis / dynamo / firestore / gcs / clickhouse / singlestore / in_memory…)。agent/_run.py read_or_create_session(L412)每 run 读写;history 通过 add_history_to_context 注入。
  4. learning 分层记忆(见”自进化”节):另有 session_context / entity_memory 等分层。

工具体系(定义/调用协议/注册/权限)

  • 定义tools/function.py Function(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.py class 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_toolsdetermine_tools_for_model_run.py L458–471)解析成 model 可用的 _functions / _tool_dicts;执行在 model 层 _prepare_function_calls(L742)+ run_function_calls(L2313)。
  • 协议:标准 OpenAI-style function-calling,各 provider adapter(models/{anthropic,openai,...})各自转换。
  • MCPtools/mcp/ 一等支持,MCP server 可直接作为工具源。
  • 权限:见”安全与权限”节(@approval + toolkit requires_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_model L177)→ <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_contextformat_message_with_state_variables(L269)对 session_state 变量做插值。
  • 结论:声明式、可组合、无 few-shot、无自动 prompt 优化;每个能力模块(skills / memory / culture / learning)各自贡献一段 snippet 拼进系统提示。

Router / 编排(任务分解、多 agent、子 agent)

两套编排抽象并存,定位不同:

  • Teamteam/team.py class Team L73):leader-member 模式,运行时 LLM 自主分派。members(L78)可含 Agent 或嵌套 Team。leader 通过默认工具 delegate_task_to_member(member_id, task)team/_default_tools.py _get_delegate_task_function L441 / 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)。
  • Workflowworkflow/):显式 DAG / 程序化编排,非 LLM 决策。原语有 StepRouterworkflow/router.py,按输入动态选步骤,支持 CEL 表达式 selector workflow/cel.py)、LoopParallelConditionSteps、嵌套 Workflow。步骤可以是函数 / Agent / Team;带 HumanReview / OnReject(router.py import)。

一句话:Team = 运行时 LLM 自主分派,Workflow = 开发者写死流程,用户按控制程度自选。

Skill / 插件体系

两层

  • Agent Skillsskills/,Anthropic Skills 同款范式):Skill = SKILL.md(name/description/instructions frontmatter)+ scripts/ + references/skill.py)。Skills 类(agent_skills.py L16)由 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/ LearningMachinelearn/machine.py L53):统一编排多个 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.py start_learning_future L505);recall(L589)检索并注入上下文;get_tools(L437)也能给模型自主写 learning 的工具。
  • Curatorlearn/curate.py class Curator L28):记忆维护——prune(按 age/count 裁剪 L36)、deduplicate(近似去重 L84)。是”保持记忆整洁”,不是 eval 驱动纠错。
  • Cultureculture/manager.py):跨 agent / team 沉淀的共享”文化知识”(norms / lessons / guardrails),注入 system prompt 的 <cultural_knowledge>(Prompt 节),add_culture_to_context 时后台生成(_run.py start_cultural_knowledge_future L514)。这是 Agno 比较独特的”集体经验反哺”设计——多 agent 共享一份沉淀知识。
  • eval 驱动纠错eval/离线评测框架(AccuracyEval LLM-as-judge L148、performance、reliability、agent_as_judge),可作为 pre/post_hook 挂进 run(agent.py pre_hooks: List[... BaseEval] L191),但不构成”评测→改 prompt→重跑”的自动闭环
  • 结论:无自我改代码 / 无自我微调;“自进化” = 分层学习记忆 + 集体文化知识 + 记忆 curator。

可观测性(日志 / trace 格式)

  • Tracing = OpenTelemetrytracing/setup.py setup_tracing(L23)建 OTEL provider;tracing/exporter.py DatabaseSpanExporter(SpanExporter)(L18)把 OTEL ReadableSpan 转成自有 Spanschemas.Span.from_otel_span L59),按 trace_id 分组(L69)后写入 DB(_export_sync / _export_async)。即 trace 落自己的 DB(配合 AgentOS UI 展示),非外部 SaaS(但走标准 OTEL,可另接 collector)。
  • metricsmetrics.py accumulate_model_metrics(loop 内 L729)逐 run 累计 token / 时延;team 后台 future 做 metrics merge(_run.py L578)。
  • 日志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 可插入自定义观测点。

安全与权限(审批门、密钥管理)

  • 审批门 @approvalapproval/decorator.py L20 + 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_executiontools/function.py L171 / L181);执行时 run_function_calls(L2336–2446)生成 paused_tool_executions 并 yield tool_call_paused,loop break 挂起。本次分析的 commit(#8837)正是把 confirmation + user_input 接到 AG-UI。Toolkit 级 requires_confirmation_tools 批量标记(toolkit.py L26)。
  • Guardrailsguardrails/):BaseGuardrail.check(run_input)(L12)。内置 PromptInjectionGuardrail(关键词匹配注入模式,prompt_injection.py L38–45,命中抛 InputCheckError)、PIIDetectionGuardrailpii.py)、OpenAIModerationGuardrailopenai.py)。作为 pre_hooks / post_hooks 挂载(agent.py L191–193);_hooks.py(L73–88)保证 guardrail 同步先跑、全过才放行后续 hook(background 模式下 PII masking 在 deepcopy 前生效)。
  • 密钥管理无自建 secret store;工具走 env var / 参数传 api_key(如 tools/e2b.pyapi_key)。
  • 路径安全:skills 脚本走 path_safety(Skill 节);tools/python.py restrict_to_base_dir(L60 _check_path)限制文件访问。

沙箱与执行隔离

  • 框架默认无隔离tools/python.py PythonTools.save_to_file_and_run(L43)用 runpy.run_path(L71)在本进程内 execsafe_globals / safe_locals 只是命名,非真沙箱);tools/shell.py run_shell_command(L26)直接 subprocess.run(L40)。
  • 真隔离靠外部沙箱 toolkit(opt-in)tools/e2b.py(E2B Sandbox.create L49,云端 code interpreter)、tools/daytona.pyDaytonaTools L55,持久化云沙箱,run_codeauto_create_sandbox L71)、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.py L3072)让模型注入自己需要的 system 指令(_messages.py L177 拼进 instructions);_tool_choice 有默认值。
  • Reasoning 协同reasoning/manager.py L110):区分原生 reasoning 模型(DeepSeek R1 / Anthropic thinking / OpenAI o 系 / Gemini / Groq / Ollama / VertexAI / AzureAIFoundry,各 is_*_reasoning_model 探测 L123–132)与用独立 reasoning_model 做显式推理步骤reasoning/step.py)。_run.py handle_reasoning(L523)在 model 调用前插入。
  • Fallbackcall_model_with_fallback_run.py L531)+ agent.fallback_config 多模型降级。
  • 压缩 / 解析 / 输出模型可分离:compression model(记忆节)、output_model / parser_model_run.py L555 / 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.py L3246 断点续跑)。
  • 反哺训练?无。轨迹不用于微调 / RL,没有 trajectory→training 管线。
  • 反哺评测 / 记忆:轨迹 → learning stores(后台抽取)、→ memory、→ culture、→ decision_logeval/ 可对历史 run 跑离线评测。即”轨迹反哺上下文 / 记忆”,而非”反哺权重”。
  • 结论:轨迹用于持久化 / 续跑 / 记忆学习 / 离线 eval;不进训练闭环

与同类 harness 的关键差异(1-3 条)

  1. 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 的实现取向。
  2. 四套并行的记忆/知识分层 + 跨 agent culture:compression(BETA,只压 tool 结果)/ LLM 抽取的 user memory / learning stores(含 decision_log)/ 跨 agent 共享的 culture 集体知识,四者并存且各注入一段 system prompt。尤其”culture 集体经验反哺”在同类框架里少见。
  3. 生产化护栏一应俱全但都是可插拔 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: 805b8238a18f88e8df864ba1513ef3d070d131892026-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_callstool_call_limit、HITL break、compression 挂载点
    • agent/_run.py — 单次 run 编排:session 读写、pre/post hooks、tools 决定、memory/learning/culture 后台 future、reasoning、fallback
    • agent/_messages.py — system prompt 组装(XML tag 段落)
    • compression/manager.py — tool result 压缩(BETA)
    • tools/function.py tools/toolkit.py tools/decorator.py — 工具定义 / schema / 注册 / @tool
    • approval/decorator.py approval/types.py@approval 审批门
    • guardrails/{base,prompt_injection,pii,openai}.py — 输入护栏
    • skills/agent_skills.py skills/skill.py — Agent Skills(SKILL.md + 渐进披露)
    • learn/machine.py learn/curate.py — learning stores + curator
    • culture/manager.py — 跨 agent 共享文化知识
    • memory/manager.py memory/strategies/ — 长期 user memory
    • team/{team,_task_tools,_default_tools}.py — 多 agent 编排(leader-member delegate)
    • workflow/{router,loop,parallel,condition,step}.py — 程序化 workflow 编排
    • tracing/{exporter,setup,schemas}.py — OpenTelemetry trace
    • reasoning/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.pyagent_run.pyagent_messages.py
    • compression_manager.py
    • tools_function.pytools_toolkit.pytools_decorator.py
    • approval_decorator.py
    • guardrails_prompt_injection.py
    • skills_agent_skills.py
    • learn_machine.py
    • team_task_tools.py
    • tracing_exporter.py