跟踪 Agno

Agno 是用于生成代理应用程序的开源框架。 它侧重于将工具和策略组合到面向任务的代理中。

MLflow 追踪 与 Agno 集成,可捕获自动化工作流和工具配置的全面轨迹。 使用 mlflow.agno.autolog 启用它。 集成提供端到端可见性:

  • 提示和完成响应
  • 潜伏期
  • 有关不同代理的元数据,例如函数名称
  • 令牌使用情况和成本
  • 缓存命中
  • 引发的任何异常

注释

在无服务器计算群集上,不会自动启用自动记录。 必须显式调用 mlflow.agno.autolog() 才能为此集成启用自动跟踪。

先决条件

若要将 MLflow 跟踪与 Agno 配合使用,需要安装 MLflow 和相关 Agno 包。

开发

对于开发环境,请使用 Databricks Extras 和 Agno 安装完整的 MLflow 包:

pip install --upgrade "mlflow[databricks]>=3.1" agno openai

完整 mlflow[databricks] 包包括用于 Databricks 的本地开发和试验的所有功能。

生产

对于生产部署,请安装 mlflow-tracing 和 Agno。

pip install --upgrade mlflow-tracing agno openai

mlflow-tracing 已针对生产用途进行优化。

注释

建议使用 MLflow 3 来获得最佳跟踪体验。

在运行示例之前,需要配置环境:

对于不使用 Databricks 笔记本的用户:设置 Databricks 环境变量:

export DATABRICKS_HOST="https://your-workspace.cloud.databricks.com"
export DATABRICKS_TOKEN="your-personal-access-token"

对于 Databricks 笔记本中的用户:这些凭据会自动为您设置。

基本示例

import mlflow

mlflow.agno.autolog()

from agno.agent import Agent
from agno.models.anthropic import Claude
from agno.tools.yfinance import YFinanceTools

agent = Agent(
    model=Claude(id="claude-sonnet-4-20250514"),
    tools=[YFinanceTools(stock_price=True)],
    instructions="Use tables to display data. Don't include any other text.",
    markdown=True,
)
agent.print_response("What is the stock price of Apple?", stream=False)

照常运行 Agno 代理程序。 跟踪记录将显示在试验 UI 中。

多代理示例

import 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(
    name="Web Search Agent",
    role="Handle web search requests and general research",
    model=OpenAIChat(id="gpt-4.1"),
    tools=[DuckDuckGoTools()],
    instructions="Always include sources",
    add_datetime_to_instructions=True,
)

finance_agent = Agent(
    name="Finance Agent",
    role="Handle financial data requests and market analysis",
    model=OpenAIChat(id="gpt-4.1"),
    tools=[
        YFinanceTools(
            stock_price=True,
            stock_fundamentals=True,
            analyst_recommendations=True,
            company_info=True,
        )
    ],
    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_instructions=True,
)

reasoning_finance_team = Team(
    name="Reasoning Finance Team",
    mode="coordinate",
    model=Claude(id="claude-sonnet-4-20250514"),
    members=[web_agent, finance_agent],
    tools=[ReasoningTools(add_instructions=True)],
    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",
    ],
    markdown=True,
    show_members_responses=True,
    enable_agentic_context=True,
    add_datetime_to_instructions=True,
    success_criteria="The 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_reasoning=True,
)

令牌使用情况跟踪

MLflow 记录每次代理调用至 mlflow.chat.tokenUsage 的令牌使用情况。 整个跟踪的总令牌使用情况在跟踪信息对象的 token_usage 字段中提供。

# Get the trace object just created
last_trace_id = mlflow.get_last_active_trace_id()
trace = mlflow.get_trace(trace_id=last_trace_id)

# Print the token usage
total_usage = trace.info.token_usage
print("== Total token usage: ==")
print(f"  Input tokens: {total_usage['input_tokens']}")
print(f"  Output tokens: {total_usage['output_tokens']}")
print(f"  Total tokens: {total_usage['total_tokens']}")

# Print the token usage for each LLM call
print("\n== Detailed usage for each LLM call: ==")
for span in trace.data.spans:
    if usage := span.get_attribute("mlflow.chat.tokenUsage"):
        print(f"{span.name}:")
        print(f"  Input tokens: {usage['input_tokens']}")
        print(f"  Output tokens: {usage['output_tokens']}")
        print(f"  Total tokens: {usage['total_tokens']}")

禁用自动跟踪

使用 mlflow.agno.autolog(disable=True) 禁用,或使用 mlflow.autolog(disable=True) 全局禁用。