用法
Agents SDK 会自动跟踪每次运行的 token 用量。您可以从运行上下文访问它,并用它来监控成本、强制限制或记录分析数据。
跟踪的内容
- requests: 发起的 LLM API 调用次数
- input_tokens: 发送的总输入 token 数
- output_tokens: 接收的总输出 token 数
- total_tokens: 输入 + 输出
- request_usage_entries: 逐请求用法明细列表
- 详情:
input_tokens_details.cached_tokensoutput_tokens_details.reasoning_tokens
从运行中访问用法
在 Runner.run(...) 之后,通过 result.context_wrapper.usage 访问用法。
result = await Runner.run(agent, "What's the weather in Tokyo?")
usage = result.context_wrapper.usage
print("Requests:", usage.requests)
print("Input tokens:", usage.input_tokens)
print("Output tokens:", usage.output_tokens)
print("Total tokens:", usage.total_tokens)
用法会在运行期间的所有模型调用中进行聚合(包括工具调用和交接)。
启用 LiteLLM 模型中的用法
LiteLLM 提供程序默认情况下不会报告用法指标。在使用 LitellmModel 时,将 ModelSettings(include_usage=True) 传递给您的 agent,以便 LiteLLM 响应填充 result.context_wrapper.usage。
from agents import Agent, ModelSettings, Runner
from agents.extensions.models.litellm_model import LitellmModel
agent = Agent(
name="Assistant",
model=LitellmModel(model="your/model", api_key="..."),
model_settings=ModelSettings(include_usage=True),
)
result = await Runner.run(agent, "What's the weather in Tokyo?")
print(result.context_wrapper.usage.total_tokens)
逐请求用法跟踪
SDK 会自动跟踪 request_usage_entries 中的每个 API 请求的用法,这对于详细的成本计算和监控上下文窗口消耗非常有用。
result = await Runner.run(agent, "What's the weather in Tokyo?")
for i, request in enumerate(result.context_wrapper.usage.request_usage_entries):
print(f"Request {i + 1}: {request.input_tokens} in, {request.output_tokens} out")
使用会话访问用法
当您使用 Session(例如 SQLiteSession)时,每次调用 Runner.run(...) 都会返回该特定运行的用法。会话会维护对话历史记录以供上下文使用,但每次运行的用法都是独立的。
session = SQLiteSession("my_conversation")
first = await Runner.run(agent, "Hi!", session=session)
print(first.context_wrapper.usage.total_tokens) # Usage for first run
second = await Runner.run(agent, "Can you elaborate?", session=session)
print(second.context_wrapper.usage.total_tokens) # Usage for second run
请注意,虽然会话会在运行之间保留对话上下文,但每个 Runner.run() 调用返回的用法指标仅代表该特定执行。在会话中,之前的消息可能会被重新输入到每次运行中,这会影响后续轮次的输入 token 数量。
在钩子中使用用法
如果您正在使用 RunHooks,传递给每个钩子的 context 对象包含 usage。这使您可以在关键生命周期时刻记录用法。
class MyHooks(RunHooks):
async def on_agent_end(self, context: RunContextWrapper, agent: Agent, output: Any) -> None:
u = context.usage
print(f"{agent.name} → {u.requests} requests, {u.total_tokens} total tokens")
API 参考
有关详细的 API 文档,请参阅
Usage- 用法跟踪数据结构RequestUsage- 逐请求用法详情RunContextWrapper- 从运行上下文访问用法RunHooks- 钩入用法跟踪生命周期