令牌使用量与成本监控
实时衡量代理消耗的令牌数量及其成本,设置预算,并找出高成本步骤,以便优化生产环境中的支出。
令牌使用量与成本监控 是 CoddyKit 上的免费 AI Agents with LangChain & Autonomous Workflows 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Agents with LangChain & Autonomous Workflows 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Agents with LangChain & Autonomous Workflows 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Track Tokens and Cost
Agents that loop, retry, or use long context can quietly become expensive. Without visibility you only discover the bill at month end.
Token and cost monitoring turns spend into a metric you can watch, alert on, and optimize.
Prompt vs Completion Tokens
Every call splits into:
- Prompt tokens: everything you send in (system prompt, context, history)
- Completion tokens: what the model generates
They are usually priced differently, so track them separately.
The Callback Approach
LangChain exposes usage via callbacks. get_openai_callback aggregates tokens and cost for everything inside its context block.
from langchain_community.callbacks import get_openai_callback
with get_openai_callback() as cb:
result = agent.invoke({'input': 'Summarize the report'})
print(cb.total_tokens, cb.total_cost)Reading the Breakdown
The callback object also exposes the split, which is what you log per request.
print('prompt:', cb.prompt_tokens)
print('completion:', cb.completion_tokens)
print('cost USD:', cb.total_cost)Usage Inside Responses
Many chat models also attach a usage_metadata field to the response, useful when you call the model directly without a callback.
resp = llm.invoke('Hello there')
print(resp.usage_metadata)Estimating Before You Send
To stay under a budget, estimate tokens before calling the model using a tokenizer like tiktoken. This catches oversized prompts early.
import tiktoken
enc = tiktoken.encoding_for_model('gpt-4o-mini')
n = len(enc.encode(prompt_text))
print('approx tokens:', n)Setting Budgets
Define a per-request and per-user token budget. If an estimate exceeds it, trim context, lower k in retrieval, or reject the request before paying for it.
MAX_TOKENS = 6000
if n > MAX_TOKENS:
raise ValueError('Request exceeds token budget')Per-Step Attribution
Agents make many sub-calls: tool selection, tool output processing, final answer. Wrapping each step's callback shows which step dominates cost, so you optimize the right one.
Logging to a Dashboard
Emit tokens and cost as structured logs or metrics (e.g. to Prometheus or LangSmith). Tag them with user, model, and route so you can slice spend.
log.info('llm_usage', extra={
'tokens': cb.total_tokens,
'cost': cb.total_cost,
'route': 'support_agent'
})Common Savings
Once you can see spend, the biggest wins are usually:
- Smaller models for simple steps
- Caching repeated calls
- Trimming history and retrieved context
- Stopping runaway agent loops with iteration limits
Alerting on Anomalies
Set alerts for sudden cost spikes — often a sign of a prompt-injection loop or a misbehaving tool. Catching it in minutes beats finding it on the invoice.
Quick Check
Test your cost monitoring knowledge.
Recap
You learned to observe agent spend:
- Split prompt vs completion tokens
- Use
get_openai_callbackandusage_metadata - Estimate with
tiktokenand enforce budgets - Attribute cost per agent step
- Log to dashboards and alert on spikes
Visibility into cost is the foundation for optimizing production agents.
常见问题解答
「令牌使用量与成本监控」课时是免费的吗?
是的 — 「令牌使用量与成本监控」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Agents with LangChain & Autonomous Workflows 课程的其余内容,请升级到 CoddyKit PRO。 AI Agents with LangChain & Autonomous Workflows 课程共包含 4 节课。
「令牌使用量与成本监控」这节课中我会学到什么?
实时衡量代理消耗的令牌数量及其成本,设置预算,并找出高成本步骤,以便优化生产环境中的支出。 你通过在浏览器中直接运行的动手代码来练习 AI Agents with LangChain & Autonomous Workflows,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 AI Agents with LangChain & Autonomous Workflows 需要有经验吗?
无需任何先前经验。CoddyKit 上的 AI Agents with LangChain & Autonomous Workflows 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「令牌使用量与成本监控」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 AI Agents with LangChain & Autonomous Workflows 课中编写并运行代码吗?
能。每节 AI Agents with LangChain & Autonomous Workflows 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 使用 LangSmith 进行追踪与监控
- 调试智能体的思考过程
- 评估智能体性能
- 令牌使用量与成本监控