ARTICLE DETAIL

资讯详情

深耕网站视觉设计与运营推广的一线实战洞察。

MLflow Agno 集成指南:用 mlflow.agno.autolog() 一键追踪 Agno Agent 全链路

MLflow Agno 集成指南:用 mlflow.agno.autolog() 一键追踪 Agno Agent 全链路 MLflow Agno 集成指南用 mlflow.agno.autolog() 一键追踪 Agno Agent 全链路【免费下载链接】mlflowThe open source AI engineering platform for agents, LLMs, and ML models. MLflow enables teams of all sizes to debug, evaluate, monitor, and optimize production-quality AI applications while controlling costs and managing access to models and data.项目地址: https://gitcode.com/GitHub_Trending/ml/mlflowMLflow 为 Agno一个用于编排 LLM、推理步骤、工具与记忆的 Agent 框架提供了原生自动追踪能力只需调用mlflow.agno.autolog()即可自动捕获 Agent 调用产生的 Trace 并记录到当前激活的 MLflow Experiment。本文以 API 参考文档 mlflow.agno.rst 为核心结合源码实现、官方集成文档与测试用例讲解该 API 的参数语义、自动追踪范围、底层双引擎V1 补丁式 / V2 OpenTelemetry原理以及单 Agent、多 Agent 协作场景下的实战用法。一、API 一览mlflow.agno.autolog 签名与参数语义mlflow.agno模块的公开入口只有一个函数autolog()定义于 mlflow/agno/init.py完整的参数语义如下参数类型默认值作用log_tracesboolTrue是否记录 Agno Agent 的 Trace设为False时只保留 autolog 集成注册不产生追踪数据disableboolFalse设为True时关闭 Agno autologging并反注册已安装的插桩silentboolFalse设为True时抑制 MLflow 的所有事件日志与警告函数体上还显式标注了autolog.integration_name agno见 mlflow/agno/init.py这是mlflow.autolog()全局入口识别该集成所需的关键标记——因此用户既可以直接调用mlflow.agno.autolog()也可以通过mlflow.autolog()统一开启。值得注意的是源码中_autolog()使用了autologging_integration(FLAVOR_NAME)装饰器承载共享逻辑而真正的清理逻辑被刻意放在装饰器包裹的入口之外。注释说明mlflow/agno/init.py这样设计的原因带注解的包装函数在disableTrue时不会执行若把反注册逻辑放进装饰函数内将无法完成关闭时的清理。这是一个理解该 API 内部实现时很关键的细节。二、快速开始三行代码启用 Agno 自动追踪官方集成文档 agno.mdx 给出的启用方式极为简洁import mlflow mlflow.agno.autolog()建议版本组合文档示例环境pip install mlflow3.3 agno anthropic yfinance。若使用 Agno V2 2.0.0还需要额外的 OpenTelemetry 相关依赖源码在缺少依赖时会抛出MlflowException并给出安装提示见 mlflow/agno/autolog_v2.pypip install opentelemetry-exporter-otlp openinference-instrumentation-agno启用后一个最简单的追踪示例来自官方集成文档from agno.agent import Agent from agno.models.anthropic import Claude from agno.tools.yfinance import YFinanceTools agent Agent( modelClaude(idclaude-sonnet-4-20250514), tools[YFinanceTools(stock_priceTrue)], instructionsUse tables to display data. Dont include any other text., markdownTrue, ) agent.print_response(What is the stock price of Apple?, streamFalse)自动追踪会捕获每次 Agentic 调用的以下信息Prompt 与完成响应completion responses各调用延迟Agent 元数据如函数名Token 用量与成本缓存命中情况调用过程中抛出的任何异常三、自动追踪覆盖范围Agent、Team、工具调用、记忆存储与模型从mlflow.agno.autolog()的 V1 补丁清单mlflow/agno/init.py可以看出自动追踪覆盖的类与方法class_map { agno.agent.Agent: [run, arun], agno.team.Team: [run, arun], agno.tools.function.FunctionCall: [execute, aexecute], }此外模块还会动态发现两类对象并自动注册补丁存储后端Storage通过discover_storage_backends()导入agno.storage下全部子模块递归收集所有Storage子类并为其补丁create / read / upsert / drop / upgrade_schema方法见 mlflow/agno/utils.py模型子类Model通过find_model_subclasses()导入agno.models下全部子模块递归收集所有Model子类并按 MRO 深度排序更具体的类先被打补丁为其补丁invoke / ainvoke方法见 mlflow/agno/utils.py。打补丁时源码会先判断原方法是否为协程函数inspect.iscoroutinefunction同步方法套用patched_class_call、异步方法套用patched_async_class_callmlflow/agno/init.py并通过safe_patch保证补丁可安全叠加与卸载。相应地生成的 Span 类型由被调用实例决定见 mlflow/agno/autolog_v1.py实例类型Span 类型说明Agent/TeamAGENTAgent 或团队执行入口run/arunFunctionCallTOOL工具函数调用execute/aexecuteStorageMEMORY记忆存储读写create/read/upsert等ModelLLM底层模型调用invoke/ainvoke其他UNKNOWN兜底从源码结构可以推断Agent.run调用会层层触发其内部的Model.invoke与FunctionCall.execute因此一次运行通常会展开为一条包含 AGENT → LLM → TOOL 多层子 Span 的完整 Trace这与测试test_run_simple_autolog中断言一次Agent.run产生 2 个 SpanAgent.runClaude.invoke的行为完全一致见 tests/agno/test_agno_tracing.py。四、Span 内容细节输入输出、Agent 属性与 Token 用量对于Agent/Team的调用_set_span_inputs_attributes会将实例的__dict__写入 Span 属性其中tools会通过model_dumps(exclude_noneTrue)序列化为结构化 JSON见 mlflow/agno/autolog_v1.py并把run方法中非None的入参写入 Span inputs——因为Agent.run有大量可选参数过滤掉None可以避免噪声mlflow/agno/autolog_v1.py。Span 命名遵循以下规则mlflow/agno/autolog_v1.py工具调用优先使用FunctionCall上的function_name/name/tool_name属性取不到时回退到底层函数的name/__name__仍无则命名为AgnoToolCall其他实例统一命名为{ClassName}.{method_name}例如Agent.run、Claude.invoke。输出侧RunResponse/TeamRunResponse会被转换为to_dict()写入 Span outputs并从result.metrics或session_metrics中聚合input_tokens、output_tokens、total_tokens以SpanAttributeKey.CHAT_USAGE属性挂到 Span 上mlflow/agno/autolog_v1.py。这就是 MLflow 能够展示 Token 用量与成本趋势的数据来源。五、底层双引擎V1 补丁式追踪与 V2 OpenTelemetry 插桩mlflow.agno.autolog()会根据已安装的 Agno 版本自动选择实现路径mlflow/agno/init.py5.1 Agno V1 2.0.0基于 safe_patch 的补丁式追踪V1 路径实现在 mlflow/agno/autolog_v1.py。核心逻辑是with mlflow.start_span(namespan_name, span_typespan_type) as span: raw_inputs construct_full_inputs(original, self, *args, **kwargs) _set_span_inputs_attributes(span, self, raw_inputs) result original(self, *args, **kwargs) _set_span_outputs(span, result) return result同步与异步版本patched_class_call/patched_async_class_call结构相同区别仅在await原始方法。异常在with块内抛出时MLflow 会自动将 Span/Trace 标记为ERROR状态测试test_run_failure_tracing验证了失败场景下SpanStatusCode.ERROR与错误描述ModelProviderError: bang的落盘tests/agno/test_agno_tracing.py。5.2 Agno V2 2.0.0OpenInference 插桩 MLflow 上下文桥接V2 路径实现在 mlflow/agno/autolog_v2.py。Agno V2 自身通过openinference.instrumentation.agno.AgnoInstrumentor导出 OpenTelemetry SpanMLflow 的做法是自定义_MlflowTracerProvider把get_tracer()替换为委托给 MLflow 的_get_tracer()mlflow/agno/autolog_v2.py用_MlflowContextBridgingTracer包装返回的 Tracer其start_span/start_as_current_span通过_bridge_parent_context把 Agno 的 OpenInference Span 挂到当前激活的 MLflow Span 之下mlflow/agno/autolog_v2.py。_bridge_parent_context处理了一个易踩坑的场景OpenInference 在顶层 Agno Team 上会传入一个包裹INVALID_SPAN的 context 以强制创建根 Span。该函数会识别这种无效父级并改桥接到 MLflow 的当前上下文从而保证 Agno 产生的 Span 与手工创建的mlflow.start_span()合并为同一条 Trace而不是各自独立的 Trace。测试test_v2_spans_nest_under_manual_mlflow_span与test_v2_invalid_span_context_still_nests_under_manual_mlflow_span对此做了专门验证tests/agno/test_agno_tracing.py。5.3 关闭时的对称清理disableTrue或log_tracesFalse时V2 路径会调用_uninstrument_otel()反注册 AgnoInstrumentormlflow/agno/autolog_v2.pyV1 路径则借助safe_patch的卸载能力移除全部补丁。因此该 API 支持在运行期安全地反复开启/关闭测试test_run_simple_autolog末尾即验证了autolog(disableTrue)后再次运行 Agent 不再产生 Tracetests/agno/test_agno_tracing.py。六、多 AgentAgents to Agents协作追踪官方集成文档专门介绍了对 Agno非流式端点的多 Agent 协作追踪MLflow 会自动记录 Agent 之间的每一次 handoff交接、交互消息以及所用工具/函数的细节输入、输出、耗时便于排查问题、度量性能与复现结果。一个完整的 Team 协作示例来自 agno.mdximport mlflow from agno.agent import Agent from agno.models.anthropic import Claude from agno.models.openai import OpenAIChat from agno.team.team import Team from agno.tools.duckduckgo import DuckDuckGoTools from agno.tools.reasoning import ReasoningTools from agno.tools.yfinance import YFinanceTools # Enable auto tracing for Agno mlflow.agno.autolog() web_agent Agent( nameWeb Search Agent, roleHandle web search requests and general research, modelOpenAIChat(idgpt-4.1), tools[DuckDuckGoTools()], instructionsAlways include sources, add_datetime_to_instructionsTrue, ) finance_agent Agent( nameFinance Agent, roleHandle financial data requests and market analysis, modelOpenAIChat(idgpt-4.1), tools[ YFinanceTools( stock_priceTrue, stock_fundamentalsTrue, analyst_recommendationsTrue, company_infoTrue, ) ], instructions[ Use tables to display stock prices, fundamentals (P/E, Market Cap), and recommendations., Clearly state the company name and ticker symbol., Focus on delivering actionable financial insights., ], add_datetime_to_instructionsTrue, ) reasoning_finance_team Team( nameReasoning Finance Team, modecoordinate, modelClaude(idclaude-sonnet-4-20250514), members[web_agent, finance_agent], tools[ReasoningTools(add_instructionsTrue)], instructions[ Collaborate to provide comprehensive financial and investment insights, Consider both fundamental analysis and market sentiment, Use tables and charts to display data clearly and professionally, Present findings in a structured, easy-to-follow format, Only output the final consolidated analysis, not individual agent responses, ], markdownTrue, show_members_responsesTrue, enable_agentic_contextTrue, add_datetime_to_instructionsTrue, success_criteriaThe team has provided a complete financial analysis with data, visualizations, risk assessment, and actionable investment recommendations supported by quantitative analysis and market research., ) reasoning_finance_team.print_response( Compare the tech sector giants (AAPL, GOOGL, MSFT) performance: 1. Get financial data for all three companies 2. Analyze recent news affecting the tech sector 3. Calculate comparative metrics and correlations 4. Recommend portfolio allocation weights, show_full_reasoningTrue, )Team与成员Agent均在追踪范围内V1 下Team.run/arun被打补丁V2 下 OpenInference 原生覆盖因此上述一次print_response会生成覆盖 Team 编排、成员 Agent、工具调用与模型调用的完整嵌套 Trace。七、Token 用量与成本追踪MLflow 会自动为 Agno 记录每次 LLM 调用的 Token 用量与成本每个 Trace/Span 上都会记录 Token 用量input_tokens/output_tokens/total_tokens见 mlflow/agno/autolog_v1.py内置 Dashboard 会展示聚合后的成本与耗时趋势如需以编程方式读取这些数据官方文档指向 Token Usage and Cost Tracking 主题对应 docs/docs/genai/tracing/ 下的专题文档。测试中test_run_simple_autolog断言了traces[0].info.token_usage与 LLM 返回的Usage(input_tokens5, output_tokens7, total_tokens12)完全一致tests/agno/test_agno_tracing.py可作为该行为的验证依据。八、关闭自动追踪与其他 MLflow 集成一致可通过两种方式全局关闭 Agno 自动追踪见 agno.mdxmlflow.agno.autolog(disableTrue) # 或 mlflow.autolog(disableTrue)源码层面disableTrue时会同时执行_autolog的清理与V2 下_uninstrument_otel()的反注册确保后续 Agno 调用不再产生任何 Trace。九、补充说明与适用前提版本前提V1 补丁式追踪适用于 Agno 2.0.0Agno 2.0.0自动切换为 OpenTelemetry/OpenInference 插桩并需要opentelemetry-exporter-otlp与openinference-instrumentation-agno两个额外包。流式支持V1 路径下源码注释明确标注# TODO: Support streamingmlflow/agno/init.py因此 V1 的模型子类目前仅对invoke/ainvoke打补丁多 Agent 追踪场景官方文档也说明针对的是非流式端点。错误处理差异Agno 2.3.14起模型错误会被 Agno 内部捕获并以错误状态返回而非抛出异常这会影响失败 Span 的生成方式见 tests/agno/test_agno_tracing.py 与test_v2_failure_creates_spans。上下文桥接在 Agno V2 下若外层已有手工创建的mlflow.start_span()Agno 自动产生的 Span 会嵌套其下合并为单条 Trace无论 MLflow 的 tracer provider 处于 isolated 还是 unified 模式MLFLOW_USE_DEFAULT_TRACER_PROVIDER该行为均被测试覆盖tests/agno/test_agno_tracing.py。相关代码与文档索引API 参考docs/api_reference/source/python_api/mlflow.agno.rst集成指南docs/docs/genai/tracing/integrations/listing/agno.mdx入口实现mlflow/agno/init.pyV1 补丁逻辑mlflow/agno/autolog_v1.pyV2 OpenTelemetry 插桩mlflow/agno/autolog_v2.py存储/模型动态发现mlflow/agno/utils.py测试用例tests/agno/test_agno_tracing.py【免费下载链接】mlflowThe open source AI engineering platform for agents, LLMs, and ML models. MLflow enables teams of all sizes to debug, evaluate, monitor, and optimize production-quality AI applications while controlling costs and managing access to models and data.项目地址: https://gitcode.com/GitHub_Trending/ml/mlflow创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表