-
Notifications
You must be signed in to change notification settings - Fork 1.6k
track token usage for each tool call in ChatAgent #3325
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
LIHUA919
wants to merge
3
commits into
camel-ai:master
Choose a base branch
from
LIHUA919:issue-3219-track-token-usage-per-tool-call
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -465,3 +465,4 @@ yarn-error.log* | |
|
|
||
| # Yarn Integrity file | ||
| .yarn-integrity | ||
| .env | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. try to test this example ,occur error ^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/suntao/Documents/GitHub/camel/camel/agents/chat_agent.py", line 3121, in _record_tool_calling
tool_record = ToolCallingRecord(
^^^^^^^^^^^^^^^^^^
File "/Users/suntao/Documents/GitHub/camel/.venv/lib/python3.12/site-packages/pydantic/main.py", line 250, in __init__
validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pydantic_core._pydantic_core.ValidationError: 2 validation errors for ToolCallingRecord
token_usage.completion_tokens_details
Input should be a valid integer [type=int_type, input_value={'accepted_prediction_tok...d_prediction_tokens': 0}, input_type=dict]
For further information visit https://errors.pydantic.dev/2.12/v/int_type
token_usage.prompt_tokens_details
Input should be a valid integer [type=int_type, input_value={'audio_tokens': 0, 'cached_tokens': 0}, input_type=dict]
For further information visit https://errors.pydantic.dev/2.12/v/int_type |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. ========= | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. ========= | ||
|
|
||
| """ | ||
| This example demonstrates how to track token usage for each individual tool | ||
| call in a ChatAgent step. | ||
|
|
||
| Starting from version 0.2.79, each ToolCallingRecord includes token_usage | ||
| information, allowing you to monitor the cost of each tool call separately. | ||
| """ | ||
|
|
||
| from camel.agents import ChatAgent | ||
| from camel.messages import BaseMessage | ||
| from camel.models import ModelFactory | ||
| from camel.toolkits import MathToolkit | ||
| from camel.types import ModelPlatformType, ModelType | ||
|
|
||
| # Create a ChatAgent with math tools | ||
| model = ModelFactory.create( | ||
| model_platform=ModelPlatformType.OPENAI, | ||
| model_type=ModelType.GPT_5_MINI, | ||
| ) | ||
|
|
||
| agent = ChatAgent( | ||
| system_message="You are a helpful math assistant.", | ||
| model=model, | ||
| tools=MathToolkit().get_tools(), | ||
| ) | ||
|
|
||
| # Send a message that will trigger multiple tool calls | ||
| user_message = BaseMessage.make_user_message( | ||
| role_name="User", | ||
| content="Calculate the result of (5 * 3) - 10", | ||
| ) | ||
|
|
||
| print("User:", user_message.content) | ||
| print("\n" + "=" * 60 + "\n") | ||
|
|
||
| # Step the agent | ||
| response = agent.step(user_message) | ||
|
|
||
| # Display the response | ||
| print("Assistant:", response.msgs[0].content) | ||
| print("\n" + "=" * 60 + "\n") | ||
|
|
||
| # Check tool calls and their token usage | ||
| if response.info.get('tool_calls'): | ||
| print("Tool Calls with Token Usage:") | ||
| print("-" * 60) | ||
|
|
||
| for i, tool_call in enumerate(response.info['tool_calls'], 1): | ||
| print(f"\nTool Call #{i}:") | ||
| print(f" Tool Name: {tool_call.tool_name}") | ||
| print(f" Arguments: {tool_call.args}") | ||
| print(f" Result: {tool_call.result}") | ||
|
|
||
| if tool_call.token_usage: | ||
| print(" Token Usage:") | ||
| prompt_tokens = tool_call.token_usage['prompt_tokens'] | ||
| completion_tokens = tool_call.token_usage['completion_tokens'] | ||
| total_tokens = tool_call.token_usage['total_tokens'] | ||
| print(f" - Prompt Tokens: {prompt_tokens}") | ||
| print(f" - Completion Tokens: {completion_tokens}") | ||
| print(f" - Total Tokens: {total_tokens}") | ||
| else: | ||
| print(" Token Usage: Not available") | ||
|
|
||
| print("\n" + "=" * 60 + "\n") | ||
|
|
||
| # Calculate total tokens across all tool calls | ||
| total_prompt = sum( | ||
| tc.token_usage['prompt_tokens'] | ||
| for tc in response.info['tool_calls'] | ||
| if tc.token_usage | ||
| ) | ||
| total_completion = sum( | ||
| tc.token_usage['completion_tokens'] | ||
| for tc in response.info['tool_calls'] | ||
| if tc.token_usage | ||
| ) | ||
| total_overall = sum( | ||
| tc.token_usage['total_tokens'] | ||
| for tc in response.info['tool_calls'] | ||
| if tc.token_usage | ||
| ) | ||
|
|
||
| print("Summary:") | ||
| print(f" Total Tool Calls: {len(response.info['tool_calls'])}") | ||
| print(f" Total Prompt Tokens: {total_prompt}") | ||
| print(f" Total Completion Tokens: {total_completion}") | ||
| print(f" Total Tokens (all tools): {total_overall}") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
i think after multiturn request
response.usage_dictcannot accurately represent the usage of a toolcall