lemooljiang avatar

Agent开发,如何统计总的token的使用 / ai #47

lemooljiang

Published: 24 Jun 2025 › Updated: 24 Jun 2025

Agent开发,如何统计总的token的使用 / ai #47

langgraph3.jpg
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:

Written by

Designer , Poet , Technology enthusiasts

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