Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

fix: token counting issues in ChatAgent context management (#3635)

Wendong-Fan10e459c7f56e
diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.py
index c974122e6..9dedb180c 100644
--- a/camel/agents/chat_agent.py
+++ b/camel/agents/chat_agent.py
@@ -70,7 +70,6 @@ from camel.logger import get_logger
from camel.memories import (
AgentMemory,
ChatHistoryMemory,
- ContextRecord,
MemoryRecord,
ScoreBasedContextCreator,
)
@@ -107,16 +106,6 @@ from camel.utils.commons import dependencies_required
from camel.utils.context_utils import ContextUtility
from camel.utils.tool_result import ToolResult
-TOKEN_LIMIT_ERROR_MARKERS = (
- "context_length_exceeded",
- "prompt is too long",
- "exceeded your current quota",
- "tokens must be reduced",
- "context length",
- "token count",
- "context limit",
-)
-
if TYPE_CHECKING:
from camel.terminators import ResponseTerminator
@@ -533,24 +522,24 @@ class ChatAgent(BaseAgent):
self._tool_output_history: List[_ToolOutputHistoryEntry] = []
# Set up memory
- # Use user-provided token_limit if valid, otherwise use model's default
model_token_limit = self.model_backend.token_limit
- if token_limit is not None and token_limit > model_token_limit:
- logger.warning(
- f"Provided token_limit ({token_limit}) exceeds model's "
- f"maximum capacity ({model_token_limit}). "
- f"Using model's token_limit instead."
- )
- effective_token_limit = (
- min(token_limit, model_token_limit)
- if token_limit is not None
- else model_token_limit
- )
+ if token_limit is not None:
+ if token_limit > model_token_limit:
+ logger.warning(
+ f"Provided token_limit ({token_limit}) exceeds model's "
+ f"limit ({model_token_limit}). Using model's limit."
+ )
+ effective_token_limit = model_token_limit
+ else:
+ effective_token_limit = token_limit
+ else:
+ effective_token_limit = model_token_limit
context_creator = ScoreBasedContextCreator(
self.model_backend.token_counter,
effective_token_limit,
)
self._token_limit = effective_token_limit
+ self._summary_token_count = 0
self._memory: AgentMemory = memory or ChatHistoryMemory(
context_creator,
@@ -587,7 +576,6 @@ class ChatAgent(BaseAgent):
f"{summarize_threshold}% of the total token limit."
)
self.summarize_threshold = summarize_threshold
- self._reset_summary_state()
# Set up role name and role type
self.role_name: str = (
@@ -638,17 +626,39 @@ class ChatAgent(BaseAgent):
self.stream_accumulate = stream_accumulate
self._last_tool_call_record: Optional[ToolCallingRecord] = None
self._last_tool_call_signature: Optional[str] = None
- self._last_token_limit_tool_signature: Optional[str] = None
self.summary_window_ratio = summary_window_ratio
def reset(self):
r"""Resets the :obj:`ChatAgent` to its initial state."""
self.terminated = False
self.init_messages()
- self._reset_summary_state()
for terminator in self.response_terminators:
terminator.reset()
+ def _update_token_cache(
+ self,
+ usage_dict: Dict[str, Any],
+ message_count: int,
+ ) -> None:
+ r"""Update the token count cache from LLM response usage.
+
+ Args:
+ usage_dict (Dict[str, Any]): Usage dictionary from LLM response.
+ message_count (int): Number of messages sent to the LLM.
+ """
+ prompt_tokens = usage_dict.get("prompt_tokens", 0)
+ completion_tokens = usage_dict.get("completion_tokens", 0)
+
+ if prompt_tokens == 0:
+ return
+
+ total_tokens = prompt_tokens + completion_tokens
+ context_creator = self.memory.get_context_creator()
+ if hasattr(context_creator, 'set_cached_token_count'):
+ context_creator.set_cached_token_count(
+ total_tokens, message_count + 1
+ )
+
def _resolve_models(
self,
model: Optional[
@@ -857,122 +867,6 @@ class ChatAgent(BaseAgent):
for func_tool in self._internal_tools.values()
]
- @staticmethod
- def _is_token_limit_error(error: Exception) -> bool:
- r"""Return True when the exception message indicates a token limit."""
- error_message = str(error).lower()
- return any(
- marker in error_message for marker in TOKEN_LIMIT_ERROR_MARKERS
- )
-
- @staticmethod
- def _is_tool_related_record(record: MemoryRecord) -> bool:
- r"""Determine whether the given memory record
- belongs to a tool call."""
- if record.role_at_backend in {
- OpenAIBackendRole.TOOL,
- OpenAIBackendRole.FUNCTION,
- }:
- return True
-
- if (
- record.role_at_backend == OpenAIBackendRole.ASSISTANT
- and isinstance(record.message, FunctionCallingMessage)
- ):
- return True
-
- return False
-
- def _find_indices_to_remove_for_last_tool_pair(
- self, recent_records: List[ContextRecord]
- ) -> List[int]:
- """Find indices of records that should be removed to clean up the most
- recent incomplete tool interaction pair.
-
- This method identifies tool call/result pairs by tool_call_id and
- returns the exact indices to remove, allowing non-contiguous deletions.
-
- Logic:
- - If the last record is a tool result (TOOL/FUNCTION) with a
- tool_call_id, find the matching assistant call anywhere in history
- and return both indices.
- - If the last record is an assistant tool call without a result yet,
- return just that index.
- - For normal messages (non tool-related): remove just the last one.
- - Fallback: If no tool_call_id is available, use heuristic (last 2 if
- tool-related, otherwise last 1).
-
- Returns:
- List[int]: Indices to remove (may be non-contiguous).
- """
- if not recent_records:
- return []
-
- last_idx = len(recent_records) - 1
- last_record = recent_records[last_idx].memory_record
-
- # Case A: Last is an ASSISTANT tool call with no result yet
- if (
- last_record.role_at_backend == OpenAIBackendRole.ASSISTANT
- and isinstance(last_record.message, FunctionCallingMessage)
- and last_record.message.result is None
- ):
- return [last_idx]
-
- # Case B: Last is TOOL/FUNCTION result, try id-based pairing
- if last_record.role_at_backend in {
- OpenAIBackendRole.TOOL,
- OpenAIBackendRole.FUNCTION,
- }:
- tool_id = None
- if isinstance(last_record.message, FunctionCallingMessage):
- tool_id = last_record.message.tool_call_id
-
- if tool_id:
- for idx in range(len(recent_records) - 2, -1, -1):
- rec = recent_records[idx].memory_record
- if rec.role_at_backend != OpenAIBackendRole.ASSISTANT:
- continue
-
- # Check if this assistant message contains the tool_call_id
- matched = False
-
- # Case 1: FunctionCallingMessage (single tool call)
- if isinstance(rec.message, FunctionCallingMessage):
- if rec.message.tool_call_id == tool_id:
- matched = True
-
- # Case 2: BaseMessage with multiple tool_calls in meta_dict
- elif (
- hasattr(rec.message, "meta_dict")
- and rec.message.meta_dict
- ):
- tool_calls_list = rec.message.meta_dict.get(
- "tool_calls", []
- )
- if isinstance(tool_calls_list, list):
- for tc in tool_calls_list:
- if (
- isinstance(tc, dict)
- and tc.get("id") == tool_id
- ):
- matched = True
- break
-
- if matched:
- # Return both assistant call and tool result indices
- return [idx, last_idx]
-
- # Fallback: no tool_call_id, use heuristic
- if self._is_tool_related_record(last_record):
- # Remove last 2 (assume they are paired)
- return [last_idx - 1, last_idx] if last_idx > 0 else [last_idx]
- else:
- return [last_idx]
-
- # Default: non tool-related tail => remove last one
- return [last_idx]
-
@staticmethod
def _serialize_tool_args(args: Dict[str, Any]) -> str:
try:
@@ -1015,39 +909,6 @@ class ChatAgent(BaseAgent):
signature = None
self._last_tool_call_signature = signature
- def _format_tool_limit_notice(self) -> Optional[str]:
- record = self._last_tool_call_record
- description = self._describe_tool_call(record)
- if description is None:
- return None
- notice_lines = [
- "[Tool Call Causing Token Limit]",
- description,
- ]
-
- if record is not None:
- result = record.result
- if isinstance(result, bytes):
- result_repr = result.decode(errors="replace")
- elif isinstance(result, str):
- result_repr = result
- else:
- try:
- result_repr = json.dumps(
- result, ensure_ascii=False, sort_keys=True
- )
- except (TypeError, ValueError):
- result_repr = str(result)
-
- result_length = len(result_repr)
- notice_lines.append(f"Tool result length: {result_length}")
- if self.model_backend.token_limit != 999999999:
- notice_lines.append(
- f"Token limit: {self.model_backend.token_limit}"
- )
-
- return "\n".join(notice_lines)
-
@staticmethod
def _append_user_messages_section(
summary_content: str, user_messages: List[str]
@@ -1075,21 +936,104 @@ class ChatAgent(BaseAgent):
def _reset_summary_state(self) -> None:
self._summary_token_count = 0 # Total tokens in summary messages
+ def _get_context_with_summarization(
+ self,
+ ) -> Tuple[List[OpenAIMessage], int]:
+ r"""Get context and trigger summarization if needed."""
+ openai_messages, num_tokens = self.memory.get_context()
+
+ if self.summarize_threshold is None or num_tokens > self.token_limit:
+ return openai_messages, num_tokens
+
+ summary_token_count = self._summary_token_count
+
+ if summary_token_count > self.token_limit * self.summary_window_ratio:
+ logger.warning(
+ f"Summary tokens ({summary_token_count}) "
+ f"exceed limit, full compression."
+ )
+ summary = self.summarize(include_summaries=True)
+ self._update_memory_with_summary(
+ summary.get("summary", ""), include_summaries=True
+ )
+ return self.memory.get_context()
+
+ threshold = self._calculate_next_summary_threshold()
+ if num_tokens > threshold:
+ logger.warning(
+ f"Token count ({num_tokens}) exceed threshold "
+ f"({threshold}). Triggering summarization."
+ )
+ summary = self.summarize(include_summaries=False)
+ self._update_memory_with_summary(
+ summary.get("summary", ""), include_summaries=False
+ )
+ return self.memory.get_context()
+
+ return openai_messages, num_tokens
+
+ async def _get_context_with_summarization_async(
+ self,
+ ) -> Tuple[List[OpenAIMessage], int]:
+ r"""Async version: get context and trigger summarization if needed."""
+ openai_messages, num_tokens = self.memory.get_context()
+
+ if self.summarize_threshold is None or num_tokens > self.token_limit:
+ return openai_messages, num_tokens
+
+ summary_token_count = self._summary_token_count
+
+ if summary_token_count > self.token_limit * self.summary_window_ratio:
+ logger.warning(
+ f"Summary tokens ({summary_token_count}) "
+ f"exceed limit, full compression."
+ )
+ summary = await self.asummarize(include_summaries=True)
+ self._update_memory_with_summary(
+ summary.get("summary", ""), include_summaries=True
+ )
+ return self.memory.get_context()
+
+ threshold = self._calculate_next_summary_threshold()
+ if num_tokens > threshold:
+ logger.warning(
+ f"Token count ({num_tokens}) exceed threshold "
+ f"({threshold}). Triggering summarization."
+ )
+ summary = await self.asummarize(include_summaries=False)
+ self._update_memory_with_summary(
+ summary.get("summary", ""), include_summaries=False
+ )
+ return self.memory.get_context()
+
+ return openai_messages, num_tokens
+
def _calculate_next_summary_threshold(self) -> int:
r"""Calculate the next token threshold that should trigger
summarization.
The threshold calculation follows a progressive strategy:
- - First time: token_limit * (summarize_threshold / 100)
- - Subsequent times: (limit - summary_token) / 2 + summary_token
+ - First time (or after full compression):
+ token_limit * (summarize_threshold / 100)
+ - After progressive compression:
+ (token_limit - summary_tokens) * (summarize_threshold / 100)
+ + summary_tokens
- This ensures that as summaries accumulate, the threshold adapts
- to maintain a reasonable balance between context and summaries.
+ This ensures that as summaries accumulate through progressive
+ compression, the threshold adapts to maintain a reasonable balance
+ between context and summaries. After full compression, the threshold
+ resets to the initial value to prevent frequent re-summarization.
Returns:
int: The token count threshold for next summarization.
"""
- token_limit = self.model_backend.token_limit
+ if self.summarize_threshold is None:
+ raise ValueError(
+ "Cannot calculate summary threshold when "
+ "summarize_threshold is None"
+ )
+
+ token_limit = self.token_limit
summary_token_count = self._summary_token_count
# First summarization: use the percentage threshold
@@ -1132,8 +1076,7 @@ class ChatAgent(BaseAgent):
):
existing_summaries.append(msg)
- # Clear memory
- self.clear_memory()
+ self.clear_memory(reset_summary_state=False)
# Restore old summaries (for progressive compression)
for old_summary in existing_summaries:
@@ -1152,25 +1095,22 @@ class ChatAgent(BaseAgent):
self.update_memory(new_summary_msg, OpenAIBackendRole.ASSISTANT)
# Restore last user message to maintain conversation structure
+ # The summary already contains all user messages, but we keep the
+ # latest one so the model knows what to respond to
if last_user_message:
- if not last_user_message.startswith("[Previous Request]"):
- last_user_message = f"[Previous Request] {last_user_message}"
+ # Avoid duplicate prefix - check if already prefixed
+ context_prefix = (
+ "Based on the previous CONTEXT_SUMMARY, "
+ "continue with my current message: "
+ )
+ if not last_user_message.startswith(context_prefix):
+ last_user_message = f"{context_prefix}{last_user_message}"
user_msg = BaseMessage.make_user_message(
role_name="user",
content=last_user_message,
)
self.update_memory(user_msg, OpenAIBackendRole.USER)
- # Add continuation prompt to guide the model
- continue_msg = BaseMessage.make_assistant_message(
- role_name="assistant",
- content=(
- "I'll continue working on this request based on the "
- "context summary above."
- ),
- )
- self.update_memory(continue_msg, OpenAIBackendRole.ASSISTANT)
-
# Update token count
try:
summary_tokens = (
@@ -1179,13 +1119,15 @@ class ChatAgent(BaseAgent):
)
)
- if include_summaries: # Full compression - reset count
+ if (
+ include_summaries
+ ): # Full compression - reset and set to new summary tokens only
self._summary_token_count = summary_tokens
logger.info(
f"Full compression: Summary with {summary_tokens} tokens. "
- f"Total summary tokens reset to: {summary_tokens}"
+ f"Total summary tokens set to: {summary_tokens}"
)
- else: # Progressive compression - accumulate
+ else: # Progressive compression - accumulate on existing count
self._summary_token_count += summary_tokens
logger.info(
f"Progressive compression: New summary "
@@ -1233,8 +1175,13 @@ class ChatAgent(BaseAgent):
- A boolean indicating whether truncation occurred
"""
serialized = self._serialize_tool_result(result)
- # Leave 10% room for system message, user input, and model response
- max_tokens = int(self.model_backend.token_limit * 0.9)
+ # Use summarize_threshold if set, otherwise default to 90%
+ threshold_ratio = (
+ min(0.9, self.summarize_threshold / 100)
+ if self.summarize_threshold is not None
+ else 0.9
+ )
+ max_tokens = int(self.token_limit * threshold_ratio)
result_tokens = self._get_token_count(serialized)
if result_tokens <= max_tokens:
@@ -1781,6 +1728,7 @@ class ChatAgent(BaseAgent):
),
model=self.model_backend,
agent_id=f"{self.agent_id}_context_summarizer",
+ token_limit=self.token_limit,
summarize_threshold=None,
)
else:
@@ -2073,6 +2021,8 @@ class ChatAgent(BaseAgent):
),
model=self.model_backend,
agent_id=f"{self.agent_id}_context_summarizer",
+ token_limit=self.token_limit,
+ summarize_threshold=None,
)
else:
self._context_summary_agent.reset()
@@ -2216,6 +2166,7 @@ class ChatAgent(BaseAgent):
),
model=self.model_backend,
agent_id=f"{self.agent_id}_context_summarizer",
+ token_limit=self.token_limit,
summarize_threshold=None,
)
else:
@@ -2359,14 +2310,24 @@ class ChatAgent(BaseAgent):
result["status"] = error_message
return result
- def clear_memory(self) -> None:
+ def clear_memory(self, reset_summary_state: bool = True):
r"""Clear the agent's memory and reset to initial state.
- Returns:
- None
+ Args:
+ reset_summary_state (bool): Whether to reset the summary token
+ count. Set to False when preserving summary state during
+ summarization. Defaults to True for full memory clearing.
"""
self.memory.clear()
+ if reset_summary_state:
+ self._reset_summary_state()
+
+ # Reset token cache when memory is cleared
+ context_creator = self.memory.get_context_creator()
+ if hasattr(context_creator, 'clear_cache'):
+ context_creator.clear_cache()
+
if self.system_message is not None:
self.memory.write_record(
MemoryRecord(
@@ -2406,7 +2367,6 @@ class ChatAgent(BaseAgent):
r"""Initializes the stored messages list with the current system
message.
"""
- self._reset_summary_state()
self.clear_memory()
def update_system_message(
@@ -2734,7 +2694,6 @@ class ChatAgent(BaseAgent):
# Explicitly set the tools to empty list to avoid calling tools
response = self._get_model_response(
openai_messages=[openai_message],
- num_tokens=0,
response_format=response_format,
tool_schemas=[],
prev_num_openai_messages=0,
@@ -2766,7 +2725,6 @@ class ChatAgent(BaseAgent):
openai_message: OpenAIMessage = {"role": "user", "content": prompt}
response = await self._aget_model_response(
openai_messages=[openai_message],
- num_tokens=0,
response_format=response_format,
tool_schemas=[],
prev_num_openai_messages=0,
@@ -2886,122 +2844,24 @@ class ChatAgent(BaseAgent):
time.sleep(0.001)
try:
- openai_messages, num_tokens = self.memory.get_context()
- if self.summarize_threshold is not None:
- threshold = self._calculate_next_summary_threshold()
- summary_token_count = self._summary_token_count
- token_limit = self.model_backend.token_limit
-
- if num_tokens <= token_limit:
- if (
- summary_token_count
- > token_limit * self.summary_window_ratio
- ):
- logger.info(
- f"Summary tokens ({summary_token_count}) "
- f"exceed limit, full compression."
- )
- # Summarize everything (including summaries)
- summary = self.summarize(include_summaries=True)
- self._update_memory_with_summary(
- summary.get("summary", ""),
- include_summaries=True,
- )
- elif num_tokens > threshold:
- logger.info(
- f"Token count ({num_tokens}) exceed threshold "
- f"({threshold}). Triggering summarization."
- )
- # Only summarize non-summary content
- summary = self.summarize(include_summaries=False)
- self._update_memory_with_summary(
- summary.get("summary", ""),
- include_summaries=False,
- )
+ openai_messages, num_tokens = (
+ self._get_context_with_summarization()
+ )
accumulated_context_tokens += num_tokens
except RuntimeError as e:
return self._step_terminate(
e.args[1], tool_call_records, "max_tokens_exceeded"
)
- # Get response from model backend with token limit error handling
- try:
- response = self._get_model_response(
- openai_messages,
- num_tokens=num_tokens,
- current_iteration=iteration_count,
- response_format=response_format,
- tool_schemas=[]
- if disable_tools
- else self._get_full_tool_schemas(),
- prev_num_openai_messages=prev_num_openai_messages,
- )
- except Exception as exc:
- logger.exception("Model error: %s", exc)
-
- if self._is_token_limit_error(exc):
- tool_signature = self._last_tool_call_signature
- if (
- tool_signature is not None
- and tool_signature
- == self._last_token_limit_tool_signature
- ):
- description = self._describe_tool_call(
- self._last_tool_call_record
- )
- repeated_msg = (
- "Context exceeded again by the same tool call."
- )
- if description:
- repeated_msg += f" {description}"
- raise RuntimeError(repeated_msg) from exc
-
- user_message_count = sum(
- 1
- for msg in openai_messages
- if getattr(msg, "role", None) == "user"
- )
- if (
- user_message_count == 1
- and getattr(openai_messages[-1], "role", None)
- == "user"
- ):
- raise RuntimeError(
- "The provided user input alone exceeds the "
- "context window. Please shorten the input."
- ) from exc
-
- logger.warning(
- "Token limit exceeded error detected. "
- "Summarizing context."
- )
-
- recent_records: List[ContextRecord]
- try:
- recent_records = self.memory.retrieve()
- except Exception: # pragma: no cover - defensive guard
- recent_records = []
-
- indices_to_remove = (
- self._find_indices_to_remove_for_last_tool_pair(
- recent_records
- )
- )
- self.memory.remove_records_by_indices(indices_to_remove)
-
- summary = self.summarize(include_summaries=False)
- tool_notice = self._format_tool_limit_notice()
- summary_messages = summary.get("summary", "")
-
- if tool_notice:
- summary_messages += "\n\n" + tool_notice
-
- self._update_memory_with_summary(
- summary_messages, include_summaries=False
- )
- self._last_token_limit_tool_signature = tool_signature
- return self._step_impl(input_message, response_format)
-
- raise
+ # Get response from model backend
+ response = self._get_model_response(
+ openai_messages,
+ current_iteration=iteration_count,
+ response_format=response_format,
+ tool_schemas=[]
+ if disable_tools
+ else self._get_full_tool_schemas(),
+ prev_num_openai_messages=prev_num_openai_messages,
+ )
prev_num_openai_messages = len(openai_messages)
iteration_count += 1
@@ -3011,6 +2871,9 @@ class ChatAgent(BaseAgent):
step_token_usage, response.usage_dict
)
+ # Update token cache from LLM response
+ self._update_token_cache(response.usage_dict, len(openai_messages))
+
# Terminate Agent if stop_event is set
if self.stop_event and self.stop_event.is_set():
# Use the _step_terminate to terminate the agent with reason
@@ -3207,128 +3070,25 @@ class ChatAgent(BaseAgent):
loop = asyncio.get_event_loop()
await loop.run_in_executor(None, self.pause_event.wait)
try:
- openai_messages, num_tokens = self.memory.get_context()
- if self.summarize_threshold is not None:
- threshold = self._calculate_next_summary_threshold()
- summary_token_count = self._summary_token_count
- token_limit = self.model_backend.token_limit
-
- if num_tokens <= token_limit:
- if (
- summary_token_count
- > token_limit * self.summary_window_ratio
- ):
- logger.info(
- f"Summary tokens ({summary_token_count}) "
- f"exceed limit, full compression."
- )
- # Summarize everything (including summaries)
- summary = await self.asummarize(
- include_summaries=True
- )
- self._update_memory_with_summary(
- summary.get("summary", ""),
- include_summaries=True,
- )
- elif num_tokens > threshold:
- logger.info(
- f"Token count ({num_tokens}) exceed threshold "
- "({threshold}). Triggering summarization."
- )
- # Only summarize non-summary content
- summary = await self.asummarize(
- include_summaries=False
- )
- self._update_memory_with_summary(
- summary.get("summary", ""),
- include_summaries=False,
- )
+ (
+ openai_messages,
+ num_tokens,
+ ) = await self._get_context_with_summarization_async()
accumulated_context_tokens += num_tokens
except RuntimeError as e:
return self._step_terminate(
e.args[1], tool_call_records, "max_tokens_exceeded"
)
- # Get response from model backend with token limit error handling
- try:
- response = await self._aget_model_response(
- openai_messages,
- num_tokens=num_tokens,
- current_iteration=iteration_count,
- response_format=response_format,
- tool_schemas=[]
- if disable_tools
- else self._get_full_tool_schemas(),
- prev_num_openai_messages=prev_num_openai_messages,
- )
- except Exception as exc:
- logger.exception("Model error: %s", exc)
-
- if self._is_token_limit_error(exc):
- tool_signature = self._last_tool_call_signature
- if (
- tool_signature is not None
- and tool_signature
- == self._last_token_limit_tool_signature
- ):
- description = self._describe_tool_call(
- self._last_tool_call_record
- )
- repeated_msg = (
- "Context exceeded again by the same tool call."
- )
- if description:
- repeated_msg += f" {description}"
- raise RuntimeError(repeated_msg) from exc
-
- user_message_count = sum(
- 1
- for msg in openai_messages
- if getattr(msg, "role", None) == "user"
- )
- if (
- user_message_count == 1
- and getattr(openai_messages[-1], "role", None)
- == "user"
- ):
- raise RuntimeError(
- "The provided user input alone exceeds the"
- "context window. Please shorten the input."
- ) from exc
-
- logger.warning(
- "Token limit exceeded error detected. "
- "Summarizing context."
- )
-
- recent_records: List[ContextRecord]
- try:
- recent_records = self.memory.retrieve()
- except Exception: # pragma: no cover - defensive guard
- recent_records = []
-
- indices_to_remove = (
- self._find_indices_to_remove_for_last_tool_pair(
- recent_records
- )
- )
- self.memory.remove_records_by_indices(indices_to_remove)
-
- summary = await self.asummarize()
-
- tool_notice = self._format_tool_limit_notice()
- summary_messages = summary.get("summary", "")
-
- if tool_notice:
- summary_messages += "\n\n" + tool_notice
- self._update_memory_with_summary(
- summary_messages, include_summaries=False
- )
- self._last_token_limit_tool_signature = tool_signature
- return await self._astep_non_streaming_task(
- input_message, response_format
- )
-
- raise
+ # Get response from model backend
+ response = await self._aget_model_response(
+ openai_messages,
+ current_iteration=iteration_count,
+ response_format=response_format,
+ tool_schemas=[]
+ if disable_tools
+ else self._get_full_tool_schemas(),
+ prev_num_openai_messages=prev_num_openai_messages,
+ )
prev_num_openai_messages = len(openai_messages)
iteration_count += 1
@@ -3338,6 +3098,9 @@ class ChatAgent(BaseAgent):
step_token_usage, response.usage_dict
)
+ # Update token cache from LLM response
+ self._update_token_cache(response.usage_dict, len(openai_messages))
+
# Terminate Agent if stop_event is set
if self.stop_event and self.stop_event.is_set():
# Use the _step_terminate to terminate the agent with reason
@@ -3406,8 +3169,6 @@ class ChatAgent(BaseAgent):
if self.prune_tool_calls_from_memory and tool_call_records:
self.memory.clean_tool_calls()
- self._last_token_limit_user_signature = None
-
return self._convert_to_chatagent_response(
response,
tool_call_records,
@@ -3489,7 +3250,6 @@ class ChatAgent(BaseAgent):
def _get_model_response(
self,
openai_messages: List[OpenAIMessage],
- num_tokens: int,
current_iteration: int = 0,
response_format: Optional[Type[BaseModel]] = None,
tool_schemas: Optional[List[Dict[str, Any]]] = None,
@@ -3506,8 +3266,6 @@ class ChatAgent(BaseAgent):
if response:
break
except RateLimitError as e:
- if self._is_token_limit_error(e):
- raise
last_error = e
if attempt < self.retry_attempts - 1:
delay = min(self.retry_delay * (2**attempt), 60.0)
@@ -3554,7 +3312,6 @@ class ChatAgent(BaseAgent):
async def _aget_model_response(
self,
openai_messages: List[OpenAIMessage],
- num_tokens: int,
current_iteration: int = 0,
response_format: Optional[Type[BaseModel]] = None,
tool_schemas: Optional[List[Dict[str, Any]]] = None,
@@ -3571,8 +3328,6 @@ class ChatAgent(BaseAgent):
if response:
break
except RateLimitError as e:
- if self._is_token_limit_error(e):
- raise
last_error = e
if attempt < self.retry_attempts - 1:
delay = min(self.retry_delay * (2**attempt), 60.0)
@@ -3998,40 +3753,54 @@ class ChatAgent(BaseAgent):
# Try different invocation paths in order of preference
if hasattr(tool, 'func') and hasattr(tool.func, 'async_call'):
# Case: FunctionTool wrapping an MCP tool
- result = await tool.func.async_call(**args)
+ raw_result = await tool.func.async_call(**args)
elif hasattr(tool, 'async_call') and callable(tool.async_call):
# Case: tool itself has async_call
- result = await tool.async_call(**args)
+ raw_result = await tool.async_call(**args)
elif hasattr(tool, 'func') and asyncio.iscoroutinefunction(
tool.func
):
# Case: tool wraps a direct async function
- result = await tool.func(**args)
+ raw_result = await tool.func(**args)
elif asyncio.iscoroutinefunction(tool):
# Case: tool is itself a coroutine function
- result = await tool(**args)
+ raw_result = await tool(**args)
else:
# Fallback: synchronous call
# Use functools.partial to properly capture args
loop = asyncio.get_running_loop()
- result = await loop.run_in_executor(
+ raw_result = await loop.run_in_executor(
None, functools.partial(tool, **args)
)
+ if self.mask_tool_output:
+ with self._secure_result_store_lock:
+ self._secure_result_store[tool_call_id] = raw_result
+ result = (
+ "[The tool has been executed successfully, but the output"
+ " from the tool is masked. You can move forward]"
+ )
+ mask_flag = True
+ else:
+ result = raw_result
+ mask_flag = False
+
except Exception as e:
# Capture the error message to prevent framework crash
error_msg = f"Error executing async tool '{func_name}': {e!s}"
result = f"Tool execution failed: {error_msg}"
- logger.warning(error_msg)
+ mask_flag = False
+ logger.warning(f"{error_msg} with result: {result}")
return self._record_tool_calling(
func_name,
args,
result,
tool_call_id,
+ mask_output=mask_flag,
extra_content=tool_call_request.extra_content,
)
@@ -4225,7 +3994,9 @@ class ChatAgent(BaseAgent):
# Get context for streaming
try:
- openai_messages, num_tokens = self.memory.get_context()
+ openai_messages, num_tokens = (
+ self._get_context_with_summarization()
+ )
except RuntimeError as e:
yield self._step_terminate(e.args[1], [], "max_tokens_exceeded")
return
@@ -4781,6 +4552,27 @@ class ChatAgent(BaseAgent):
tool = self._internal_tools[function_name]
try:
result = tool(**args)
+
+ # Handle mask_tool_output
+ if self.mask_tool_output:
+ with self._secure_result_store_lock:
+ self._secure_result_store[tool_call_id] = result
+ result = (
+ "[The tool has been executed successfully, but the"
+ " output from the tool is masked. You can move"
+ " forward]"
+ )
+
+ # Truncate tool result if it exceeds the maximum token
+ # limit. This prevents single tool calls from exceeding
+ # context window
+ truncated_result, was_truncated = (
+ self._truncate_tool_result(function_name, result)
+ )
+ result_for_memory = (
+ truncated_result if was_truncated else result
+ )
+
# First, create and record the assistant message with tool
# call
assist_msg = FunctionCallingMessage(
@@ -4801,8 +4593,9 @@ class ChatAgent(BaseAgent):
meta_dict=None,
content="",
func_name=function_name,
- result=result,
+ result=result_for_memory,
tool_call_id=tool_call_id,
+ mask_output=self.mask_tool_output,
extra_content=extra_content,
)
@@ -4838,7 +4631,7 @@ class ChatAgent(BaseAgent):
f"Error executing tool '{function_name}': {e!s}"
)
result = {"error": error_msg}
- logger.warning(error_msg)
+ logger.warning(f"{error_msg} with result: {result}")
# Record error response
func_msg = FunctionCallingMessage(
@@ -4935,6 +4728,26 @@ class ChatAgent(BaseAgent):
None, functools.partial(tool, **args)
)
+ # Handle mask_tool_output
+ if self.mask_tool_output:
+ with self._secure_result_store_lock:
+ self._secure_result_store[tool_call_id] = result
+ result = (
+ "[The tool has been executed successfully, but the"
+ " output from the tool is masked. You can move"
+ " forward]"
+ )
+
+ # Truncate tool result if it exceeds the maximum token
+ # limit. This prevents single tool calls from exceeding
+ # context window
+ truncated_result, was_truncated = (
+ self._truncate_tool_result(function_name, result)
+ )
+ result_for_memory = (
+ truncated_result if was_truncated else result
+ )
+
# Create the tool response message
func_msg = FunctionCallingMessage(
role_name=self.role_name,
@@ -4942,8 +4755,9 @@ class ChatAgent(BaseAgent):
meta_dict=None,
content="",
func_name=function_name,
- result=result,
+ result=result_for_memory,
tool_call_id=tool_call_id,
+ mask_output=self.mask_tool_output,
extra_content=extra_content,
)
func_ts = time.time_ns() / 1_000_000_000
@@ -4967,7 +4781,7 @@ class ChatAgent(BaseAgent):
f"Error executing async tool '{function_name}': {e!s}"
)
result = {"error": error_msg}
- logger.warning(error_msg)
+ logger.warning(f"{error_msg} with result: {result}")
# Record error response
func_msg = FunctionCallingMessage(
@@ -5045,7 +4859,10 @@ class ChatAgent(BaseAgent):
# Get context for streaming
try:
- openai_messages, num_tokens = self.memory.get_context()
+ (
+ openai_messages,
+ num_tokens,
+ ) = await self._get_context_with_summarization_async()
except RuntimeError as e:
yield self._step_terminate(e.args[1], [], "max_tokens_exceeded")
return
diff --git a/camel/memories/context_creators/score_based.py b/camel/memories/context_creators/score_based.py
index cf5e7f922..01929d3a1 100644
--- a/camel/memories/context_creators/score_based.py
+++ b/camel/memories/context_creators/score_based.py
@@ -24,6 +24,11 @@ from camel.utils import BaseTokenCounter
class ScoreBasedContextCreator(BaseContextCreator):
r"""A context creation strategy that orders records chronologically.
+ This class supports token count estimation to reduce expensive repeated
+ token counting. When a cached token count is available, it estimates
+ new message tokens using character-based approximation instead of
+ calling the token counter for every message.
+
Args:
token_counter (BaseTokenCounter): Token counter instance used to
compute the combined token count of the returned messages.
@@ -36,6 +41,10 @@ class ScoreBasedContextCreator(BaseContextCreator):
) -> None:
self._token_counter = token_counter
self._token_limit = token_limit
+ # Token count cache: stores the known token count and corresponding
+ # message count from the last LLM response
+ self._cached_token_count: Optional[int] = None
+ self._cached_message_count: int = 0
@property
def token_counter(self) -> BaseTokenCounter:
@@ -45,6 +54,61 @@ class ScoreBasedContextCreator(BaseContextCreator):
def token_limit(self) -> int:
return self._token_limit
+ def set_cached_token_count(
+ self, token_count: int, message_count: int
+ ) -> None:
+ r"""Set the cached token count from LLM response usage.
+
+ Args:
+ token_count (int): The total token count (prompt + completion)
+ from LLM response usage.
+ message_count (int): The number of messages including the
+ assistant response that will be added to memory.
+ """
+ self._cached_token_count = token_count
+ self._cached_message_count = message_count
+
+ def clear_cache(self) -> None:
+ r"""Clear the cached token count."""
+ self._cached_token_count = None
+ self._cached_message_count = 0
+
+ def _estimate_message_tokens(self, message: OpenAIMessage) -> int:
+ r"""Estimate token count for a single message.
+
+ Uses ~2 chars/token as a conservative approximation to handle both
+ ASCII (~4 chars/token) and CJK text (~1-2 chars/token).
+
+ Args:
+ message: The OpenAI message to estimate.
+
+ Returns:
+ Estimated token count (intentionally conservative).
+ """
+ content = message.get("content", "")
+ token_estimate = 4 # message overhead
+
+ if isinstance(content, list):
+ # Multimodal content
+ for part in content:
+ if isinstance(part, dict):
+ if part.get("type") == "image_url":
+ # Images: 85 (low) to ~1500 (high detail large image)
+ # Use 1500 as conservative estimate
+ token_estimate += 1500
+ else:
+ token_estimate += len(str(part)) // 2
+ else:
+ token_estimate += len(str(part)) // 2
+ else:
+ token_estimate += len(str(content)) // 2
+
+ # Add tool_calls if present (already text, safe to serialize)
+ if message.get("tool_calls"):
+ token_estimate += len(str(message.get("tool_calls"))) // 2
+
+ return token_estimate
+
def create_context(
self,
records: List[ContextRecord],
@@ -78,5 +142,28 @@ class ScoreBasedContextCreator(BaseContextCreator):
if not messages:
return [], 0
+ current_count = len(messages)
+
+ # Use cache if available and valid
+ if (
+ self._cached_token_count is not None
+ and self._cached_message_count > 0
+ ):
+ if current_count == self._cached_message_count:
+ # Same message count, use cached value directly
+ return messages, self._cached_token_count
+ elif current_count > self._cached_message_count:
+ # New messages added, estimate incrementally
+ new_messages = messages[self._cached_message_count :]
+ estimated_new_tokens = sum(
+ self._estimate_message_tokens(msg) for msg in new_messages
+ )
+ return (
+ messages,
+ self._cached_token_count + estimated_new_tokens,
+ )
+ # current_count < cached: messages were removed, cache invalid
+
+ # No cache or cache is stale - do full calculation
total_tokens = self.token_counter.count_tokens_from_messages(messages)
return messages, total_tokens
diff --git a/camel/types/unified_model_type.py b/camel/types/unified_model_type.py
index f845f27c7..7dbca574d 100644
--- a/camel/types/unified_model_type.py
+++ b/camel/types/unified_model_type.py
@@ -62,11 +62,15 @@ class UnifiedModelType(str):
@property
def token_limit(self) -> int:
- r"""Returns the token limit for the model. Here we set the default
- value as `999_999_999` if it's not provided from `model_config_dict`"""
+ r"""Returns the context window size for the model.
+
+ For unknown model types not defined in ModelType enum, this returns
+ a default value of 999_999_999 tokens.
+ """
logging.warning(
- "Invalid or missing `max_tokens` in `model_config_dict`. "
- "Defaulting to 999_999_999 tokens."
+ "Unknown model '%s': context window size not defined. "
+ "Defaulting to 999_999_999.",
+ str(self),
)
return 999_999_999
diff --git a/examples/models/openai_example.py b/examples/models/openai_example.py
index b8c9deb19..efd2fc2cd 100644
--- a/examples/models/openai_example.py
+++ b/examples/models/openai_example.py
@@ -11,56 +11,43 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# ========= Copyright 2023-2025 @ CAMEL-AI.org. All Rights Reserved. =========
+"""OpenAI model example: multi-turn conversation with tool use and structured
+output."""
+
+from pydantic import BaseModel, Field
from camel.agents import ChatAgent
-from camel.configs import ChatGPTConfig
from camel.models import ModelFactory
-from camel.toolkits import TerminalToolkit
+from camel.toolkits import MathToolkit
from camel.types import ModelPlatformType, ModelType
-tools = [
- *TerminalToolkit().get_tools(),
-]
-gpt_5_model = ModelFactory.create(
+class Summary(BaseModel):
+ total: float = Field(description="The calculated total")
+ explanation: str = Field(description="Brief explanation")
+
+
+model = ModelFactory.create(
model_platform=ModelPlatformType.OPENAI,
- model_type=ModelType.GPT_5_2,
- model_config_dict=ChatGPTConfig().as_dict(),
+ model_type=ModelType.GPT_4O_MINI,
)
-# Set agent
-camel_agent = ChatAgent(model=gpt_5_model, tools=tools)
+agent = ChatAgent(model=model, tools=MathToolkit().get_tools())
-# Set user message
-user_msg = """Use tool to create an interactive HTML webpage that allows users
-to play with a Rubik's Cube, and saved it to local file.
-"""
-
-# Get response information
-response = camel_agent.step(user_msg)
+# Turn 1: Basic chat
+response = agent.step("Hi, I need help with some calculations.")
print(response.msgs[0].content)
-'''
-===============================================================================
-Created an interactive Rubik's Cube webpage and saved it locally as:
-
-- `rubiks_cube.html`
-It includes:
-- 3D cube rendering (drag to orbit, wheel to zoom)
-- Face turns via buttons or keyboard (U/D/L/R/F/B, Shift for prime)
-- Scramble, reset, random move
-- Undo/redo
-- Copyable moves log
-
-Open it by double-clicking the file or serving it locally
-(recommended due to browser module/security policies):
+# Turn 2: Tool use
+response = agent.step("What is 123.45 + 678.90?")
+print(response.msgs[0].content)
-```bash
-python3 -m http.server
-# then visit http://localhost:8000/rubiks_cube.html
-```
+# Turn 3: Follow-up with context
+response = agent.step("Now multiply that result by 2.")
+print(response.msgs[0].content)
-If you want a **fully offline** version (no CDN usage), tell me and
-I'll modify it to bundle the required libraries locally or inline them.
-===============================================================================
-'''
+# Turn 4: Structured output
+response = agent.step(
+ "Summarize all calculations we did.", response_format=Summary
+)
+print(response.msgs[0].content)