🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
fix: Multi-round step running token count in ChatAgent (#2416)
Wendong-Fan1b106cfada50
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlindex b83360f03..80376a662 100644--- a/.github/ISSUE_TEMPLATE/bug_report.yml+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -26,7 +26,7 @@ body:attributes:label: What version of camel are you using?description: Run command `python3 -c 'print(__import__("camel").__version__)'` in your shell and paste the output here.- placeholder: E.g., 0.2.58+ placeholder: E.g., 0.2.59validations:required: truediff --git a/camel/__init__.py b/camel/__init__.pyindex a2b89f15f..8859b718d 100644--- a/camel/__init__.py+++ b/camel/__init__.py@@ -14,7 +14,7 @@from camel.logger import disable_logging, enable_logging, set_log_level-__version__ = '0.2.58'+__version__ = '0.2.59'__all__ = ['__version__',diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.pyindex e2ebca05d..dc6b3a2ad 100644--- a/camel/agents/chat_agent.py+++ b/camel/agents/chat_agent.py@@ -384,8 +384,7 @@ class ChatAgent(BaseAgent):# List of tuples (platform, type)resolved_models_list = []for model_spec in model_list:- # type: ignore[index]- platform, type_ = model_spec[0], model_spec[1]+ platform, type_ = model_spec[0], model_spec[1] # type: ignore[index]resolved_models_list.append(ModelFactory.create(model_platform=platform, model_type=type_@@ -759,9 +758,17 @@ class ChatAgent(BaseAgent):tool_call_records: List[ToolCallingRecord] = []external_tool_call_requests: Optional[List[ToolCallRequest]] = None+ accumulated_context_tokens = (+ 0 # This tracks cumulative context tokens, not API usage tokens+ )++ # Initialize token usage tracker+ step_token_usage = self._create_token_usage_tracker()+while True:try:openai_messages, num_tokens = self.memory.get_context()+ accumulated_context_tokens += num_tokensexcept RuntimeError as e:return self._step_terminate(e.args[1], tool_call_records, "max_tokens_exceeded"@@ -769,16 +776,23 @@ class ChatAgent(BaseAgent):# Get response from model backendresponse = self._get_model_response(openai_messages,- num_tokens,+ accumulated_context_tokens, # Cumulative context tokensresponse_format,self._get_full_tool_schemas(),)+ # Accumulate API token usage+ self._update_token_usage_tracker(+ step_token_usage, response.usage_dict+ )+# Terminate Agent if stop_event is setif self.stop_event and self.stop_event.is_set():# Use the _step_terminate to terminate the agent with reasonreturn self._step_terminate(- num_tokens, tool_call_records, "termination_triggered"+ accumulated_context_tokens,+ tool_call_records,+ "termination_triggered",)if tool_call_requests := response.tool_call_requests:@@ -814,8 +828,11 @@ class ChatAgent(BaseAgent):return self._convert_to_chatagent_response(response,tool_call_records,- num_tokens,+ accumulated_context_tokens,external_tool_call_requests,+ step_token_usage["prompt_tokens"],+ step_token_usage["completion_tokens"],+ step_token_usage["total_tokens"],)@property@@ -858,9 +875,16 @@ class ChatAgent(BaseAgent):tool_call_records: List[ToolCallingRecord] = []external_tool_call_requests: Optional[List[ToolCallRequest]] = None+ accumulated_context_tokens = (+ 0 # This tracks cumulative context tokens, not API usage tokens+ )++ # Initialize token usage tracker+ step_token_usage = self._create_token_usage_tracker()while True:try:openai_messages, num_tokens = self.memory.get_context()+ accumulated_context_tokens += num_tokensexcept RuntimeError as e:return self._step_terminate(e.args[1], tool_call_records, "max_tokens_exceeded"@@ -868,7 +892,7 @@ class ChatAgent(BaseAgent):response = await self._aget_model_response(openai_messages,- num_tokens,+ accumulated_context_tokens,response_format,self._get_full_tool_schemas(),)@@ -877,7 +901,9 @@ class ChatAgent(BaseAgent):if self.stop_event and self.stop_event.is_set():# Use the _step_terminate to terminate the agent with reasonreturn self._step_terminate(- num_tokens, tool_call_records, "termination_triggered"+ accumulated_context_tokens,+ tool_call_records,+ "termination_triggered",)if tool_call_requests := response.tool_call_requests:@@ -911,28 +937,68 @@ class ChatAgent(BaseAgent):await self._aformat_response_if_needed(response, response_format)self._record_final_output(response.output_messages)+ # Create token usage tracker for this step+ step_token_usage = self._create_token_usage_tracker()++ # Update with response usage+ self._update_token_usage_tracker(step_token_usage, response.usage_dict)+return self._convert_to_chatagent_response(response,tool_call_records,- num_tokens,+ accumulated_context_tokens,external_tool_call_requests,+ step_token_usage["prompt_tokens"],+ step_token_usage["completion_tokens"],+ step_token_usage["total_tokens"],)+ def _create_token_usage_tracker(self) -> Dict[str, int]:+ r"""Creates a fresh token usage tracker for a step.++ Returns:+ Dict[str, int]: A dictionary for tracking token usage.+ """+ return {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}++ def _update_token_usage_tracker(+ self, tracker: Dict[str, int], usage_dict: Dict[str, int]+ ) -> None:+ r"""Updates a token usage tracker with values from a usage dictionary.++ Args:+ tracker (Dict[str, int]): The token usage tracker to update.+ usage_dict (Dict[str, int]): The usage dictionary with new values.+ """+ tracker["prompt_tokens"] += usage_dict.get("prompt_tokens", 0)+ tracker["completion_tokens"] += usage_dict.get("completion_tokens", 0)+ tracker["total_tokens"] += usage_dict.get("total_tokens", 0)+def _convert_to_chatagent_response(self,response: ModelResponse,tool_call_records: List[ToolCallingRecord],- num_tokens: int,+ num_tokens: int, # Context tokens from the last call in stepexternal_tool_call_requests: Optional[List[ToolCallRequest]],+ step_api_prompt_tokens: int = 0,+ step_api_completion_tokens: int = 0,+ step_api_total_tokens: int = 0,) -> ChatAgentResponse:r"""Parse the final model response into the chat agent response."""+ # Create usage_dict for the current step's API calls+ step_api_usage_dict = {+ "prompt_tokens": step_api_prompt_tokens,+ "completion_tokens": step_api_completion_tokens,+ "total_tokens": step_api_total_tokens,+ }+info = self._step_get_info(response.output_messages,response.finish_reasons,- response.usage_dict,+ step_api_usage_dict, # Pass step-specific API usage hereresponse.response_id,tool_call_records,- num_tokens,+ num_tokens, # This is context tokens, not API usageexternal_tool_call_requests,)diff --git a/docs/conf.py b/docs/conf.pyindex d51fdaf1d..d666b7b87 100644--- a/docs/conf.py+++ b/docs/conf.py@@ -27,7 +27,7 @@ sys.path.insert(0, os.path.abspath('..'))project = 'CAMEL'copyright = '2024, CAMEL-AI.org'author = 'CAMEL-AI.org'-release = '0.2.58'+release = '0.2.59'html_favicon = ('https://raw.githubusercontent.com/camel-ai/camel/master/misc/favicon.png'diff --git a/docs/key_modules/loaders.md b/docs/key_modules/loaders.mdindex 38e8e7aea..80ed8e232 100644--- a/docs/key_modules/loaders.md+++ b/docs/key_modules/loaders.md@@ -357,14 +357,14 @@ print(response)``````markdown->>>Welcome to CAMEL’s documentation! — CAMEL 0.2.58 documentation+>>>Welcome to CAMEL’s documentation! — CAMEL 0.2.59 documentation===============[Skip to main content](https://docs.camel-ai.org/#main-content)Back to top Ctrl+K- [ CAMEL 0.2.58](https://docs.camel-ai.org/#)+ [ CAMEL 0.2.59](https://docs.camel-ai.org/#)Search Ctrl+Kdiff --git a/pyproject.toml b/pyproject.tomlindex 98841e7f4..33a35b89f 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "camel-ai"-version = "0.2.58"+version = "0.2.59"description = "Communicative Agents for AI Society Study"authors = [{ name = "CAMEL-AI.org" }]requires-python = ">=3.10,<3.13"diff --git a/uv.lock b/uv.lockindex 8d6fc71d6..266b62da0 100644--- a/uv.lock+++ b/uv.lock@@ -555,7 +555,7 @@ wheels = [[[package]]name = "camel-ai"-version = "0.2.58"+version = "0.2.59"source = { editable = "." }dependencies = [{ name = "colorama" },