跟踪AI代理API调用,分析token使用情况,优化成本。适用于监控大语言模型支出、调试API调用、跟踪token消耗等场景。
代理 Lens : 跟踪每个 AI API 的呼叫, 分析符号使用, 并优化成本是一项面向实际任务的技能,主要用于当用户: 使用时激活此技能;说“ 我花费多少 ” 、 “ 托肯使用 ” 、 “ API 成本 ”。
从功能定位来看,该技能强调把分散的操作要求整理成清晰、可复用的处理流程,使用户能够围绕既定目标快速准备输入、选择执行方式并获得结构化结果。实际使用前应先确认任务范围、数据来源、运行环境、必要权限和关键参数,再依据技能说明逐步执行;
若输入条件不完整,应先补齐信息或采用保守配置,避免因错误假设导致结果偏离需求。执行过程中需要关注工具调用是否成功、接口或依赖是否可用、输出格式是否符合预期,并对异常提示、缺失字段和边界情况进行处理;涉及批量任务时,还应保存进度,避免中断后重复操作。
追踪每一次 AI API 调用,分析 Token 使用量,并优化成本。
当用户出现以下情况时,启用该能力:
# 安装 pip install git+https://github.com/lrg913427-dot/agent-lens.git # 生成演示数据并立即查看效果 agent-lens demo # 查看统计信息 agent-lens stats agent-lens cost agent-lens recent
from agent_lens import AgentLens
lens = AgentLens(agent_name="my-agent")
@lens.track(model="gpt-4o")
def call_api(prompt):
return client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": prompt}],
)
# Token 使用量会自动从 OpenAI 风格的响应中提取
result = call_api("Hello")
from agent_lens import AgentLens
lens = AgentLens(agent_name="my-agent")
with lens.trace(model="claude-3.5-sonnet") as t:
result = client.chat.completions.create(...)
t.input_tokens = result.usage.prompt_tokens
t.output_tokens = result.usage.completion_tokens
from agent_lens import AgentLens
lens = AgentLens(agent_name="my-agent")
lens.record(
model="gpt-4o",
input_tokens=1500,
output_tokens=800,
latency_ms=2300,
)
from agent_lens import record, trace, track
record(model="gpt-4o", input_tokens=100, output_tokens=50)
with trace(model="gpt-4o") as t:
...
@track(model="gpt-4o")
def my_func():
...
| 命令 | 说明 |
|---|---|
agent-lens stats |
概览:总调用次数、Token 总数、总成本 |
agent-lens report --by model |
按模型 / 提供商 / Agent 分组的详细统计 |
agent-lens cost |
成本排名(含百分比条形图) |
agent-lens recent -n 10 |
最近 10 次 API 调用 |
agent-lens top |
成本最高的调用 |
agent-lens export --json |
导出为 JSON 格式 |
agent-lens export -o data.csv |
导出为 CSV 格式 |
agent-lens clean --before |
清理指定时间戳之前的历史数据 |
agent-lens demo |
生成示例数据 |
当用户询问“我该如何省钱”时:
agent-lens costagent-lens report --by statusimport tiktoken
def count_tokens(text: str, model: str = "gpt-4o") -> int:
"""统计指定模型下的 Token 数量。"""
try:
enc = tiktoken.encoding_for_model(model)
except KeyError:
enc = tiktoken.get_encoding("cl100k_base")
return len(enc.encode(text))
# 发送前校验
prompt = "Your long prompt here..."
tokens = count_tokens(prompt)
print(f"Prompt: {tokens} tokens")
print(f"Estimated cost: ${tokens * 2.50 / 1_000_000:.4f}")
已内置定价数据的模型:OpenAI(GPT-4o、o1、o3)、Anthropic(Claude 3.5/4)、Google(Gemini 2.x)、DeepSeek、Mistral、Qwen、GLM、MiMo。
未知模型仍可被追踪,但成本显示为“—”。
# 追踪 Hermes Agent 的 API 调用
from agent_lens import AgentLens
lens = AgentLens(agent_name="hermes-main")
# 在你的 Agent 循环中:
with lens.trace(model=config.model) as t:
response = agent.run_conversation(message)
t.input_tokens = response.get("input_tokens", 0)
t.output_tokens = response.get("output_tokens", 0)
使用 SQLite 存储于 ~/.agent-lens/traces.db。完全本地化,无需任何云服务。
t.input_tokens 和 t.output_tokensagent-lens cleanagent-lens demo # 生成 20 条示例记录 agent-lens stats # 应显示共 20 次调用 agent-lens cost # 应显示按模型划分的成本分布