Published: 24 Jun 2025 › Updated: 24 Jun 2025
Agent开发,如何统计总的token的使用 / ai #47
https://langchain-ai.github.io/langgraph/
Agent中会涉及多次的大模型调用,在实际的生产应用中又要如何计算token的使用呢?
查了下技术文档, 使用的是一个get_openai_callback的函数来统计token用量。简单的语法如下:
from langchain_community.callbacks.manager import get_openai_callback
llm = ChatOpenAI(
model="gpt-4o-mini",
temperature=0,
stream_usage=True,
)
with get_openai_callback() as cb:
result = llm.invoke("Tell me a joke")
print(cb)
//Tokens Used: 27
Prompt Tokens: 11
Completion Tokens: 16
Successful Requests: 1
Total Cost (USD): $2.95e-05
使用这个callback函数就可以很方便地统计token用量,也算是解决了一个问题点。
在Agent中也可以测试使用下:
with get_openai_callback() as cb:
result = graph.invoke({"messages":["How's the weather in Beijing"]})
print(668, result)
print(236, cb)
print(569, cb.total_tokens)
//236 Tokens Used: 3715
Prompt Tokens: 3560
Prompt Tokens Cached: 0
Completion Tokens: 155
Reasoning Tokens: 0
Successful Requests: 6
Total Cost (USD): $0.0006269999999999998
569 3715
AIJoe 也将上线Agent的相关应用,敬请期待!
Leave Agent开发,如何统计总的token的使用 / ai #47 to:
Read more #cn posts
Best Posts From lemooljiang
We have not curated any of lemooljiang's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.
More Posts From lemooljiang
- DeepTutor:AI个性化辅导平台 / ai #57
- ComfyUI:可编程和自动化的PS / ai #56
- 将Neo4j封装进Agent / ai #55
- 闲鱼省钱大法:极限0.5折!
- 对Neo4j批量导入结构化数据 / ai #54
- langchain对neo4j进行交互,写入和查询数据 / ai #53
- 知识图谱和图数据库Neo4j的作用和使用场景 / ai #52
- SpaceX、美股和比特币
- 又是币圈血洗日!
- 链股合流,当币安也开始卖股票啰
- 天涯社区重启,爷青回?
- 诺基亚在AI时代重新杀回来啦
- 《2049:未来10000天的可能》书中的镜像世界为什么不叫元宇宙
- 今天适合吃披萨
- 开通即被封,别再给Claude送人头了!
- 两根内存条引发的“官司”
- AI·Joe V12更新, 更新GPT-5.5和DeepSeek V4 等
- 中医进校园活动反响热烈
- 猪价低伤农,猪价贵伤民
- Solidity开发指南