Replies: 1 comment 7 replies
-
Hello @FawazSapa! I'm here to help you with your GitHub issue. If you need assistance, just let me know! To get token usage and cost information from a LangGraph-based implementation of an OpenAI model, you can use the
Here is the updated code: from langchain_core.messages import HumanMessage
from langchain_community.callbacks.openai_info import OpenAICallbackHandler
# Initialize the callback handler
callback_handler = OpenAICallbackHandler()
inputs = {
"messages": [
HumanMessage(
content='Can you delete the user with email mike@gmail.com.'
)
]
}
# Use the Runnable to get the final state with the callback handler
final_state = app.invoke(
inputs,
config={"configurable": {"thread_id": 42}},
callbacks=[callback_handler] # Pass the callback handler here
)
# Print the final response
print(final_state)
# Access and print the token usage information
print(f"Total Tokens Used: {callback_handler.total_tokens}")
print(f"Prompt Tokens: {callback_handler.prompt_tokens}")
print(f"Completion Tokens: {callback_handler.completion_tokens}")
print(f"Successful Requests: {callback_handler.successful_requests}")
print(f"Total Cost (USD): ${callback_handler.total_cost}") This approach ensures that the |
Beta Was this translation helpful? Give feedback.
7 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Checked other resources
Commit to Help
Example Code
Description
I have developed a tool utilizing OpenAI’s GPT-3.5-turbo-1106, integrated with LangSmith and LangGraph. I am looking to implement a feature that limits the usage of my bot based on a certain cost threshold for OpenAI API calls.
The final_state doesn’t provide any information regarding tokens, unlike the documentation that used the metadata from the response.
I tried using get_openai_callback function but it didnt work either.
How do I get to know the tokens usage per api?
System Info
langchain==0.2.11
langchain-community==0.2.10
langchain-core==0.2.23
langchain-openai==0.1.17
langchain-text-splitters==0.2.2
Beta Was this translation helpful? Give feedback.
All reactions