令牌计数
LangChain提供了一个上下文管理器,允许您计算令牌数量。
import asyncio
from langchain.callbacks import get_openai_callback
from langchain.llms import OpenAI
llm = OpenAI(temperature=0)
with get_openai_callback() as cb:
llm("What is the square root of 4?")
total_tokens = cb.total_tokens
assert total_tokens > 0
with get_openai_callback() as cb:
llm("What is the square root of 4?")
llm("What is the square root of 4?")
assert cb.total_tokens == total_tokens * 2
# 您可以在上下文管理器内启动并发运行
with get_openai_callback() as cb:
await asyncio.gather(
*[llm.agenerate(["What is the square root of 4?"]) for _ in range(3)]
)
assert cb.total_tokens == total_tokens * 3
# 上下文管理器是并发安全的
task = asyncio.create_task(llm.agenerate(["What is the square root of 4?"]))
with get_openai_callback() as cb:
await llm.agenerate(["What is the square root of 4?"])
await task
assert cb.total_tokens == total_tokens
API参考:
- get_openai_callback 来自
langchain.callbacks
- OpenAI 来自
langchain.llms