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

feat: save truncated tool outputs to log files (#4179)

Sylvanus Chinedu Egbosiuba5e7d9e161b58
diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.py
index 63037789b..533819f0d 100644
--- a/camel/agents/chat_agent.py
+++ b/camel/agents/chat_agent.py
@@ -468,6 +468,12 @@ class ChatAgent(BaseAgent):
context window that can be occupied by summary information. Used
to limit how much of the model's context is reserved for
summarization results. (default: :obj:`0.6`)
+ tool_log_dir (Optional[Union[str, Path]]): Directory used to save full
+ tool outputs when they are truncated. If `None`, full outputs are
+ not saved. Saved files contain raw tool output and are not removed
+ automatically, so use an appropriately protected directory. Paths
+ refer to the host running the agent and may not be accessible
+ inside sandboxed tools. (default: :obj:`None`)
"""
def __init__(
@@ -516,6 +522,7 @@ class ChatAgent(BaseAgent):
on_request_usage: Optional[Callable[[Dict[str, Any]], Any]] = None,
stream_accumulate: Optional[bool] = None,
summary_window_ratio: float = 0.6,
+ tool_log_dir: Optional[Union[str, Path]] = None,
) -> None:
if isinstance(model, ModelManager):
self.model_backend = model
@@ -619,6 +626,11 @@ class ChatAgent(BaseAgent):
self.stop_event = stop_event
self.tool_execution_timeout = tool_execution_timeout
self.mask_tool_output = mask_tool_output
+ self._tool_log_dir = (
+ Path(tool_log_dir).expanduser().resolve()
+ if tool_log_dir is not None
+ else None
+ )
self._secure_result_store: Dict[str, Any] = {}
self._secure_result_store_lock = threading.Lock()
self.pause_event = pause_event
@@ -1230,6 +1242,49 @@ class ChatAgent(BaseAgent):
except (TypeError, ValueError):
return str(result)
+ def _save_tool_output_log(
+ self, func_name: str, content: str
+ ) -> Optional[str]:
+ r"""Save full tool output to a .log file when truncation occurs.
+
+ Args:
+ func_name (str): The name of the tool function.
+ content (str): The full serialized tool output to persist.
+
+ Returns:
+ Optional[str]: Absolute path to the saved log file, or None when
+ logging is disabled or saving failed.
+ """
+ log_dir = self._tool_log_dir
+ if log_dir is None:
+ return None
+
+ try:
+ log_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
+ safe_func_name = re.sub(r"[^A-Za-z0-9_-]+", "_", func_name).strip(
+ "_"
+ )
+ safe_func_name = safe_func_name[:64] or "tool"
+ with tempfile.NamedTemporaryFile(
+ mode="w",
+ encoding="utf-8",
+ prefix=f"{safe_func_name}_",
+ suffix=".log",
+ dir=log_dir,
+ delete=False,
+ ) as log_file:
+ log_file.write(content)
+ log_path = Path(log_file.name)
+ logger.info(
+ "Full tool output for '%s' saved to: %s", func_name, log_path
+ )
+ return str(log_path)
+ except Exception as e:
+ logger.warning(
+ "Failed to save tool output log for '%s': %s", func_name, e
+ )
+ return None
+
def _truncate_tool_result(
self, func_name: str, result: Any
) -> Tuple[Any, bool]:
@@ -1261,10 +1316,19 @@ class ChatAgent(BaseAgent):
target_tokens = max(max_tokens - 100, 100)
truncated = serialized[: target_tokens * 3]
+ log_ref = ""
+ if self._tool_log_dir is not None:
+ log_path = self._save_tool_output_log(func_name, serialized)
+ log_ref = (
+ f" Full output saved to: {log_path}"
+ if log_path
+ else " (log saving failed)"
+ )
+
notice = (
f"\n\n[TRUNCATED] Tool '{func_name}' output truncated "
f"({result_tokens} > {max_tokens} tokens). "
- f"Tool executed successfully."
+ f"Tool executed successfully.{log_ref}"
)
logger.warning(
@@ -6182,6 +6246,7 @@ class ChatAgent(BaseAgent):
),
summarize_threshold=self.summarize_threshold,
mask_tool_output=self.mask_tool_output,
+ tool_log_dir=self._tool_log_dir,
enable_snapshot_clean=self._enable_snapshot_clean,
retry_attempts=self.retry_attempts,
retry_delay=self.retry_delay,
diff --git a/test/agents/test_chat_agent_tool_log.py b/test/agents/test_chat_agent_tool_log.py
new file mode 100644
index 000000000..4b80ed569
--- /dev/null
+++ b/test/agents/test_chat_agent_tool_log.py
@@ -0,0 +1,200 @@
+# ========= Copyright 2023-2026 @ 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-2026 @ CAMEL-AI.org. All Rights Reserved. =========
+"""Tests for optionally saving full tool outputs before truncation."""
+
+import inspect
+import os
+import stat
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+from unittest.mock import MagicMock
+
+import pytest
+
+from camel.agents import ChatAgent
+from camel.models import StubModel
+from camel.types import ModelType
+
+
+class _CharTokenCounter:
+ def encode(self, text):
+ return [ord(char) for char in text]
+
+ def decode(self, token_ids):
+ return "".join(chr(token_id) for token_id in token_ids)
+
+
+def test_tool_log_dir_is_appended_to_constructor():
+ parameters = list(inspect.signature(ChatAgent.__init__).parameters)
+ assert parameters.index("tool_log_dir") > parameters.index(
+ "summary_window_ratio"
+ )
+
+
+def test_tool_log_dir_is_opt_in_and_preserved_by_clone(tmp_path):
+ default_agent = ChatAgent(model=StubModel(ModelType.STUB))
+ assert default_agent._tool_log_dir is None
+ assert default_agent.clone()._tool_log_dir is None
+
+ log_dir = tmp_path / "relative" / ".." / "logs"
+ configured_agent = ChatAgent(
+ model=StubModel(ModelType.STUB),
+ tool_log_dir=log_dir,
+ )
+ assert configured_agent._tool_log_dir == log_dir.resolve()
+ assert configured_agent.clone()._tool_log_dir == log_dir.resolve()
+
+
+def agent(tmp_path):
+ """A ChatAgent with just enough state for these methods."""
+ a = ChatAgent.__new__(ChatAgent)
+ a._tool_log_dir = tmp_path / "camel_tool_logs"
+ a._token_limit = 4096
+ a.summarize_threshold = None
+ a.model_backend = MagicMock()
+ a.model_backend.token_counter = _CharTokenCounter()
+ return a
+
+
+class TestSaveToolOutputLog:
+ def test_creates_log_file(self, agent):
+ path = agent._save_tool_output_log("my_tool", "full content")
+ assert path is not None
+ assert Path(path).exists()
+ assert Path(path).is_absolute()
+
+ def test_log_file_contains_full_content(self, agent):
+ content = "full output data"
+ path = agent._save_tool_output_log("my_tool", content)
+ assert Path(path).read_text(encoding="utf-8") == content
+
+ def test_log_file_placed_in_tool_log_dir(self, agent):
+ path = agent._save_tool_output_log("my_tool", "data")
+ assert Path(path).parent == agent._tool_log_dir
+
+ def test_log_filename_contains_func_name(self, agent):
+ path = agent._save_tool_output_log("search_web", "data")
+ assert "search_web" in Path(path).name
+
+ def test_log_dir_created_automatically(self, agent, tmp_path):
+ # dir doesn't exist yet - method should mkdir(parents=True) for us
+ agent._tool_log_dir = tmp_path / "new" / "nested" / "dir"
+ assert not agent._tool_log_dir.exists()
+ agent._save_tool_output_log("tool", "content")
+ assert agent._tool_log_dir.exists()
+
+ def test_returns_none_on_write_failure(self, agent, tmp_path):
+ # Point _tool_log_dir at an existing *file* so mkdir() raises
+ # FileExistsError / NotADirectoryError under the hood. We just
+ # want to confirm this fails quietly (returns None) rather than
+ # blowing up the whole tool-call flow.
+ bad_path = tmp_path / "i_am_a_file"
+ bad_path.write_text("block")
+ agent._tool_log_dir = bad_path
+ result = agent._save_tool_output_log("tool", "content")
+ assert result is None
+
+ def test_handles_non_ascii_content(self, agent):
+ # Tool output can easily contain non-ASCII text (e.g. a web
+ # search result in another language) - make sure we're writing
+ # with utf-8 and not silently mangling it.
+ content = "café, 日本語, emoji 🚀"
+ path = agent._save_tool_output_log("my_tool", content)
+ assert Path(path).read_text(encoding="utf-8") == content
+
+ @pytest.mark.parametrize(
+ "func_name",
+ ["../escaped", "/tmp/escaped", r"..\escaped"],
+ )
+ def test_sanitizes_func_name(self, agent, func_name):
+ path = agent._save_tool_output_log(func_name, "content")
+ assert Path(path).parent == agent._tool_log_dir
+
+ def test_handles_func_name_without_safe_characters(self, agent):
+ path = agent._save_tool_output_log("../", "content")
+ assert Path(path).name.startswith("tool_")
+
+ def test_uses_private_file_permissions(self, agent):
+ path = agent._save_tool_output_log("my_tool", "content")
+ if os.name != "nt":
+ assert stat.S_IMODE(Path(path).stat().st_mode) & 0o077 == 0
+ assert (
+ stat.S_IMODE(agent._tool_log_dir.stat().st_mode) & 0o077 == 0
+ )
+
+ def test_does_not_save_without_configured_directory(self, agent):
+ agent._tool_log_dir = None
+ assert agent._save_tool_output_log("my_tool", "content") is None
+
+
+class TestTruncateToolResult:
+ def test_short_result_not_truncated(self, agent):
+ result, was_truncated = agent._truncate_tool_result("tool", "short")
+ assert was_truncated is False
+ assert result == "short"
+
+ def test_long_result_is_truncated(self, agent):
+ result, was_truncated = agent._truncate_tool_result(
+ "tool", "x" * 50000
+ )
+ assert was_truncated is True
+ assert len(result) < 50000
+
+ def test_truncation_creates_log_file(self, agent):
+ agent._truncate_tool_result("my_tool", "x" * 50000)
+ log_files = list(agent._tool_log_dir.glob("my_tool_*.log"))
+ assert len(log_files) == 1
+
+ def test_truncation_notice_contains_log_path(self, agent):
+ result, _ = agent._truncate_tool_result("my_tool", "x" * 50000)
+ assert "Full output saved to:" in result
+
+ def test_log_file_contains_full_original_output(self, agent):
+ long_output = "x" * 50000
+ agent._truncate_tool_result("my_tool", long_output)
+ log_file = next(agent._tool_log_dir.glob("my_tool_*.log"))
+ assert log_file.read_text(encoding="utf-8") == long_output
+
+ def test_no_log_file_when_not_truncated(self, agent):
+ agent._truncate_tool_result("my_tool", "short")
+ # nothing should have been written at all, dir shouldn't exist
+ assert not agent._tool_log_dir.exists()
+
+ def test_no_log_notice_when_logging_is_disabled(self, agent):
+ agent._tool_log_dir = None
+ result, _ = agent._truncate_tool_result("my_tool", "x" * 50000)
+ assert "Full output saved to:" not in result
+ assert "log saving failed" not in result
+
+ def test_two_truncated_calls_produce_two_log_files(self, agent):
+ # Regression check: filenames need to be unique per call (e.g.
+ # timestamped or uuid-suffixed), otherwise the second truncation
+ # would silently clobber the first log.
+ agent._truncate_tool_result("my_tool", "a" * 50000)
+ agent._truncate_tool_result("my_tool", "b" * 50000)
+ log_files = list(agent._tool_log_dir.glob("my_tool_*.log"))
+ assert len(log_files) == 2
+
+ def test_concurrent_calls_produce_unique_log_files(self, agent):
+ with ThreadPoolExecutor(max_workers=4) as executor:
+ paths = list(
+ executor.map(
+ lambda content: agent._save_tool_output_log(
+ "my_tool", content
+ ),
+ [str(index) for index in range(10)],
+ )
+ )
+ assert len(paths) == len(set(paths))