本示例展示了如何获取 agent 运行的指标。

代码

cookbook/agent_concepts/other/agent_metrics.py
from typing import Iterator
from agno.agent import Agent, RunResponse
from agno.models.openai import OpenAIChat
from agno.tools.yfinance import YFinanceTools
from agno.utils.pprint import pprint_run_response
from rich.pretty import pprint

agent = Agent(
    model=OpenAIChat(id="gpt-4o"),
    tools=[YFinanceTools(stock_price=True)],
    markdown=True,
    show_tool_calls=True,
)

run_stream: Iterator[RunResponse] = agent.run(
    "What is the stock price of NVDA", stream=True
)
pprint_run_response(run_stream, markdown=True)

# 打印每个消息的指标
if agent.run_response.messages:
    for message in agent.run_response.messages:
        if message.role == "assistant":
            if message.content:
                print(f"消息: {message.content}")
            elif message.tool_calls:
                print(f"工具调用: {message.tool_calls}")
            print("---" * 5, "指标", "---" * 5)
            pprint(message.metrics)
            print("---" * 20)

# 打印指标
print("---" * 5, "聚合指标", "---" * 5)
pprint(agent.run_response.metrics)
# 打印会话指标
print("---" * 5, "会话指标", "---" * 5)
pprint(agent.session_metrics)

用法

1

创建虚拟环境

打开 Terminal 并创建一个 python 虚拟环境。

python3 -m venv .venv
source .venv/bin/activate
2

设置您的 API 密钥

export OPENAI_API_KEY=xxx
3

安装库

pip install -U openai agno yfinance rich
4

运行 Agent

python cookbook/agent_concepts/other/agent_metrics.py