🐫 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
feat: auto-coerce dict args to Pydantic models in FunctionTool (#3916)
Wendong-Fanba5f27601035
diff --git a/camel/toolkits/__init__.py b/camel/toolkits/__init__.pyindex 4ede3aae4..76f768fe9 100644--- a/camel/toolkits/__init__.py+++ b/camel/toolkits/__init__.py@@ -66,7 +66,7 @@ from .image_analysis_toolkit import ImageAnalysisToolkitfrom .mcp_toolkit import MCPToolkitfrom .browser_toolkit import BrowserToolkitfrom .async_browser_toolkit import AsyncBrowserToolkit-from .file_toolkit import FileToolkit, FileWriteToolkit+from .file_toolkit import FileToolkitfrom .pptx_toolkit import PPTXToolkitfrom .terminal_toolkit import TerminalToolkitfrom .pubmed_toolkit import PubMedToolkit@@ -103,6 +103,10 @@ from .microsoft_outlook_mail_toolkit import OutlookMailToolkitfrom .earth_science_toolkit import EarthScienceToolkitfrom .skill_toolkit import SkillToolkitfrom .headless_browser_search_toolkit import HeadlessBrowserSearchToolkit+from .agent_toolkit import AgentToolkit+from .planning_worktree_toolkit import PlanningWorktreeToolkit+from .todo_toolkit import TodoItem, TodoToolkit+from .web_fetch_toolkit import WebFetchToolkit__all__ = ['BaseToolkit',@@ -157,7 +161,6 @@ __all__ = ['BrowserToolkit','AsyncBrowserToolkit','FileToolkit',- 'FileWriteToolkit', # Deprecated, use FileToolkit instead'PPTXToolkit','TerminalToolkit','PubMedToolkit',@@ -197,4 +200,9 @@ __all__ = ['EarthScienceToolkit','SkillToolkit','HeadlessBrowserSearchToolkit',+ 'AgentToolkit',+ 'PlanningWorktreeToolkit',+ 'TodoItem',+ 'TodoToolkit',+ 'WebFetchToolkit',]diff --git a/camel/toolkits/agent_toolkit.py b/camel/toolkits/agent_toolkit.pynew file mode 100644index 000000000..cdb71e47f--- /dev/null+++ b/camel/toolkits/agent_toolkit.py@@ -0,0 +1,657 @@+# ========= 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. =========++import concurrent.futures+import threading+import time+import types+import uuid+from dataclasses import dataclass, field+from typing import (+ TYPE_CHECKING,+ Any,+ Callable,+ Dict,+ List,+ Optional,+ Tuple,+ Union,+)++from camel.logger import get_logger+from camel.toolkits.base import BaseToolkit, RegisteredAgentToolkit+from camel.toolkits.function_tool import FunctionTool++if TYPE_CHECKING:+ from camel.agents import ChatAgent+ from camel.responses import ChatAgentResponse++logger = get_logger(__name__)+++@dataclass+class _AgentSession:+ agent: "ChatAgent"+ subagent_type: str+ description: str+ turns: int = 0+ active_task_id: Optional[str] = None+++@dataclass+class _AgentTask:+ task_id: str+ agent_id: str+ prompt: str+ future: concurrent.futures.Future["ChatAgentResponse"]+ stop_event: threading.Event+ status: str = "running"+ result: Optional[str] = None+ error: Optional[str] = None+ created_at: float = field(default_factory=time.time)+ completed_at: Optional[float] = None+++class AgentToolkit(BaseToolkit, RegisteredAgentToolkit):+ r"""Toolkit for delegating a task to a persistent specialized sub-agent.++ This toolkit exposes tools for either waiting on a delegated task directly+ or starting one and checking its result later.+ """++ _TYPE_INSTRUCTIONS = types.MappingProxyType(+ {+ "general-purpose": (+ "Complete the delegated task autonomously and return a "+ "direct, useful result."+ ),+ "research": (+ "Investigate the task carefully, synthesize findings, and "+ "note important uncertainties."+ ),+ "analysis": (+ "Break the problem down, compare options when relevant, and "+ "return the strongest conclusion."+ ),+ "coding": (+ "Focus on implementation details, correctness, and concrete "+ "engineering tradeoffs."+ ),+ "writing": (+ "Produce clear, polished writing that matches the requested "+ "tone and constraints."+ ),+ }+ )++ def __init__(+ self,+ timeout: Optional[float] = None,+ ) -> None:+ r"""Initialize the AgentToolkit.++ Args:+ timeout (Optional[float]): Maximum execution time for toolkit+ calls. (default: :obj:`None`)+ """+ super().__init__(timeout=timeout)+ RegisteredAgentToolkit.__init__(self)+ self._sessions: Dict[str, _AgentSession] = {}+ self._tasks: Dict[str, _AgentTask] = {}+ self._lock = threading.RLock()+ self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=4)++ def _build_system_message(+ self,+ subagent_type: str,+ description: str,+ ) -> str:+ specialization = self._TYPE_INSTRUCTIONS.get(+ subagent_type.lower(),+ (+ "Approach the delegated task as a focused specialist and "+ "return the most useful result you can."+ ),+ )+ return (+ "You are a specialized sub-agent working on behalf of another "+ "agent.\n"+ f"Sub-agent type: {subagent_type}\n"+ f"Task description: {description}\n"+ f"Operating guidance: {specialization}\n"+ )++ def _error_result(+ self, error_message: str, **payload: Any+ ) -> Dict[str, Any]:+ logger.warning(error_message)+ result: Dict[str, Any] = {+ "status": "failed",+ "error": f"Error: {error_message}",+ }+ result.update(payload)+ return result++ def _require_parent_agent(self) -> Optional["ChatAgent"]:+ return self._agent++ def _resolve_child_tools(+ self,+ parent: Optional["ChatAgent"],+ ) -> Tuple[+ Optional[List[Union[FunctionTool, Callable]]],+ Optional[List[RegisteredAgentToolkit]],+ ]:+ if parent is None:+ return None, None+ cloned_tools, toolkits_to_register = parent._clone_tools()+ return list(cloned_tools), toolkits_to_register++ def _create_subagent(+ self,+ subagent_type: str,+ description: str,+ ) -> Optional["ChatAgent"]:+ from camel.agents import ChatAgent++ parent = self._require_parent_agent()+ if parent is None:+ return None+ tools, toolkits_to_register = self._resolve_child_tools(parent=parent)++ return ChatAgent(+ system_message=self._build_system_message(+ subagent_type=subagent_type,+ description=description,+ ),+ model=parent.model_backend.models,+ message_window_size=getattr(parent.memory, "window_size", None),+ token_limit=getattr(+ parent.memory.get_context_creator(),+ "token_limit",+ None,+ ),+ output_language=getattr(parent, "_output_language", None),+ tools=tools,+ toolkits_to_register_agent=toolkits_to_register,+ response_terminators=parent.response_terminators,+ scheduling_strategy=(+ parent.model_backend.scheduling_strategy.__name__+ ),+ max_iteration=parent.max_iteration,+ tool_execution_timeout=parent.tool_execution_timeout,+ prune_tool_calls_from_memory=(parent.prune_tool_calls_from_memory),+ on_request_usage=parent.on_request_usage,+ stream_accumulate=parent.stream_accumulate,+ )++ def _run_agent_step(+ self,+ agent: "ChatAgent",+ prompt: str,+ ) -> "ChatAgentResponse":+ return agent.step(prompt)++ def _complete_task(self, task_id: str) -> None:+ with self._lock:+ task = self._tasks.get(task_id)+ if (+ task is None+ or not task.future.done()+ or task.status != "running"+ ):+ return++ try:+ response = task.future.result()+ except concurrent.futures.CancelledError:+ status = "stopped"+ result = None+ error = None+ except Exception as exc:+ status = "stopped" if task.stop_event.is_set() else "failed"+ result = None+ error = str(exc)+ else:+ status = "stopped" if task.stop_event.is_set() else "completed"+ result = response.msgs[0].content if response.msgs else ""+ error = None++ with self._lock:+ current = self._tasks.get(task_id)+ if current is None or current.status != "running":+ return+ current.status = status+ current.result = result+ current.error = error+ current.completed_at = time.time()++ session = self._sessions.get(current.agent_id)+ if session is not None and session.active_task_id == task_id:+ session.active_task_id = None+ if status in {"completed", "stopped"}:+ session.turns += 1++ _MAX_FINISHED_TASKS = 64++ def _submit_agent_task(+ self,+ agent_id: str,+ agent: "ChatAgent",+ prompt: str,+ ) -> _AgentTask:+ """Submit a new task. Caller MUST hold ``self._lock``."""+ finished_count = sum(+ 1+ for t in self._tasks.values()+ if t.status in {"completed", "failed", "stopped"}+ )+ if finished_count >= self._MAX_FINISHED_TASKS:+ self._purge_completed_tasks()+ stop_event = threading.Event()+ agent.stop_event = stop_event+ task_id = str(uuid.uuid4())+ future = self._executor.submit(self._run_agent_step, agent, prompt)+ task = _AgentTask(+ task_id=task_id,+ agent_id=agent_id,+ prompt=prompt,+ future=future,+ stop_event=stop_event,+ )++ self._tasks[task_id] = task+ self._sessions[agent_id].active_task_id = task_id++ future.add_done_callback(lambda _future: self._complete_task(task_id))+ return task++ def _get_task(self, task_id: str) -> Optional[_AgentTask]:+ self._complete_task(task_id)+ with self._lock:+ task = self._tasks.get(task_id)+ return task++ def agent_run_subagent(+ self,+ prompt: str,+ description: str = "Specialized sub-agent task",+ subagent_type: str = "general-purpose",+ agent_id: Optional[str] = None,+ wait: bool = True,+ timeout: Optional[float] = None,+ ) -> Dict[str, Any]:+ r"""Run a specialized sub-agent, optionally waiting for completion.++ Use this tool when the current task is complex enough to benefit from+ a focused child agent with its own conversation state. If+ :obj:`agent_id` is omitted, a new sub-agent session is created with a+ fresh ChatAgent instance and its own empty conversation state. If+ :obj:`agent_id` is provided, the matching sub-agent instance is reused+ rather than recreated. This means the sub-agent keeps its existing+ memory and any state accumulated from previous turns in that session.++ Prefer :obj:`wait=True` when the parent agent needs the sub-agent+ result before it can continue. Use :obj:`wait=False` only when the+ parent agent intentionally wants to do other work first and check the+ task later with :obj:`agent_get_task_output`.++ Args:+ prompt (str): The task instructions to send to the sub-agent for+ this turn.+ description (str): Short description of the sub-task or role for+ the sub-agent. This is primarily used when creating a new+ session. (default: :obj:`"Specialized sub-agent task"`)+ subagent_type (str): Specialization label for the spawned+ sub-agent, such as :obj:`general-purpose`, :obj:`research`,+ :obj:`analysis`, :obj:`coding`, or :obj:`writing`.+ (default: :obj:`"general-purpose"`)+ agent_id (Optional[str]): Existing sub-agent session ID to resume.+ When provided, the stored sub-agent instance is reused, so it+ continues with the same memory / conversation state from+ earlier turns. In this case, :obj:`description` and+ :obj:`subagent_type` are ignored. The spawned sub-agent always+ uses the calling parent agent's model. (default: :obj:`None`)++ wait (bool): Whether to wait for the sub-agent to finish before+ returning. Set to :obj:`False` to start the task and check it+ later with :obj:`agent_get_task_output`.+ (default: :obj:`True`)+ timeout (Optional[float]): Maximum wait time in seconds for the+ sub-agent to finish when :obj:`wait` is True. If the timeout is+ reached, the task keeps running and the current status is+ returned.++ Returns:+ Dict[str, Any]: Final result for completed tasks, or current task+ metadata if still running.+ """+ if self._require_parent_agent() is None:+ return self._error_result(+ "AgentToolkit must be registered to a parent ChatAgent via "+ "'toolkits_to_register_agent' before it can spawn "+ "sub-agents.",+ agent_id=agent_id,+ task_id=None,+ created=False,+ subagent_type=subagent_type,+ description=description,+ )+ if not prompt or not prompt.strip():+ return self._error_result(+ "prompt cannot be empty",+ agent_id=agent_id,+ task_id=None,+ created=False,+ subagent_type=subagent_type,+ description=description,+ )++ created = False+ if agent_id is None:+ try:+ agent = self._create_subagent(+ subagent_type=subagent_type,+ description=description,+ )+ except Exception as exc:+ return self._error_result(+ f"Failed to create sub-agent: {exc}",+ agent_id=None,+ task_id=None,+ created=False,+ subagent_type=subagent_type,+ description=description,+ )+ if agent is None:+ return self._error_result(+ "AgentToolkit must be registered to a parent ChatAgent "+ "via 'toolkits_to_register_agent' before it can spawn "+ "sub-agents.",+ agent_id=None,+ task_id=None,+ created=False,+ subagent_type=subagent_type,+ description=description,+ )+ agent_id = agent.agent_id+ session = _AgentSession(+ agent=agent,+ subagent_type=subagent_type,+ description=description,+ )+ with self._lock:+ self._sessions[agent_id] = session+ created = True+ else:+ with self._lock:+ existing_session = self._sessions.get(agent_id)+ if existing_session is None:+ return self._error_result(+ f"No sub-agent session found for agent_id '{agent_id}'.",+ agent_id=agent_id,+ task_id=None,+ created=False,+ subagent_type=subagent_type,+ description=description,+ )+ session = existing_session+ agent = session.agent++ with self._lock:+ active_task_id = self._sessions[agent_id].active_task_id+ active_task = (+ self._tasks.get(active_task_id) if active_task_id else None+ )+ if active_task is not None and active_task_id is not None:+ self._complete_task(active_task_id)+ active_task = self._tasks.get(active_task_id)+ if active_task is not None and active_task.status == "running":+ return self._error_result(+ f"Sub-agent '{agent_id}' already has a running task "+ f"('{active_task_id}'). Query it or stop it before "+ f"starting another task.",+ agent_id=agent_id,+ task_id=active_task_id,+ created=False,+ subagent_type=session.subagent_type,+ description=session.description,+ )++ try:+ task = self._submit_agent_task(+ agent_id=agent_id,+ agent=agent,+ prompt=prompt,+ )+ except Exception as exc:+ return self._error_result(+ f"Failed to start sub-agent task: {exc}",+ agent_id=agent_id,+ task_id=None,+ created=created,+ subagent_type=session.subagent_type,+ description=session.description,+ )++ if wait and not task.future.done():+ try:+ task.future.result(timeout=timeout)+ except concurrent.futures.TimeoutError:+ logger.debug(+ "Timed out waiting for sub-agent task '%s'.",+ task.task_id,+ )+ except Exception as exc:+ logger.debug(+ "Sub-agent task '%s' raised while waiting: %s",+ task.task_id,+ exc,+ )+ current_task = self._get_task(task.task_id)+ if current_task is None:+ return self._error_result(+ f"No sub-agent task found for task_id '{task.task_id}'.",+ task_id=task.task_id,+ agent_id=session.agent.agent_id,+ created=created,+ subagent_type=session.subagent_type,+ description=session.description,+ )+ return {+ "agent_id": session.agent.agent_id,+ "task_id": current_task.task_id,+ "created": created,+ "subagent_type": session.subagent_type,+ "description": session.description,+ "status": current_task.status,+ "result": current_task.result,+ "error": current_task.error,+ }++ def agent_get_task_output(+ self,+ task_id: str,+ block: bool = False,+ timeout: Optional[float] = None,+ ) -> Dict[str, Any]:+ r"""Get the latest result of a sub-agent task started earlier.++ Use this after calling :obj:`agent_run_subagent(wait=False)`. When+ :obj:`block` is False, the call returns immediately with the latest+ known status. When :obj:`block` is True, the tool waits up to+ :obj:`timeout` seconds for completion before returning.++ Args:+ task_id (str): Sub-agent task ID returned by+ :obj:`agent_run_subagent`.+ block (bool): Whether to wait for the task to finish before+ returning status and output. (default: :obj:`False`)+ timeout (Optional[float]): Maximum wait time in seconds when+ :obj:`block` is True. (default: :obj:`None`)++ Returns:+ Dict[str, Any]: Task status, associated :obj:`agent_id`, and any+ available result or error output.+ """+ task = self._get_task(task_id)+ if task is None:+ return self._error_result(+ f"No sub-agent task found for task_id '{task_id}'.",+ task_id=task_id,+ agent_id=None,+ result=None,+ )+ if block and not task.future.done():+ try:+ task.future.result(timeout=timeout)+ except concurrent.futures.TimeoutError:+ pass+ except Exception:+ pass+ task = self._get_task(task_id)+ if task is None:+ return self._error_result(+ f"No sub-agent task found for task_id '{task_id}'.",+ task_id=task_id,+ agent_id=None,+ result=None,+ )++ return {+ "task_id": task.task_id,+ "agent_id": task.agent_id,+ "status": task.status,+ "result": task.result,+ "error": task.error,+ }++ def agent_stop_task(self, task_id: str) -> Dict[str, Any]:+ r"""Request cancellation of a running sub-agent task.++ Args:+ task_id (str): Sub-agent task ID returned by+ :obj:`agent_run_subagent`.++ Returns:+ Dict[str, Any]: Stop request status and the latest known task+ state.+ """+ task = self._get_task(task_id)+ if task is None:+ return self._error_result(+ f"No sub-agent task found for task_id '{task_id}'.",+ task_id=task_id,+ agent_id=None,+ message=None,+ )+ if task.status != "running":+ return {+ "task_id": task.task_id,+ "agent_id": task.agent_id,+ "status": task.status,+ "message": "Task is not running.",+ }++ try:+ task.stop_event.set()+ task.future.cancel()+ self._complete_task(task_id)+ refreshed = self._get_task(task_id)+ except Exception as exc:+ return self._error_result(+ f"Failed to stop task '{task_id}': {exc}",+ task_id=task.task_id,+ agent_id=task.agent_id,+ message=None,+ )+ if refreshed is None:+ return self._error_result(+ f"No sub-agent task found for task_id '{task_id}'.",+ task_id=task_id,+ agent_id=task.agent_id,+ message=None,+ )+ reported_status = (+ "stopping" if refreshed.status == "running" else refreshed.status+ )++ return {+ "task_id": refreshed.task_id,+ "agent_id": refreshed.agent_id,+ "status": reported_status,+ "message": "Stop requested.",+ }++ def clone_for_new_session(+ self,+ new_session_id: Optional[str] = None,+ ) -> "AgentToolkit":+ r"""Create a fresh AgentToolkit without carrying over sub-agent state.++ Args:+ new_session_id (Optional[str]): Unused compatibility parameter for+ ChatAgent toolkit cloning. (default: :obj:`None`)++ Returns:+ AgentToolkit: A new toolkit instance with the same configuration+ and no active sub-agent sessions.+ """+ del new_session_id+ return AgentToolkit(+ timeout=self.timeout,+ )++ def _purge_completed_tasks(self) -> None:+ """Remove finished tasks to prevent unbounded memory growth."""+ with self._lock:+ finished = [+ (tid, t)+ for tid, t in self._tasks.items()+ if t.status in {"completed", "failed", "stopped"}+ ]+ excess = len(finished) - self._MAX_FINISHED_TASKS + 1+ if excess <= 0:+ return+ finished.sort(+ key=lambda item: (+ item[1].completed_at or item[1].created_at,+ item[1].created_at,+ )+ )+ for tid, _ in finished[:excess]:+ del self._tasks[tid]++ def cleanup(self) -> None:+ with self._lock:+ tasks = list(self._tasks.values())+ for task in tasks:+ if task.status == "running":+ task.stop_event.set()+ task.future.cancel()+ self._executor.shutdown(wait=False, cancel_futures=True)++ def __del__(self) -> None:+ try:+ self.cleanup()+ except Exception:+ pass++ def get_tools(self) -> List[FunctionTool]:+ r"""Return the tool list for this toolkit."""+ return [+ FunctionTool(self.agent_run_subagent),+ FunctionTool(self.agent_get_task_output),+ FunctionTool(self.agent_stop_task),+ ]diff --git a/camel/toolkits/file_toolkit.py b/camel/toolkits/file_toolkit.pyindex 69b2d93f3..810d2f752 100644--- a/camel/toolkits/file_toolkit.py+++ b/camel/toolkits/file_toolkit.py@@ -13,9 +13,10 @@# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========import osimport re+import uuidfrom datetime import datetimefrom pathlib import Path-from typing import Dict, List, Optional, Tuple, Union+from typing import Any, Dict, List, Optional, Tuple, Unionfrom camel.logger import get_loggerfrom camel.toolkits.base import BaseToolkit@@ -46,7 +47,7 @@ class FileToolkit(BaseToolkit):default_encoding: str = "utf-8",backup_enabled: bool = True,) -> None:- r"""Initialize the FileWriteToolkit.+ r"""Initialize the FileToolkit.Args:working_directory (str, optional): The default directory for@@ -74,7 +75,7 @@ class FileToolkit(BaseToolkit):self.default_encoding = default_encodingself.backup_enabled = backup_enabledlogger.info(- f"FileWriteToolkit initialized with output directory"+ f"FileToolkit initialized with output directory"f": {self.working_directory}, encoding: {default_encoding}")@@ -100,6 +101,26 @@ class FileToolkit(BaseToolkit):path_obj = path_obj.parent / sanitized_filenamereturn path_obj.resolve()+ def _resolve_search_path(self, path: Optional[str] = None) -> Path:+ r"""Resolve a search directory without sanitizing it."""+ if path:+ path_obj = Path(path)+ if not path_obj.is_absolute():+ return (self.working_directory / path_obj).resolve()+ return path_obj.resolve()+ return self.working_directory++ def _resolve_existing_filepath(self, file_path: str) -> Path:+ r"""Resolve a file path without sanitizing the filename."""+ path_obj = Path(file_path)+ if not path_obj.is_absolute():+ path_obj = self.working_directory / path_obj+ return path_obj.resolve()++ def _tool_error(self, message: str) -> str:+ logger.warning(message)+ return f"Error: {message}"+def _sanitize_filename(self, filename: str) -> str:r"""Sanitize a filename by replacing any character that is notalphanumeric, a dot (.), hyphen (-), or underscore (_) with an@@ -116,6 +137,82 @@ class FileToolkit(BaseToolkit):safe = re.sub(r'[^\w\-.]', '_', filename)return safe+ def _iter_grep_candidate_files(+ self,+ root: Path,+ glob_pattern: str,+ file_type: Optional[str],+ ) -> List[Path]:+ suffix = None+ if file_type:+ suffix = f".{file_type.lstrip('.')}".lower()++ candidates: List[Path] = []+ for candidate in root.rglob(glob_pattern):+ if not candidate.is_file():+ continue+ if suffix and candidate.suffix.lower() != suffix:+ continue+ candidates.append(candidate)+ return sorted(candidates)++ def _render_grep_context_block(+ self,+ file_path: Path,+ lines: List[str],+ match_index: int,+ context_lines: int,+ ) -> str:+ start = max(0, match_index - context_lines)+ end = min(len(lines), match_index + context_lines + 1)+ rendered = []+ for index in range(start, end):+ marker = ">" if index == match_index else " "+ rendered.append(+ f"{file_path}:{index + 1}:{marker} " f"{lines[index].rstrip()}"+ )+ return "\n".join(rendered)++ def _render_grep_multiline_block(+ self,+ file_path: Path,+ lines: List[str],+ start_line: int,+ end_line: int,+ context_lines: int,+ ) -> str:+ start = max(1, start_line - context_lines)+ end = min(len(lines), end_line + context_lines)+ rendered = []+ for number in range(start, end + 1):+ marker = ">" if start_line <= number <= end_line else " "+ rendered.append(+ f"{file_path}:{number}:{marker} "+ f"{lines[number - 1].rstrip()}"+ )+ return "\n".join(rendered)++ def _normalize_notebook_source(self, new_source: str) -> List[str]:+ if not new_source:+ return []+ return new_source.splitlines(keepends=True)++ def _build_notebook_cell(+ self,+ new_source: str,+ cell_type: str,+ ) -> Dict[str, Any]:+ cell: Dict[str, Any] = {+ "id": uuid.uuid4().hex[:8],+ "cell_type": cell_type,+ "metadata": {},+ "source": self._normalize_notebook_source(new_source),+ }+ if cell_type == "code":+ cell["execution_count"] = None+ cell["outputs"] = []+ return cell+def _write_text_file(self, file_path: Path, content: str, encoding: str = "utf-8") -> None:@@ -1104,7 +1201,7 @@ class FileToolkit(BaseToolkit):try:# Handle single file path for backward compatibilityif isinstance(file_paths, str):- resolved_path = self._resolve_filepath(file_paths)+ resolved_path = self._resolve_existing_filepath(file_paths)# Use MarkItDownLoader to convert the fileresult = MarkItDownLoader().convert_files(@@ -1119,7 +1216,8 @@ class FileToolkit(BaseToolkit):# Handle multiple file pathselse:resolved_paths = [- str(self._resolve_filepath(fp)) for fp in file_paths+ str(self._resolve_existing_filepath(fp))+ for fp in file_paths]# Use MarkItDownLoader to convert files in parallel@@ -1163,7 +1261,7 @@ class FileToolkit(BaseToolkit):error message if the content wasn't found or an error occurred."""try:- working_path = self._resolve_filepath(file_path)+ working_path = self._resolve_existing_filepath(file_path)if not working_path.exists():return f"Error: File {working_path} does not exist"@@ -1201,6 +1299,304 @@ class FileToolkit(BaseToolkit):except Exception as e:return f"Error editing file: {e}"+ def glob_files(+ self,+ pattern: str,+ path: Optional[str] = None,+ ) -> Union[List[str], str]:+ r"""Find files by glob pattern and sort by modification time.++ Args:+ pattern (str): Glob pattern to match, for example+ :obj:`**/*.js`.+ path (Optional[str]): Optional directory to search from. If not+ provided, the toolkit working directory is used.++ Returns:+ Union[List[str], str]: Matching absolute file paths sorted by most+ recent modification time first, or an error message.+ """+ try:+ root = self._resolve_search_path(path)+ if not root.exists():+ return self._tool_error(f"Search path does not exist: {root}")++ matches = [item for item in root.glob(pattern) if item.is_file()]+ matches.sort(+ key=lambda item: (item.stat().st_mtime, str(item)),+ reverse=True,+ )+ return [str(item.resolve()) for item in matches]+ except Exception as exc:+ return self._tool_error(f"Glob search failed: {exc}")++ def grep_files(+ self,+ pattern: str,+ path: str,+ glob_pattern: str = "*",+ file_type: Optional[str] = None,+ output_mode: str = "content",+ ignore_case: bool = False,+ context_lines: int = 0,+ head_limit: int = 20,+ multiline: bool = False,+ ) -> Any:+ r"""Search file content with a regular expression.++ Args:+ pattern (str): Regular expression to search for.+ path (str): Directory to search recursively.+ glob_pattern (str): Glob filter for candidate files before+ searching content. (default: :obj:`"*"`)+ file_type (Optional[str]): Optional file extension filter without+ requiring the leading dot. (default: :obj:`None`)+ output_mode (str): One of :obj:`content`,+ :obj:`files_with_matches`, or :obj:`count`. (default:+ :obj:`"content"`)+ ignore_case (bool): Whether to search case-insensitively.+ (default: :obj:`False`)+ context_lines (int): Number of surrounding lines to include when+ :obj:`output_mode` is :obj:`content`. (default: :obj:`0`)+ head_limit (int): Maximum number of blocks or file paths to return.+ (default: :obj:`20`)+ multiline (bool): Whether the regex may span multiple lines.+ (default: :obj:`False`)++ Returns:+ Any: Matching content blocks, matching file paths, aggregate+ counts, or an error string depending on :obj:`output_mode`.+ """+ valid_output_modes = {"content", "files_with_matches", "count"}+ if output_mode not in valid_output_modes:+ return self._tool_error(+ f"output_mode must be one of {sorted(valid_output_modes)}."+ )++ try:+ root = self._resolve_search_path(path)+ if not root.exists():+ return self._tool_error(f"Search path does not exist: {root}")++ # Treat head_limit <= 0 as unlimited+ effective_limit = head_limit if head_limit > 0 else float("inf")++ flags = re.MULTILINE+ if ignore_case:+ flags |= re.IGNORECASE+ if multiline:+ flags |= re.DOTALL+ regex = re.compile(pattern, flags)++ blocks: List[str] = []+ files_with_matches: List[str] = []+ total_matches = 0++ for file_path in self._iter_grep_candidate_files(+ root, glob_pattern, file_type+ ):+ try:+ if file_path.stat().st_size > 2_000_000:+ logger.info(+ f"Skipping large file during Grep: {file_path}"+ )+ continue+ text = file_path.read_text(+ encoding=self.default_encoding,+ errors="ignore",+ )+ except OSError:+ continue++ if multiline:+ lines = text.splitlines()+ file_match_count = 0+ for match in regex.finditer(text):+ file_match_count += 1+ total_matches += 1+ if (+ output_mode == "content"+ and len(blocks) < effective_limit+ ):+ start_line = text.count("\n", 0, match.start()) + 1+ end_offset = max(match.end() - 1, match.start())+ end_line = text.count("\n", 0, end_offset) + 1+ blocks.append(+ self._render_grep_multiline_block(+ file_path=file_path,+ lines=lines,+ start_line=start_line,+ end_line=end_line,+ context_lines=context_lines,+ )+ )+ if file_match_count:+ files_with_matches.append(str(file_path.resolve()))+ continue++ lines = text.splitlines()+ file_has_match = False+ for index, line in enumerate(lines):+ if not regex.search(line):+ continue+ file_has_match = True+ total_matches += 1+ if (+ output_mode == "content"+ and len(blocks) < effective_limit+ ):+ blocks.append(+ self._render_grep_context_block(+ file_path=file_path,+ lines=lines,+ match_index=index,+ context_lines=context_lines,+ )+ )+ if file_has_match:+ files_with_matches.append(str(file_path.resolve()))++ if output_mode == "files_with_matches":+ if head_limit > 0:+ return files_with_matches[:head_limit]+ return files_with_matches+ if output_mode == "count":+ return {+ "files_with_matches": len(files_with_matches),+ "matches": total_matches,+ }+ if not blocks:+ return "No matches found."+ if head_limit > 0:+ return "\n--\n".join(blocks[:head_limit])+ return "\n--\n".join(blocks)+ except re.error as exc:+ return self._tool_error(f"Invalid regex pattern: {exc}")+ except Exception as exc:+ return self._tool_error(f"Grep search failed: {exc}")++ def notebook_edit_cell(+ self,+ notebook_path: str,+ new_source: str = "",+ cell_id: Optional[str] = None,+ cell_type: Optional[str] = None,+ edit_mode: str = "replace",+ ) -> str:+ r"""Edit, insert, or delete a cell in a Jupyter notebook.++ Args:+ notebook_path (str): Absolute or working-directory-relative path+ to the notebook file.+ new_source (str): New source for the cell when inserting or+ replacing.+ cell_id (Optional[str]): Target cell ID. Required for replace and+ delete, and used as the insertion anchor when inserting.+ cell_type (Optional[str]): Cell type for inserted cells, or+ optional replacement cell type. Supported values are+ :obj:`code` and :obj:`markdown`.+ edit_mode (str): One of :obj:`replace`, :obj:`insert`, or+ :obj:`delete`.++ Returns:+ str: Confirmation describing the notebook update, or an error+ message.+ """+ import json++ path = self._resolve_existing_filepath(notebook_path)+ if not path.exists():+ return self._tool_error(f"Notebook file not found: {path}")++ try:+ with path.open("r", encoding=self.default_encoding) as file:+ notebook = json.load(file)+ except json.JSONDecodeError:+ return self._tool_error(f"Invalid notebook format: {path}")+ except OSError as exc:+ return self._tool_error(f"Failed to read notebook '{path}': {exc}")++ cells = notebook.get("cells")+ if not isinstance(cells, list):+ return self._tool_error(f"Invalid notebook format: {path}")++ if cell_type is not None and cell_type not in {"code", "markdown"}:+ return self._tool_error(+ "cell_type must be either 'code' or 'markdown'."+ )+ if edit_mode not in {"replace", "insert", "delete"}:+ return self._tool_error(+ "edit_mode must be one of 'replace', 'insert', or 'delete'."+ )++ target_index = None+ if cell_id is not None:+ for index, cell in enumerate(cells):+ if cell.get("id") == cell_id:+ target_index = index+ break++ if edit_mode == "replace":+ if target_index is None:+ return self._tool_error(+ "cell_id must refer to an existing cell for replace."+ )+ if not new_source:+ return self._tool_error("new_source is required for replace.")+ target_cell = cells[target_index]+ target_cell["source"] = self._normalize_notebook_source(new_source)+ if cell_type is not None:+ target_cell["cell_type"] = cell_type+ if cell_type == "code":+ target_cell.setdefault("outputs", [])+ target_cell.setdefault("execution_count", None)+ else:+ target_cell.pop("outputs", None)+ target_cell.pop("execution_count", None)+ result = (+ f"Updated cell '{target_cell.get('id')}' in notebook "+ f"'{path}'."+ )+ elif edit_mode == "insert":+ if not new_source:+ return self._tool_error("new_source is required for insert.")+ target_cell_type = cell_type or "code"+ new_cell = self._build_notebook_cell(+ new_source=new_source,+ cell_type=target_cell_type,+ )+ if target_index is None:+ cells.append(new_cell)+ location = "at the end"+ else:+ cells.insert(target_index + 1, new_cell)+ location = f"after cell '{cell_id}'"+ result = (+ f"Inserted new cell '{new_cell['id']}' {location} in "+ f"notebook '{path}'."+ )+ else:+ if target_index is None:+ return self._tool_error(+ "cell_id must refer to an existing cell for delete."+ )+ removed = cells.pop(target_index)+ result = (+ f"Deleted cell '{removed.get('id')}' from notebook "+ f"'{path}'."+ )++ try:+ with path.open("w", encoding=self.default_encoding) as file:+ json.dump(notebook, file, indent=1, ensure_ascii=False)+ file.write("\n")+ except OSError as exc:+ return self._tool_error(+ f"Failed to write notebook '{path}': {exc}"+ )++ return result+def search_files(self,pattern: str,@@ -1255,15 +1651,7 @@ class FileToolkit(BaseToolkit):import jsontry:- # resolve search path- if path:- path_obj = Path(path)- if not path_obj.is_absolute():- search_path = (self.working_directory / path_obj).resolve()- else:- search_path = path_obj.resolve()- else:- search_path = self.working_directory+ search_path = self._resolve_search_path(path)# validate that search path existsif not search_path.exists():@@ -1281,8 +1669,7 @@ class FileToolkit(BaseToolkit):if file_pattern:# use file_pattern if provided (overrides file_types)- pattern_glob = f"**/{file_pattern}"- matching_files.extend(search_path.rglob(pattern_glob))+ matching_files.extend(search_path.rglob(file_pattern))else:# use file_types if file_pattern not providedif file_types is None:@@ -1297,8 +1684,7 @@ class FileToolkit(BaseToolkit):for file_type in normalized_types:# use rglob for recursive search- pattern_glob = f"**/*.{file_type}"- matching_files.extend(search_path.rglob(pattern_glob))+ matching_files.extend(search_path.rglob(f"*.{file_type}"))# search through files (case-insensitive)matches = []@@ -1379,24 +1765,7 @@ class FileToolkit(BaseToolkit):FunctionTool(self.read_file),FunctionTool(self.edit_file),FunctionTool(self.search_files),+ FunctionTool(self.notebook_edit_cell),+ FunctionTool(self.glob_files),+ FunctionTool(self.grep_files),]---# Backward compatibility: FileWriteToolkit as deprecated alias-class FileWriteToolkit(FileToolkit):- r"""Deprecated: Use FileToolkit instead.-- This class is maintained for backward compatibility only.- Please use FileToolkit for new code.- """-- def __init__(self, *args, **kwargs):- import warnings-- warnings.warn(- "FileWriteToolkit is deprecated and will be removed in a "- "future version. Please use FileToolkit instead.",- DeprecationWarning,- stacklevel=2,- )- super().__init__(*args, **kwargs)diff --git a/camel/toolkits/function_tool.py b/camel/toolkits/function_tool.pyindex 3142df1d4..14b8224bf 100644--- a/camel/toolkits/function_tool.py+++ b/camel/toolkits/function_tool.py@@ -18,10 +18,23 @@ import inspectimport loggingimport textwrapimport threading+import typesimport warningsfrom concurrent.futures import ThreadPoolExecutorfrom inspect import Parameter, getsource, signature-from typing import Any, Callable, Dict, Mapping, Optional, Tuple, Type+from typing import (+ Any,+ Callable,+ Dict,+ List,+ Mapping,+ Optional,+ Tuple,+ Type,+ Union,+ get_args,+ get_origin,+)from docstring_parser import parsefrom jsonschema.exceptions import SchemaError@@ -43,6 +56,120 @@ _PERSISTENT_LOOP: Optional[asyncio.AbstractEventLoop] = None_PERSISTENT_LOOP_LOCK = threading.Lock()+def _annotation_accepts(annotation: Any, value: Any) -> bool:+ r"""Quick structural check: could *annotation* plausibly apply to *value*?++ Used by the Union handler to skip branches that clearly don't match+ before attempting (potentially failing) coercion.+ """+ # BaseModel annotation expects a dict (to coerce) or an instance+ if isinstance(annotation, type) and issubclass(annotation, BaseModel):+ return isinstance(value, (dict, annotation))++ origin = get_origin(annotation)+ if origin is list:+ return isinstance(value, list)+ if origin is dict:+ return isinstance(value, dict)+ if origin in (Union, types.UnionType):+ return True # handled recursively+ # For unknown/primitive annotations we can't tell — be conservative+ return False+++def _coerce_arg(value: Any, annotation: Any) -> Any:+ r"""Coerce *value* so that plain dicts become Pydantic model instances+ where the function signature expects them.++ Handles ``Model``, ``List[Model]``, ``Dict[str, Model]``,+ ``Optional[...]``, and ``Union[...]`` annotations recursively.+ Non-model annotations are returned unchanged.+ """+ # --- Plain BaseModel subclass (e.g. ``param: TodoItem``) ---+ if isinstance(annotation, type) and issubclass(annotation, BaseModel):+ if isinstance(value, dict):+ return annotation.model_validate(value)+ return value++ origin = get_origin(annotation)+ args = get_args(annotation)++ if origin is None or not args:+ return value++ # --- List[X] / list[X] ---+ if origin is list:+ if isinstance(value, list):+ inner = args[0]+ return [_coerce_arg(item, inner) for item in value]+ return value++ # --- Dict[K, V] / dict[K, V] — coerce values only ---+ if origin is dict:+ if isinstance(value, dict) and len(args) == 2:+ val_ann = args[1]+ return {k: _coerce_arg(v, val_ann) for k, v in value.items()}+ return value++ # --- Optional[X] / Union[X, Y, ...] — try each inner type ---+ if origin in (Union, types.UnionType):+ validation_error = None+ for inner in args:+ if inner is type(None):+ if value is None:+ return value+ continue+ if not _annotation_accepts(inner, value):+ continue+ try:+ coerced = _coerce_arg(value, inner)+ except Exception as exc:+ validation_error = exc+ continue+ return coerced+ if validation_error is not None:+ raise validation_error+ return value++ return value+++def _coerce_arguments(+ func: Callable,+ args: tuple,+ kwargs: Dict[str, Any],+) -> Tuple[tuple, Dict[str, Any]]:+ r"""Coerce positional and keyword arguments to match Pydantic model+ type annotations in *func*'s signature.++ This bridges the gap between the JSON dicts that the LLM produces (via+ ``json.loads``) and the Pydantic models that toolkit authors declare in+ their function signatures. Plain values and non-model parameters are+ passed through unchanged.+ """+ params = signature(func).parameters+ param_list = list(params.values())++ # --- positional args ---+ new_args: List[Any] = []+ for i, val in enumerate(args):+ if i < len(param_list):+ p = param_list[i]+ if p.annotation is not Parameter.empty:+ val = _coerce_arg(val, p.annotation)+ new_args.append(val)++ # --- keyword args ---+ new_kwargs: Dict[str, Any] = {}+ for key, val in kwargs.items():+ kw_param = params.get(key)+ if kw_param is not None and kw_param.annotation is not Parameter.empty:+ val = _coerce_arg(val, kw_param.annotation)+ new_kwargs[key] = val++ return tuple(new_args), new_kwargs++def _remove_a_key(d: Dict, remove_key: Any) -> None:r"""Remove a key from a dictionary recursively."""if isinstance(d, dict):@@ -488,7 +615,17 @@ class FunctionTool:result = self.synthesize_execution_output(args, kwargs)return result- # Call the function first+ # Coerce dict arguments to Pydantic models where the function+ # signature expects them (e.g. List[TodoItem]).+ try:+ args, kwargs = _coerce_arguments(self.func, args, kwargs)+ except Exception as e:+ raise ValueError(+ f"Argument coercion for function {self.func.__name__} "+ f"failed. Error: {e}"+ )++ # Call the functiontry:result = self.func(*args, **kwargs)except Exception as e:@@ -566,6 +703,16 @@ class FunctionTool:result = self.synthesize_execution_output(args, kwargs)return result+ # Coerce dict arguments to Pydantic models where the function+ # signature expects them.+ try:+ args, kwargs = _coerce_arguments(self.func, args, kwargs)+ except Exception as e:+ raise ValueError(+ f"Argument coercion for function {self.func.__name__} "+ f"failed. Error: {e}"+ )+# Check if the function itself (not unwrapped) is a coroutine functionif inspect.iscoroutinefunction(self.func):return await self.func(*args, **kwargs)diff --git a/camel/toolkits/planning_worktree_toolkit.py b/camel/toolkits/planning_worktree_toolkit.pynew file mode 100644index 000000000..96ddfd720--- /dev/null+++ b/camel/toolkits/planning_worktree_toolkit.py@@ -0,0 +1,387 @@+# ========= 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. =========++import os+import re+import subprocess+import threading+import time+from pathlib import Path+from typing import Any, ClassVar, Dict, List, Optional++from camel.logger import get_logger+from camel.toolkits.base import BaseToolkit+from camel.toolkits.function_tool import FunctionTool+from camel.utils import MCPServer++logger = get_logger(__name__)+++@MCPServer()+class PlanningWorktreeToolkit(BaseToolkit):+ r"""Toolkit for plan-mode state and git worktree management.++ Each toolkit instance owns an independent plan file determined by+ *working_directory* and *plan_file_name*. A class-level lock registry+ ensures that concurrent agents sharing the same plan file do not+ corrupt each other's writes.++ Args:+ working_directory (Optional[str]): The directory to use as the+ working root. Falls back to the ``CAMEL_WORKDIR`` environment+ variable, then the current working directory.+ (default: :obj:`None`)+ timeout (Optional[float]): The timeout for the toolkit.+ (default: :obj:`None`)+ plan_file_name (str): Name of the Markdown plan file created inside+ *working_directory*. (default: :obj:`".camel-plan.md"`)+ switch_process_cwd (bool): If :obj:`True`, ``os.chdir`` will be+ called when entering/leaving a worktree so the whole process+ sees the new directory. (default: :obj:`False`)+ """++ _plan_locks: ClassVar[Dict[str, threading.Lock]] = {}+ _plan_locks_guard = threading.Lock()++ def __init__(+ self,+ working_directory: Optional[str] = None,+ timeout: Optional[float] = None,+ plan_file_name: str = ".camel-plan.md",+ switch_process_cwd: bool = False,+ ) -> None:+ super().__init__(timeout=timeout)+ if working_directory is not None:+ self.working_directory = Path(working_directory).resolve()+ else:+ camel_workdir = os.environ.get("CAMEL_WORKDIR")+ if camel_workdir:+ self.working_directory = Path(camel_workdir).resolve()+ else:+ self.working_directory = Path.cwd().resolve()+ self.plan_file_name = plan_file_name+ self.switch_process_cwd = switch_process_cwd+ self.plan_mode_active = False+ self.current_worktree_path: Optional[Path] = None++ def _plan_file_path(self) -> Path:+ return self.working_directory / self.plan_file_name++ def _plan_lock(self) -> threading.Lock:+ key = str(self._plan_file_path())+ with PlanningWorktreeToolkit._plan_locks_guard:+ if key not in PlanningWorktreeToolkit._plan_locks:+ PlanningWorktreeToolkit._plan_locks[key] = threading.Lock()+ return PlanningWorktreeToolkit._plan_locks[key]++ def _error_result(self, message: str, **payload: Any) -> Dict[str, Any]:+ logger.warning(message)+ result: Dict[str, Any] = {"error": f"Error: {message}"}+ result.update(payload)+ return result++ def _run_git(+ self,+ *args: str,+ cwd: Optional[Path] = None,+ ) -> subprocess.CompletedProcess[str]:+ return subprocess.run(+ ["git", *args],+ cwd=cwd or self.working_directory,+ capture_output=True,+ text=True,+ check=False,+ )++ def planning_enter_plan_mode(self) -> Dict[str, Any]:+ r"""Mark the toolkit as being in plan mode.++ Returns:+ Dict[str, Any]: Plan mode status and plan file location.+ """+ with self._plan_lock():+ plan_file = self._plan_file_path()+ try:+ if not plan_file.exists():+ plan_file.write_text(+ "# Plan\n\n"+ "- Objective:\n"+ "- Constraints:\n"+ "- Steps:\n",+ encoding="utf-8",+ )+ except OSError as exc:+ self.plan_mode_active = False+ return self._error_result(+ f"Failed to initialize plan file '{plan_file}': {exc}",+ plan_mode=False,+ plan_file_path=str(plan_file),+ working_directory=str(self.working_directory),+ )+ self.plan_mode_active = True+ return {+ "plan_mode": True,+ "plan_file_path": str(plan_file),+ "working_directory": str(self.working_directory),+ }++ def planning_exit_plan_mode(+ self,+ allowed_prompts: Optional[List[Dict[str, str]]] = None,+ ) -> Dict[str, Any]:+ r"""Exit plan mode and return the current plan for approval.++ Args:+ allowed_prompts (Optional[List[Dict[str, str]]]): Optional list of+ tool/prompt pairs that are allowed after plan approval.++ Returns:+ Dict[str, Any]: Current plan content together with the supplied+ allowed prompts.+ """+ with self._plan_lock():+ if not self.plan_mode_active:+ return self._error_result(+ "Plan mode is not active.",+ plan_mode=False,+ plan_file_path=str(self._plan_file_path()),+ allowed_prompts=allowed_prompts or [],+ )++ plan_file = self._plan_file_path()+ try:+ plan_content = (+ plan_file.read_text(encoding="utf-8")+ if plan_file.exists()+ else ""+ )+ except OSError as exc:+ self.plan_mode_active = False+ return self._error_result(+ f"Failed to read plan file '{plan_file}': {exc}",+ plan_mode=False,+ plan_file_path=str(plan_file),+ allowed_prompts=allowed_prompts or [],+ )+ self.plan_mode_active = False+ return {+ "plan_mode": False,+ "plan_file_path": str(plan_file),+ "plan_content": plan_content,+ "allowed_prompts": allowed_prompts or [],+ }++ def worktree_enter_worktree(+ self,+ name: Optional[str] = None,+ ) -> Dict[str, Any]:+ r"""Create and switch this toolkit to a dedicated git worktree.++ Args:+ name (Optional[str]): Optional worktree name seed.++ Returns:+ Dict[str, Any]: Created branch name, worktree path, and active+ working directory.+ """+ if self.current_worktree_path is not None:+ return self._error_result(+ "Already inside a worktree. Call "+ "worktree_remove_worktree() first.",+ working_directory=str(self.working_directory),+ current_worktree=str(self.current_worktree_path),+ )++ try:+ repo_root_result = self._run_git(+ "rev-parse",+ "--show-toplevel",+ cwd=self.working_directory,+ )+ if repo_root_result.returncode != 0:+ return self._error_result(+ repo_root_result.stderr.strip()+ or repo_root_result.stdout.strip()+ or "Failed to determine the git repository root.",+ working_directory=str(self.working_directory),+ )+ repo_root = Path(repo_root_result.stdout.strip()).resolve()++ safe_name = re.sub(r"[^a-zA-Z0-9._-]+", "-", name or "").strip("-")+ if not safe_name:+ safe_name = f"session-{time.strftime('%Y%m%d-%H%M%S')}"++ worktree_base = repo_root.parent / f".{repo_root.name}_worktrees"+ worktree_base.mkdir(parents=True, exist_ok=True)++ max_suffix = 100+ suffix = 0+ while suffix <= max_suffix:+ candidate_name = (+ safe_name if suffix == 0 else f"{safe_name}-{suffix}"+ )+ branch_name = f"camel/{candidate_name}"+ worktree_path = worktree_base / candidate_name+ branch_exists = (+ self._run_git(+ "show-ref",+ "--verify",+ "--quiet",+ f"refs/heads/{branch_name}",+ cwd=repo_root,+ ).returncode+ == 0+ )+ if not branch_exists and not worktree_path.exists():+ break+ suffix += 1+ else:+ return self._error_result(+ f"Too many worktree name collisions for '{safe_name}'.",+ working_directory=str(self.working_directory),+ )++ add_result = self._run_git(+ "worktree",+ "add",+ "-b",+ branch_name,+ str(worktree_path),+ "HEAD",+ cwd=repo_root,+ )+ if add_result.returncode != 0:+ return self._error_result(+ add_result.stderr.strip()+ or add_result.stdout.strip()+ or "Failed to create git worktree.",+ working_directory=str(self.working_directory),+ )++ self.current_worktree_path = worktree_path.resolve()+ self.working_directory = self.current_worktree_path+ if self.switch_process_cwd:+ os.chdir(self.current_worktree_path)++ return {+ "branch": branch_name,+ "worktree_path": str(self.current_worktree_path),+ "working_directory": str(self.working_directory),+ "process_cwd_switched": self.switch_process_cwd,+ }+ except Exception as exc:+ return self._error_result(+ f"Failed to create worktree: {exc}",+ working_directory=str(self.working_directory),+ )++ def worktree_remove_worktree(self) -> Dict[str, Any]:+ r"""Remove the current worktree and its branch, restoring the+ original working directory.++ Returns:+ Dict[str, Any]: Removal status and restored working directory.+ """+ if self.current_worktree_path is None:+ return self._error_result(+ "No active worktree to remove.",+ working_directory=str(self.working_directory),+ )++ worktree_path = self.current_worktree_path+ try:+ repo_root_result = self._run_git(+ "rev-parse",+ "--show-toplevel",+ cwd=worktree_path,+ )+ if repo_root_result.returncode != 0:+ return self._error_result(+ repo_root_result.stderr.strip()+ or "Failed to determine repository root from worktree.",+ working_directory=str(self.working_directory),+ )++ branch_result = self._run_git(+ "rev-parse",+ "--abbrev-ref",+ "HEAD",+ cwd=worktree_path,+ )+ branch_name = branch_result.stdout.strip()++ main_repo_result = self._run_git(+ "worktree",+ "list",+ "--porcelain",+ cwd=worktree_path,+ )+ # The first "worktree ..." entry is always the main repo.+ main_repo_path: Optional[Path] = None+ for line in main_repo_result.stdout.splitlines():+ if line.startswith("worktree "):+ main_repo_path = Path(line.split(" ", 1)[1]).resolve()+ break++ if main_repo_path is None:+ return self._error_result(+ "Could not determine the main repository path.",+ working_directory=str(self.working_directory),+ )++ self.working_directory = main_repo_path+ self.current_worktree_path = None+ if self.switch_process_cwd:+ os.chdir(main_repo_path)++ remove_result = self._run_git(+ "worktree",+ "remove",+ str(worktree_path),+ "--force",+ cwd=main_repo_path,+ )+ if remove_result.returncode != 0:+ return self._error_result(+ remove_result.stderr.strip()+ or "Failed to remove worktree.",+ working_directory=str(self.working_directory),+ )++ if branch_name:+ self._run_git(+ "branch",+ "-d",+ branch_name,+ cwd=main_repo_path,+ )++ return {+ "removed_worktree": str(worktree_path),+ "removed_branch": branch_name,+ "working_directory": str(self.working_directory),+ }+ except Exception as exc:+ return self._error_result(+ f"Failed to remove worktree: {exc}",+ working_directory=str(self.working_directory),+ )++ def get_tools(self) -> List[FunctionTool]:+ return [+ FunctionTool(self.planning_enter_plan_mode),+ FunctionTool(self.planning_exit_plan_mode),+ FunctionTool(self.worktree_enter_worktree),+ FunctionTool(self.worktree_remove_worktree),+ ]diff --git a/camel/toolkits/todo_toolkit.py b/camel/toolkits/todo_toolkit.pynew file mode 100644index 000000000..5b7fc870b--- /dev/null+++ b/camel/toolkits/todo_toolkit.py@@ -0,0 +1,184 @@+# ========= 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. =========++import json+import threading+from pathlib import Path+from typing import List, Literal, Optional++from pydantic import BaseModel, ValidationError++from camel.logger import get_logger+from camel.toolkits import FunctionTool+from camel.toolkits.base import BaseToolkit+from camel.utils import MCPServer++logger = get_logger(__name__)++_STATUS_EMOJI = {+ "pending": "⬜",+ "in_progress": "🔄",+ "completed": "✅",+}+++class TodoItem(BaseModel):+ r"""Schema for a single todo item.++ Attributes:+ content: A brief, actionable title for the task.+ active_form: Present-continuous label shown in a UI spinner while+ the task is in progress.+ status: Current status of the task.+ """++ content: str+ active_form: str+ status: Literal["pending", "in_progress", "completed"]+++@MCPServer()+class TodoToolkit(BaseToolkit):+ r"""A toolkit for managing a todo list persisted to local files.++ The toolkit exposes a single :obj:`todo_write` tool that lets an agent+ replace the current todo list with a new set of items. Each item carries+ a short content string, an active-form label for UI spinners, and a+ status drawn from ``pending``, ``in_progress``, or ``completed``.++ Two files are maintained inside *working_dir*:++ - ``todo.md`` — a clean, human-readable Markdown checklist.+ - ``.todo.json`` — structured data used to reload state across sessions.++ A thread lock prevents concurrent write conflicts within the same+ process.++ Args:+ working_dir (Optional[str]): Directory where files are stored.+ Defaults to the current working directory.+ timeout (Optional[float]): The timeout for the toolkit.+ (default: :obj:`None`)+ """++ def __init__(+ self,+ working_dir: Optional[str] = None,+ timeout: Optional[float] = None,+ ):+ super().__init__(timeout=timeout)+ self._working_dir = Path(working_dir) if working_dir else Path.cwd()+ self._md_path = self._working_dir / "todo.md"+ self._json_path = self._working_dir / ".todo.json"+ self._lock = threading.Lock()+ with self._lock:+ self.todos: List[TodoItem] = self._load()++ # ── persistence helpers ──────────────────────────────────────────++ def _load(self) -> List[TodoItem]:+ r"""Load todos from the JSON data file, if it exists."""+ if not self._json_path.exists():+ return []+ try:+ data = json.loads(self._json_path.read_text(encoding="utf-8"))+ except (json.JSONDecodeError, OSError) as exc:+ logger.warning(+ "Failed to read %s, starting with empty list: %s",+ self._json_path,+ exc,+ )+ return []+ if not isinstance(data, list):+ logger.warning(+ "Expected a JSON array in %s, got %s; starting with empty "+ "list.",+ self._json_path,+ type(data).__name__,+ )+ return []+ items: List[TodoItem] = []+ for entry in data:+ try:+ items.append(TodoItem.model_validate(entry))+ except ValidationError as exc:+ logger.warning(+ "Skipping malformed todo entry in %s: %s",+ self._json_path,+ exc,+ )+ return items++ def _save(self) -> None:+ r"""Write todos to both the JSON data file and the Markdown file."""+ self._working_dir.mkdir(parents=True, exist_ok=True)+ # JSON — source of truth for reloading+ self._json_path.write_text(+ json.dumps(+ [item.model_dump() for item in self.todos],+ ensure_ascii=False,+ indent=2,+ )+ + "\n",+ encoding="utf-8",+ )+ # Markdown — clean, human-readable view+ lines = ["# Todo", ""]+ for item in self.todos:+ emoji = _STATUS_EMOJI.get(item.status, "⬜")+ lines.append(f"- {emoji} {item.content}")+ self._md_path.write_text("\n".join(lines) + "\n", encoding="utf-8")++ # ── tool methods ─────────────────────────────────────────────────++ def todo_write(+ self,+ todos: List[TodoItem],+ ) -> str:+ r"""Replace the current todo list with a new set of items.++ Args:+ todos (List[TodoItem]): The new todo list that will replace+ the current one.++ Returns:+ str: A success message, or an error string prefixed with+ ``[ERROR]`` if validation fails.+ """+ # Validate & normalise: accept both TodoItem instances (from+ # FunctionTool coercion) and raw dicts (from direct calls).+ validated: List[TodoItem] = []+ try:+ for item in todos:+ if isinstance(item, TodoItem):+ validated.append(item)+ else:+ validated.append(TodoItem.model_validate(item))+ except ValidationError as exc:+ return f"[ERROR] Failed to update todos: {exc}"++ with self._lock:+ self.todos = validated+ self._save()+ return "Todos have been modified successfully."++ def get_tools(self) -> List[FunctionTool]:+ r"""Get all tools in the toolkit.++ Returns:+ List[FunctionTool]: A list of tools.+ """+ return [+ FunctionTool(self.todo_write),+ ]diff --git a/camel/toolkits/web_fetch_toolkit.py b/camel/toolkits/web_fetch_toolkit.pynew file mode 100644index 000000000..b7a811ff6--- /dev/null+++ b/camel/toolkits/web_fetch_toolkit.py@@ -0,0 +1,205 @@+# ========= 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. =========++import html+import re+from typing import TYPE_CHECKING, List, Optional, Union+from urllib.parse import urlparse++import httpx++from camel.logger import get_logger+from camel.models import BaseModelBackend, ModelManager+from camel.toolkits.base import BaseToolkit, RegisteredAgentToolkit+from camel.toolkits.function_tool import FunctionTool++if TYPE_CHECKING:+ from camel.agents import ChatAgent++logger = get_logger(__name__)++_ALLOWED_SCHEMES = ("http", "https")+++class WebFetchToolkit(BaseToolkit, RegisteredAgentToolkit):+ r"""Toolkit for fetching a web page and summarizing it for a prompt."""++ def __init__(+ self,+ default_model: Optional[BaseModelBackend] = None,+ timeout: Optional[float] = None,+ request_timeout: float = 20.0,+ ) -> None:+ super().__init__(timeout=timeout)+ RegisteredAgentToolkit.__init__(self)+ self.default_model = default_model+ self.request_timeout = request_timeout+ self._summary_agent: Optional["ChatAgent"] = None+ self._summary_agent_model: Optional[+ Union[BaseModelBackend, ModelManager]+ ] = None+ self._summary_agent_language: Optional[str] = None++ def _error_message(self, message: str) -> str:+ logger.warning(message)+ return f"Error: {message}"++ def _resolve_model(+ self,+ ) -> Optional[Union[BaseModelBackend, ModelManager]]:+ if self._agent is not None:+ return self._agent.model_backend+ return self.default_model++ def _extract_text(self, content_type: str, body: str) -> str:+ if "html" not in content_type.lower():+ return body.strip()++ body = re.sub(+ r"(?is)<(script|style|noscript).*?>.*?</\1>",+ " ",+ body,+ )+ body = re.sub(r"(?s)<!--.*?-->", " ", body)+ body = re.sub(r"(?s)<[^>]+>", " ", body)+ body = html.unescape(body)+ body = re.sub(r"[ \t]+", " ", body)+ body = re.sub(r"\n\s*\n+", "\n\n", body)+ return body.strip()++ def _get_summary_agent(self) -> Optional["ChatAgent"]:+ from camel.agents import ChatAgent++ model = self._resolve_model()+ if model is None:+ return None++ output_language = (+ self._agent.output_language if self._agent is not None else None+ )++ # Reuse cached agent only if model and language haven't changed+ if (+ self._summary_agent is not None+ and self._summary_agent_model is model+ and self._summary_agent_language == output_language+ ):+ self._summary_agent.reset()+ return self._summary_agent++ self._summary_agent = ChatAgent(+ system_message=(+ "You analyze fetched web pages and answer the user's prompt "+ "using only the provided page content."+ ),+ model=model,+ output_language=output_language,+ )+ self._summary_agent_model = model+ self._summary_agent_language = output_language+ return self._summary_agent++ def web_fetch_and_analyze(+ self, url: str, prompt: str, max_chars: int = 0+ ) -> str:+ r"""Fetch a URL and answer a prompt about its content.++ Args:+ url (str): URL to fetch.+ prompt (str): Instruction describing what to extract or analyze+ from the fetched page.+ max_chars (int): Maximum number of characters of page content to+ use. When set to 0 (default) the full page is sent to the+ summarizer. If the summarizer fails because the content is+ too long, retry with a smaller value.++ Returns:+ str: AI-processed summary or answer derived from the page content.+ """+ parsed = urlparse(url)+ if parsed.scheme not in _ALLOWED_SCHEMES:+ return self._error_message(+ f"URL scheme '{parsed.scheme}' is not allowed. "+ f"Only {_ALLOWED_SCHEMES} are supported."+ )++ try:+ with httpx.Client(+ follow_redirects=True,+ timeout=self.request_timeout,+ headers={+ "User-Agent": (+ "Mozilla/5.0 (compatible; CAMEL WebFetchToolkit/1.0)"+ )+ },+ ) as client:+ http_response = client.get(url)+ except httpx.HTTPError as exc:+ return self._error_message(f"Failed to fetch {url}: {exc}")+ except Exception as exc:+ return self._error_message(+ f"Unexpected WebFetch request failure for {url}: {exc}"+ )++ if http_response.is_error:+ return self._error_message(+ f"Failed to fetch {url}: HTTP {http_response.status_code}"+ )++ page_text = self._extract_text(+ http_response.headers.get("content-type", ""),+ http_response.text,+ )+ if not page_text:+ return self._error_message(f"No readable content found at {url}")++ total_chars = len(page_text)+ if max_chars > 0:+ page_text = page_text[:max_chars]++ try:+ summary_agent = self._get_summary_agent()+ except Exception as exc:+ return self._error_message(+ f"Failed to create WebFetch summary agent: {exc}"+ )+ if summary_agent is None:+ return self._error_message(+ "WebFetchToolkit requires a registered parent agent or "+ "default_model."+ )++ try:+ agent_response = summary_agent.step(+ "Analyze the following fetched page content.\n\n"+ f"URL: {url}\n"+ f"User prompt: {prompt}\n\n"+ "Page content:\n"+ f"{page_text}"+ )+ except Exception as exc:+ return self._error_message(+ f"WebFetch summarizer failed for {url} "+ f"(page has {total_chars} chars). "+ f"You may retry with a smaller max_chars value. "+ f"Original error: {exc}"+ )+ if not agent_response.msgs:+ return self._error_message(+ "WebFetch summarizer returned no messages."+ )+ return agent_response.msgs[0].content++ def get_tools(self) -> List[FunctionTool]:+ return [FunctionTool(self.web_fetch_and_analyze)]diff --git a/camel/utils/mcp.py b/camel/utils/mcp.pyindex e4bc5b370..df393917c 100644--- a/camel/utils/mcp.py+++ b/camel/utils/mcp.py@@ -236,20 +236,33 @@ class MCPServer:"Please specify function names or use BaseToolkit.")- function_names = self.function_names- if not function_names and isinstance(instance, BaseToolkit):- function_names = [- tool.get_function_name() for tool in instance.get_tools()- ]-- for name in function_names:- func = getattr(instance, name, None)- if func is None or not callable(func):- raise ValueError(- f"Method {name} not found in class {cls.__name__} or "- "cannot be called."+ tool_entries: List[Tuple[str, Callable[..., Any]]] = []+ if not self.function_names and isinstance(instance, BaseToolkit):+ for tool in instance.get_tools():+ name = tool.get_function_name()+ func = getattr(+ tool,+ "mcp_registration_func",+ tool.func,)-+ if func is None or not callable(func):+ raise ValueError(+ f"Tool {name} in class {cls.__name__} does not "+ "provide a callable MCP registration function."+ )+ tool_entries.append((name, func))+ else:+ function_names = self.function_names or []+ for name in function_names:+ func = getattr(instance, name, None)+ if func is None or not callable(func):+ raise ValueError(+ f"Method {name} not found in class {cls.__name__} "+ "or cannot be called."+ )+ tool_entries.append((name, func))++ for name, func in tool_entries:# Validate function types for Pydantic compatibilitytype_errors = _validate_function_types(func)if type_errors:diff --git a/docs/mintlify/docs.json b/docs/mintlify/docs.jsonindex 91ad229b8..f4b606cdd 100644--- a/docs/mintlify/docs.json+++ b/docs/mintlify/docs.json@@ -521,7 +521,6 @@"reference/camel.toolkits.edgeone_pages_mcp_toolkit","reference/camel.toolkits.excel_toolkit","reference/camel.toolkits.file_toolkit",- "reference/camel.toolkits.file_write_toolkit","reference/camel.toolkits.function_tool","reference/camel.toolkits.github_toolkit","reference/camel.toolkits.gmail_toolkit",diff --git a/docs/mintlify/reference/camel.toolkits.file_toolkit.mdx b/docs/mintlify/reference/camel.toolkits.file_toolkit.mdxindex 5e6c257b8..340c1dfb0 100644--- a/docs/mintlify/reference/camel.toolkits.file_toolkit.mdx+++ b/docs/mintlify/reference/camel.toolkits.file_toolkit.mdx@@ -33,7 +33,7 @@ def __init__():```-Initialize the FileWriteToolkit.+Initialize the FileToolkit.**Parameters:**@@ -573,23 +573,3 @@ def get_tools(self):List[FunctionTool]: A list of FunctionTool objects representingthe available functions in this toolkit.-<a id="camel.toolkits.file_toolkit.FileWriteToolkit"></a>--## FileWriteToolkit--```python-class FileWriteToolkit(FileToolkit):-```--Deprecated: Use FileToolkit instead.--This class is maintained for backward compatibility only.-Please use FileToolkit for new code.--<a id="camel.toolkits.file_toolkit.FileWriteToolkit.__init__"></a>--### __init__--```python-def __init__(self, *args, **kwargs):-```diff --git a/docs/mintlify/reference/camel.toolkits.file_write_toolkit.mdx b/docs/mintlify/reference/camel.toolkits.file_write_toolkit.mdxdeleted file mode 100644index 929aed169..000000000--- a/docs/mintlify/reference/camel.toolkits.file_write_toolkit.mdx+++ /dev/null@@ -1,453 +0,0 @@-<a id="camel.toolkits.file_write_toolkit"></a>--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit"></a>--## FileWriteToolkit--```python-class FileWriteToolkit(BaseToolkit):-```--A toolkit for creating, writing, and modifying text in files.--This class provides cross-platform (macOS, Linux, Windows) support for-writing to various file formats (Markdown, DOCX, PDF, and plaintext),-replacing text in existing files, automatic filename uniquification to-prevent overwrites, custom encoding and enhanced formatting options for-specialized formats.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit.__init__"></a>--### __init__--```python-def __init__(- self,- working_directory: Optional[str] = None,- timeout: Optional[float] = None,- default_encoding: str = 'utf-8',- backup_enabled: bool = True-):-```--Initialize the FileWriteToolkit.--**Parameters:**--- **working_directory** (str, optional): The default directory for output files. If not provided, it will be determined by the `CAMEL_WORKDIR` environment variable (if set). If the environment variable is not set, it defaults to `camel_working_dir`.-- **timeout** (Optional[float]): The timeout for the toolkit. (default: :obj:`None`)-- **default_encoding** (str): Default character encoding for text operations. (default: :obj:`utf-8`)-- **backup_enabled** (bool): Whether to create backups of existing files before overwriting. (default: :obj:`True`)--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._resolve_filepath"></a>--### _resolve_filepath--```python-def _resolve_filepath(self, file_path: str):-```--Convert the given string path to a Path object.--If the provided path is not absolute, it is made relative to the-default output directory. The filename part is sanitized to replace-spaces and special characters with underscores, ensuring safe usage-in downstream processing.--**Parameters:**--- **file_path** (str): The file path to resolve.--**Returns:**-- Path: A fully resolved (absolute) and sanitized Path object.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._sanitize_filename"></a>--### _sanitize_filename--```python-def _sanitize_filename(self, filename: str):-```--Sanitize a filename by replacing any character that is not-alphanumeric, a dot (.), hyphen (-), or underscore (_) with an-underscore (_).--**Parameters:**--- **filename** (str): The original filename which may contain spaces or special characters.--**Returns:**-- str: The sanitized filename with disallowed characters replaced by-underscores.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._write_text_file"></a>--### _write_text_file--```python-def _write_text_file(- self,- file_path: Path,- content: str,- encoding: str = 'utf-8'-):-```--Write text content to a plaintext file.--**Parameters:**--- **file_path** (Path): The target file path.-- **content** (str): The text content to write.-- **encoding** (str): Character encoding to use. (default: :obj:`utf-8`) (default: utf-8)--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._generate_unique_filename"></a>--### _generate_unique_filename--```python-def _generate_unique_filename(self, file_path: Path):-```--Generate a unique filename if the target file already exists.--**Parameters:**--- **file_path** (Path): The original file path.--**Returns:**-- Path: A unique file path that doesn't exist yet.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._write_docx_file"></a>--### _write_docx_file--```python-def _write_docx_file(self, file_path: Path, content: str):-```--Write text content to a DOCX file with default formatting.--**Parameters:**--- **file_path** (Path): The target file path.-- **content** (str): The text content to write.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._write_pdf_file"></a>--### _write_pdf_file--```python-def _write_pdf_file(- self,- file_path: Path,- title: str,- content: Union[str, List[List[str]]],- use_latex: bool = False-):-```--Write text content to a PDF file with LaTeX and table support.--**Parameters:**--- **file_path** (Path): The target file path.-- **title** (str): The document title.-- **content** (Union[str, List[List[str]]]): The content to write. Can-- **be**: - String: Supports Markdown-style tables and LaTeX math expressions - List[List[str]]: Table data as list of rows for direct table rendering-- **use_latex** (bool): Whether to use LaTeX for math rendering. (default: :obj:`False`)--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._process_text_content"></a>--### _process_text_content--```python-def _process_text_content(- self,- story,- content: str,- heading_style,- body_style-):-```--Process text content and add to story.--**Parameters:**--- **story**: The reportlab story list to append to-- **content** (str): The text content to process-- **heading_style**: Style for headings-- **body_style**: Style for body text--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._find_table_line_ranges"></a>--### _find_table_line_ranges--```python-def _find_table_line_ranges(self, lines: List[str]):-```--Find line ranges that contain markdown tables.--**Parameters:**--- **lines** (List[str]): List of lines to analyze.--**Returns:**-- List[Tuple[int, int]]: List of (start_line, end_line) tuples-for table ranges.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._register_chinese_font"></a>--### _register_chinese_font--```python-def _register_chinese_font(self):-```--**Returns:**-- str: The font name to use for Chinese text.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._parse_markdown_table"></a>--### _parse_markdown_table--```python-def _parse_markdown_table(self, lines: List[str]):-```--Parse markdown-style tables from a list of lines.--**Parameters:**--- **lines** (List[str]): List of text lines that may contain tables.--**Returns:**-- List[List[List[str]]]: List of tables, where each table is a list-of rows, and each row is a list of cells.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._is_table_row"></a>--### _is_table_row--```python-def _is_table_row(self, line: str):-```--Check if a line appears to be a table row.--**Parameters:**--- **line** (str): The line to check.--**Returns:**-- bool: True if the line looks like a table row.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._is_table_separator"></a>--### _is_table_separator--```python-def _is_table_separator(self, line: str):-```--Check if a line is a table separator (e.g., |---|---|).--**Parameters:**--- **line** (str): The line to check.--**Returns:**-- bool: True if the line is a table separator.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._parse_table_row"></a>--### _parse_table_row--```python-def _parse_table_row(self, line: str):-```--Parse a single table row into cells.--**Parameters:**--- **line** (str): The table row line.--**Returns:**-- List[str]: List of cell contents.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._create_pdf_table"></a>--### _create_pdf_table--```python-def _create_pdf_table(self, table_data: List[List[str]]):-```--Create a formatted table for PDF.--**Parameters:**--- **table_data** (List[List[str]]): Table data as list of rows.--**Returns:**-- Table: A formatted reportlab Table object.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._convert_markdown_to_html"></a>--### _convert_markdown_to_html--```python-def _convert_markdown_to_html(self, text: str):-```--Convert basic markdown formatting to HTML for PDF rendering.--**Parameters:**--- **text** (str): Text with markdown formatting.--**Returns:**-- str: Text with HTML formatting.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._ensure_html_utf8_meta"></a>--### _ensure_html_utf8_meta--```python-def _ensure_html_utf8_meta(self, content: str):-```--Ensure HTML content has UTF-8 meta tag.--**Parameters:**--- **content** (str): The HTML content.--**Returns:**-- str: HTML content with UTF-8 meta tag.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._write_csv_file"></a>--### _write_csv_file--```python-def _write_csv_file(- self,- file_path: Path,- content: Union[str, List[List]],- encoding: str = 'utf-8'-):-```--Write CSV content to a file.--**Parameters:**--- **file_path** (Path): The target file path.-- **content** (Union[str, List[List]]): The CSV content as a string or list of lists.-- **encoding** (str): Character encoding to use. (default: :obj:`utf-8`) (default: utf-8)--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._write_json_file"></a>--### _write_json_file--```python-def _write_json_file(- self,- file_path: Path,- content: str,- encoding: str = 'utf-8'-):-```--Write JSON content to a file.--**Parameters:**--- **file_path** (Path): The target file path.-- **content** (str): The JSON content as a string.-- **encoding** (str): Character encoding to use. (default: :obj:`utf-8`) (default: utf-8)--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._write_simple_text_file"></a>--### _write_simple_text_file--```python-def _write_simple_text_file(- self,- file_path: Path,- content: str,- encoding: str = 'utf-8'-):-```--Write text content to a file (used for HTML, Markdown, YAML, etc.).--**Parameters:**--- **file_path** (Path): The target file path.-- **content** (str): The content to write.-- **encoding** (str): Character encoding to use. (default: :obj:`utf-8`) (default: utf-8)--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit.write_to_file"></a>--### write_to_file--```python-def write_to_file(- self,- title: str,- content: Union[str, List[List[str]]],- filename: str,- encoding: Optional[str] = None,- use_latex: bool = False-):-```--Write the given content to a file.--If the file exists, it will be overwritten. Supports multiple formats:-Markdown (.md, .markdown, default), Plaintext (.txt), CSV (.csv),-DOC/DOCX (.doc, .docx), PDF (.pdf), JSON (.json), YAML (.yml, .yaml),-and HTML (.html, .htm).--**Parameters:**--- **title** (str): The title of the document.-- **content** (Union[str, List[List[str]]]): The content to write to the file. Content format varies by file type: - Text formats (txt, md, html, yaml): string - CSV: string or list of lists - JSON: string or serializable object-- **filename** (str): The name or path of the file. If a relative path is supplied, it is resolved to self.working_directory.-- **encoding** (Optional[str]): The character encoding to use. (default: :obj: `None`)-- **use_latex** (bool): Whether to use LaTeX for math rendering. (default: :obj:`False`)--**Returns:**-- str: A message indicating success or error details.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit.get_tools"></a>--### get_tools--```python-def get_tools(self):-```--**Returns:**-- List[FunctionTool]: A list of FunctionTool objects representing-the available functions in this toolkit.diff --git a/docs/reference/camel.toolkits.file_write_toolkit.md b/docs/reference/camel.toolkits.file_write_toolkit.mddeleted file mode 100644index fc5f43fe9..000000000--- a/docs/reference/camel.toolkits.file_write_toolkit.md+++ /dev/null@@ -1,435 +0,0 @@-<a id="camel.toolkits.file_write_toolkit"></a>--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit"></a>--## FileWriteToolkit--```python-class FileWriteToolkit(BaseToolkit):-```--A toolkit for creating, writing, and modifying text in files.--This class provides cross-platform (macOS, Linux, Windows) support for-writing to various file formats (Markdown, DOCX, PDF, and plaintext),-replacing text in existing files, automatic filename uniquification to-prevent overwrites, custom encoding and enhanced formatting options for-specialized formats.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit.__init__"></a>--### __init__--```python-def __init__(- self,- working_directory: Optional[str] = None,- timeout: Optional[float] = None,- default_encoding: str = 'utf-8',- backup_enabled: bool = True-):-```--Initialize the FileWriteToolkit.--**Parameters:**--- **working_directory** (str, optional): The default directory for output files. If not provided, it will be determined by the `CAMEL_WORKDIR` environment variable (if set). If the environment variable is not set, it defaults to `camel_working_dir`.-- **timeout** (Optional[float]): The timeout for the toolkit. (default: :obj:`None`)-- **default_encoding** (str): Default character encoding for text operations. (default: :obj:`utf-8`)-- **backup_enabled** (bool): Whether to create backups of existing files before overwriting. (default: :obj:`True`)--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._resolve_filepath"></a>--### _resolve_filepath--```python-def _resolve_filepath(self, file_path: str):-```--Convert the given string path to a Path object.--If the provided path is not absolute, it is made relative to the-default output directory. The filename part is sanitized to replace-spaces and special characters with underscores, ensuring safe usage-in downstream processing.--**Parameters:**--- **file_path** (str): The file path to resolve.--**Returns:**-- Path: A fully resolved (absolute) and sanitized Path object.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._sanitize_filename"></a>--### _sanitize_filename--```python-def _sanitize_filename(self, filename: str):-```--Sanitize a filename by replacing any character that is not-alphanumeric, a dot (.), hyphen (-), or underscore (_) with an-underscore (_).--**Parameters:**--- **filename** (str): The original filename which may contain spaces or special characters.--**Returns:**-- str: The sanitized filename with disallowed characters replaced by-underscores.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._write_text_file"></a>--### _write_text_file--```python-def _write_text_file(- self,- file_path: Path,- content: str,- encoding: str = 'utf-8'-):-```--Write text content to a plaintext file.--**Parameters:**--- **file_path** (Path): The target file path.-- **content** (str): The text content to write.-- **encoding** (str): Character encoding to use. (default: :obj:`utf-8`) (default: utf-8)--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._generate_unique_filename"></a>--### _generate_unique_filename--```python-def _generate_unique_filename(self, file_path: Path):-```--Generate a unique filename if the target file already exists.--**Parameters:**--- **file_path** (Path): The original file path.--**Returns:**-- Path: A unique file path that doesn't exist yet.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._write_docx_file"></a>--### _write_docx_file--```python-def _write_docx_file(self, file_path: Path, content: str):-```--Write text content to a DOCX file with default formatting.--**Parameters:**--- **file_path** (Path): The target file path.-- **content** (str): The text content to write.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._write_pdf_file"></a>--### _write_pdf_file--```python-def _write_pdf_file(- self,- file_path: Path,- title: str,- content: Union[str, List[List[str]]],- use_latex: bool = False-):-```--Write text content to a PDF file with LaTeX and table support.--**Parameters:**--- **file_path** (Path): The target file path.-- **title** (str): The document title.-- **content** (Union[str, List[List[str]]]): The content to write. Can-- **be**: - String: Supports Markdown-style tables and LaTeX math expressions - List[List[str]]: Table data as list of rows for direct table rendering-- **use_latex** (bool): Whether to use LaTeX for math rendering. (default: :obj:`False`)--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._process_text_content"></a>--### _process_text_content--```python-def _process_text_content(- self,- story,- content: str,- heading_style,- body_style-):-```--Process text content and add to story.--**Parameters:**--- **story**: The reportlab story list to append to-- **content** (str): The text content to process-- **heading_style**: Style for headings-- **body_style**: Style for body text--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._find_table_line_ranges"></a>--### _find_table_line_ranges--```python-def _find_table_line_ranges(self, lines: List[str]):-```--Find line ranges that contain markdown tables.--**Parameters:**--- **lines** (List[str]): List of lines to analyze.--**Returns:**-- List[Tuple[int, int]]: List of (start_line, end_line) tuples-for table ranges.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._register_chinese_font"></a>--### _register_chinese_font--```python-def _register_chinese_font(self):-```--**Returns:**-- str: The font name to use for Chinese text.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._parse_markdown_table"></a>--### _parse_markdown_table--```python-def _parse_markdown_table(self, lines: List[str]):-```--Parse markdown-style tables from a list of lines.--**Parameters:**--- **lines** (List[str]): List of text lines that may contain tables.--**Returns:**-- List[List[List[str]]]: List of tables, where each table is a list-of rows, and each row is a list of cells.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._is_table_row"></a>--### _is_table_row--```python-def _is_table_row(self, line: str):-```--Check if a line appears to be a table row.--**Parameters:**--- **line** (str): The line to check.--**Returns:**-- bool: True if the line looks like a table row.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._is_table_separator"></a>--### _is_table_separator--```python-def _is_table_separator(self, line: str):-```--Check if a line is a table separator (e.g., |---|---|).--**Parameters:**--- **line** (str): The line to check.--**Returns:**-- bool: True if the line is a table separator.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._parse_table_row"></a>--### _parse_table_row--```python-def _parse_table_row(self, line: str):-```--Parse a single table row into cells.--**Parameters:**--- **line** (str): The table row line.--**Returns:**-- List[str]: List of cell contents.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._create_pdf_table"></a>--### _create_pdf_table--```python-def _create_pdf_table(self, table_data: List[List[str]]):-```--Create a formatted table for PDF.--**Parameters:**--- **table_data** (List[List[str]]): Table data as list of rows.--**Returns:**-- Table: A formatted reportlab Table object.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._convert_markdown_to_html"></a>--### _convert_markdown_to_html--```python-def _convert_markdown_to_html(self, text: str):-```--Convert basic markdown formatting to HTML for PDF rendering.--**Parameters:**--- **text** (str): Text with markdown formatting.--**Returns:**-- str: Text with HTML formatting.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._write_csv_file"></a>--### _write_csv_file--```python-def _write_csv_file(- self,- file_path: Path,- content: Union[str, List[List]],- encoding: str = 'utf-8'-):-```--Write CSV content to a file.--**Parameters:**--- **file_path** (Path): The target file path.-- **content** (Union[str, List[List]]): The CSV content as a string or list of lists.-- **encoding** (str): Character encoding to use. (default: :obj:`utf-8`) (default: utf-8)--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._write_json_file"></a>--### _write_json_file--```python-def _write_json_file(- self,- file_path: Path,- content: str,- encoding: str = 'utf-8'-):-```--Write JSON content to a file.--**Parameters:**--- **file_path** (Path): The target file path.-- **content** (str): The JSON content as a string.-- **encoding** (str): Character encoding to use. (default: :obj:`utf-8`) (default: utf-8)--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit._write_simple_text_file"></a>--### _write_simple_text_file--```python-def _write_simple_text_file(- self,- file_path: Path,- content: str,- encoding: str = 'utf-8'-):-```--Write text content to a file (used for HTML, Markdown, YAML, etc.).--**Parameters:**--- **file_path** (Path): The target file path.-- **content** (str): The content to write.-- **encoding** (str): Character encoding to use. (default: :obj:`utf-8`) (default: utf-8)--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit.write_to_file"></a>--### write_to_file--```python-def write_to_file(- self,- title: str,- content: Union[str, List[List[str]]],- filename: str,- encoding: Optional[str] = None,- use_latex: bool = False-):-```--Write the given content to a file.--If the file exists, it will be overwritten. Supports multiple formats:-Markdown (.md, .markdown, default), Plaintext (.txt), CSV (.csv),-DOC/DOCX (.doc, .docx), PDF (.pdf), JSON (.json), YAML (.yml, .yaml),-and HTML (.html, .htm).--**Parameters:**--- **title** (str): The title of the document.-- **content** (Union[str, List[List[str]]]): The content to write to the file. Content format varies by file type: - Text formats (txt, md, html, yaml): string - CSV: string or list of lists - JSON: string or serializable object-- **filename** (str): The name or path of the file. If a relative path is supplied, it is resolved to self.working_directory.-- **encoding** (Optional[str]): The character encoding to use. (default: :obj: `None`)-- **use_latex** (bool): Whether to use LaTeX for math rendering. (default: :obj:`False`)--**Returns:**-- str: A message indicating success or error details.--<a id="camel.toolkits.file_write_toolkit.FileWriteToolkit.get_tools"></a>--### get_tools--```python-def get_tools(self):-```--**Returns:**-- List[FunctionTool]: A list of FunctionTool objects representing-the available functions in this toolkit.diff --git a/examples/debug/eigent.py b/examples/debug/eigent.pyindex 7e17728a6..2a9fde5e2 100644--- a/examples/debug/eigent.py+++ b/examples/debug/eigent.py@@ -28,7 +28,7 @@ from camel.toolkits import (AudioAnalysisToolkit,Crawl4AIToolkit,ExcelToolkit,- FileWriteToolkit,+ FileToolkit,# GoogleDriveMCPToolkit,HumanToolkit,HybridBrowserToolkit,@@ -324,7 +324,7 @@ def document_agent_factory(r"""Factory for creating a document agent, based on user-provided codestructure."""tools = [- *FileWriteToolkit().get_tools(),+ *FileToolkit().get_tools(),*PPTXToolkit().get_tools(),# *google_drive_mcp_toolkit.get_tools(),# *RetrievalToolkit().get_tools(),diff --git a/examples/toolkits/agent_toolkit.py b/examples/toolkits/agent_toolkit.pynew file mode 100644index 000000000..37c1f19b5--- /dev/null+++ b/examples/toolkits/agent_toolkit.py@@ -0,0 +1,111 @@+# ========= 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. =========++from camel.agents import ChatAgent+from camel.models import ModelFactory+from camel.toolkits import AgentToolkit+from camel.types import ModelPlatformType, ModelType++# Define system message for the parent agent+sys_msg = (+ "You are a manager agent that delegates tasks to sub-agents. "+ "Use agent_run_subagent with wait=True when you need a sub-agent result "+ "before you can continue. Use wait=False only if you intentionally want "+ "to do other work first and then call agent_get_task_output later."+)++# Create model and AgentToolkit+model = ModelFactory.create(+ model_platform=ModelPlatformType.DEFAULT,+ model_type=ModelType.DEFAULT,+)++agent_toolkit = AgentToolkit()++# Create the parent agent and register the toolkit+parent_agent = ChatAgent(+ system_message=sys_msg,+ model=model,+ tools=agent_toolkit.get_tools(),+ toolkits_to_register_agent=[agent_toolkit],+)++# Ask the parent agent to delegate a research task to a sub-agent+usr_msg = (+ "Run a research sub-agent to summarize the key differences "+ "between Python asyncio and threading. "+ "Wait for the result and report it back to me."+)++response = parent_agent.step(usr_msg)+print(response.msgs[0].content)+"""+===============================================================================+Here is a summary of the key differences between Python's asyncio and+threading:++1. Concurrency Models+- asyncio: Uses asynchronous programming with an event loop, coroutines (async+def), and await expressions. It runs single-threaded concurrency with+cooperative task switching at await points. Designed for non-blocking I/O+operations.+- threading: Uses preemptive multitasking with multiple OS threads that can+run concurrently. Context switching is managed by the OS and can happen+anytime. Threads can block independently.++2. Use Cases+- asyncio: Ideal for I/O-bound, high-concurrency network code, suitable when+many simultaneous I/O operations or connections are involved. Less suitable+for CPU-bound tasks. Requires async-compatible libraries.+- threading: Good for I/O-bound tasks involving blocking or legacy blocking+APIs, some CPU-bound parallelism (limited by GIL). Useful with non-async+libraries and for real parallelism via C extensions or multiprocessing.++3. Performance Characteristics+- asyncio: Lower overhead than threads, scalable to thousands of tasks,+efficient for I/O-bound workloads. Runs on a single CPU core unless combined+with multiprocessing.+- threading: Higher overhead for thread management, limited CPU parallelism+due to Python's GIL, prone to race conditions requiring synchronization.++Summary Table:++| Aspect | asyncio |+threading |+|-------------------|----------------------------------|+----------------------------------|+| Concurrency Model | Single-threaded cooperative | Multi-threaded+preemptive |+| Switching | Explicit await points | OS-managed context+switching |+| Suitable for | High-concurrency I/O-bound tasks | Blocking I/O, some+CPU tasks |+| Performance | Low overhead, high scalability | Higher overhead,+limited CPU parallelism due to GIL |+| Complexity | Requires async programming model | Simpler but prone to+race conditions |+| Parallelism | Single CPU core (multiprocessing possible) | Multiple+threads, limited by GIL |++Additional notes:+- asyncio requires async-compatible libraries and special handling for+blocking code.+- Threading requires careful synchronization to avoid data races.+- For CPU-bound parallelism, multiprocessing or native extensions are often+better than threading.++If you want, I can also provide example code snippets or deeper details on any+aspect.+===============================================================================+"""diff --git a/examples/toolkits/file_toolkit.py b/examples/toolkits/file_toolkit.pyindex 50ccff225..65adf097a 100644--- a/examples/toolkits/file_toolkit.py+++ b/examples/toolkits/file_toolkit.py@@ -33,7 +33,7 @@ sys_msg = "You are a helpful assistant that can create and modify files."working_directory = "./file_write_outputs"os.makedirs(working_directory, exist_ok=True)-# Initialize the FileWriteToolkit with the output directory+# Initialize the FileToolkit with the output directoryfile_toolkit = FileToolkit(working_directory=working_directory)# Get the tools from the toolkit@@ -460,3 +460,42 @@ The file now includes:Tool calls: [ToolCallingRecord(tool_name='read_file', args={'file_path': 'simple_flask_server.py'}, result='# This is a simple Flask application\nfrom flask import Flask\n\napp = Flask(__name__)\n\[email protected](\'/\')\ndef home():\n return "Hello, Flask!"\n\[email protected](\'/about\')\ndef about():\n return "About Flask Server"\n\[email protected](\'/contact\')\ndef contact():\n return "Contact us at [email protected]"\n\nif __name__ == \'__main__\':\n app.run(debug=True)', tool_call_id='call_hij789klm012')]==============================================================================='''++# Example 15: Use glob_files to find files by pattern+camel_agent.reset()+response = camel_agent.step(+ "First, create three files in the working directory: "+ "'utils.py' containing 'def add(a, b): return a + b', "+ "'main.py' containing 'from utils import add\\nprint(add(1, 2))', "+ "and 'notes.md' containing '# Project Notes'. "+ "Then use glob_files to find all Python files (*.py)."+)+print("Example 15: Using glob_files")+print(response.msgs[0].content)+print("Tool calls:", response.info['tool_calls'])+print("\n")++# Example 16: Use grep_files to search content with regex+camel_agent.reset()+response = camel_agent.step(+ "Use grep_files to search for the pattern 'def\\s+\\w+' "+ "in all .py files under the working directory. "+ "Show the matching content with 1 line of context."+)+print("Example 16: Using grep_files")+print(response.msgs[0].content)+print("Tool calls:", response.info['tool_calls'])+print("\n")++# Example 17: Edit a Jupyter notebook with notebook_edit_cell+camel_agent.reset()+response = camel_agent.step(+ "Create a file 'demo.ipynb' with a valid empty Jupyter notebook "+ "structure (nbformat 4, empty cells list). "+ "Then use notebook_edit_cell to insert a markdown cell with "+ "'# Demo Notebook' and a code cell with 'print(\"hello\")'."+)+print("Example 17: Using notebook_edit_cell")+print(response.msgs[0].content)+print("Tool calls:", response.info['tool_calls'])+print("\n")diff --git a/examples/toolkits/planning_worktree_toolkit.py b/examples/toolkits/planning_worktree_toolkit.pynew file mode 100644index 000000000..e8b410dc3--- /dev/null+++ b/examples/toolkits/planning_worktree_toolkit.py@@ -0,0 +1,61 @@+# ========= 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. =========++from camel.agents import ChatAgent+from camel.models import ModelFactory+from camel.toolkits import FileToolkit, PlanningWorktreeToolkit+from camel.types import ModelPlatformType, ModelType++# Define system message+sys_msg = (+ "You are a software engineering assistant that plans before coding. "+ "When asked to implement something, first enter plan mode to outline "+ "the approach, then write the implementation files."+)++# Initialize toolkits — combine planning with file operations+planning_toolkit = PlanningWorktreeToolkit()+file_toolkit = FileToolkit()+tools = planning_toolkit.get_tools() + file_toolkit.get_tools()++model = ModelFactory.create(+ model_platform=ModelPlatformType.DEFAULT,+ model_type=ModelType.GPT_5_4,+)++# Set agent+camel_agent = ChatAgent(+ system_message=sys_msg,+ model=model,+ tools=tools,+)++# Example: Plan and implement a simple utility module+usr_msg = (+ "I need a Python utility module called `string_utils.py` that provides "+ "two functions: `snake_to_camel(s)` and `camel_to_snake(s)` for "+ "converting between naming conventions. "+ "First enter plan mode and write your implementation plan to the plan "+ "file, then exit plan mode so I can review it before you write the code."+)++# Get response information+response = camel_agent.step(usr_msg)+print(str(response.info['tool_calls']))++'''+===============================================================================++===============================================================================+'''diff --git a/examples/toolkits/todo_toolkit.py b/examples/toolkits/todo_toolkit.pynew file mode 100644index 000000000..e6191a7a5--- /dev/null+++ b/examples/toolkits/todo_toolkit.py@@ -0,0 +1,109 @@+# ========= 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. =========++from camel.agents import ChatAgent+from camel.models import ModelFactory+from camel.toolkits import MathToolkit, TodoToolkit+from camel.types import ModelPlatformType, ModelType++# Define system message+sys_msg = (+ "You are a math assistant that solves problems step by step. "+ "You have a todo list to track each calculation step. "+ "For EVERY step: first update the todo list (mark current step "+ "in_progress), then call the math tool to compute, then update "+ "the todo list again (mark that step completed). "+ "Always rewrite the full todo list when updating."+)++# Set model config and initialize toolkit+todo_toolkit = TodoToolkit()+math_toolkit = MathToolkit()+tools = todo_toolkit.get_tools() + math_toolkit.get_tools()++model = ModelFactory.create(+ model_platform=ModelPlatformType.DEFAULT,+ model_type=ModelType.GPT_5_4,+)++# Set agent+camel_agent = ChatAgent(+ system_message=sys_msg,+ model=model,+ tools=tools,+)+++def print_todos(label: str):+ r"""Helper to print the current todo state."""+ print(f"\n{'=' * 60}")+ print(f" {label}")+ print('=' * 60)+ for item in todo_toolkit.todos:+ print(f" [{item.status:>11}] {item.content}")+ print()+++usr_msg = (+ "A company has 3 product lines with monthly revenues: "+ "Product A = $1200, Product B = $850, Product C = $2100. "+ "Solve step by step using the math tools:\n"+ "1. Add Product A + Product B revenues\n"+ "2. Add that result to Product C to get total monthly revenue\n"+ "3. Multiply total monthly revenue by 12 for annual revenue\n"+ "4. Calculate 15% tax on the annual revenue\n"+ "5. Subtract the tax from annual revenue to get net annual revenue\n"+ "Track each step in the todo list as you go."+)++response = camel_agent.step(usr_msg)+print_todos("Final state")+print(f"Agent response:\n{response.msgs[0].content}")++'''+===============================================================================+============================================================+ Final state+============================================================+ [ completed] Add Product A and Product B revenues+ [ completed] Add Product C to get total monthly revenue+ [ completed] Multiply total monthly revenue by 12 for annual revenue+ [ completed] Calculate 15% tax on annual revenue+ [ completed] Subtract tax from annual revenue to get net annual revenue++Agent response:+Here is the step-by-step calculation:++1. Product A + Product B+ $1200 + $850 = $2050++2. Add Product C for total monthly revenue+ $2050 + $2100 = $4150++3. Annual revenue+ $4150 x 12 = $49,800++4. 15% tax on annual revenue+ $49,800 x 0.15 = $7,470++5. Net annual revenue+ $49,800 - $7,470 = $42,330++Final answers:+- Total monthly revenue: $4,150+- Annual revenue: $49,800+- Tax at 15%: $7,470+- Net annual revenue: $42,330+===============================================================================+'''diff --git a/examples/toolkits/web_fetch_toolkit_example.py b/examples/toolkits/web_fetch_toolkit_example.pynew file mode 100644index 000000000..4ae1710b3--- /dev/null+++ b/examples/toolkits/web_fetch_toolkit_example.py@@ -0,0 +1,40 @@+# ========= 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. =========++from camel.agents import ChatAgent+from camel.models import ModelFactory+from camel.toolkits import WebFetchToolkit+from camel.types import ModelPlatformType, ModelType++# Create the toolkit instance+web_fetch_toolkit = WebFetchToolkit()++model = ModelFactory.create(+ model_platform=ModelPlatformType.DEFAULT,+ model_type=ModelType.DEFAULT,+)++# The toolkit extends RegisteredAgentToolkit, so pass it via+# toolkits_to_register_agent to let the agent register itself.+agent = ChatAgent(+ system_message="You are a helpful research assistant.",+ model=model,+ tools=web_fetch_toolkit.get_tools(),+ toolkits_to_register_agent=[web_fetch_toolkit],+)++response = agent.step(+ "Fetch https://httpbin.org/html and tell me what the page is about."+)+print(response.msgs[0].content)diff --git a/examples/usecases/multi_agent_research_assistant/README.md b/examples/usecases/multi_agent_research_assistant/README.mdindex 5e949c38d..bb5cbbdf3 100644--- a/examples/usecases/multi_agent_research_assistant/README.md+++ b/examples/usecases/multi_agent_research_assistant/README.md@@ -10,7 +10,7 @@ A powerful, AI-driven research assistant built using the [CAMEL-AI](https://www.- `ArxivToolkit` for accessing preprints.- `AskNewsToolkit` for fetching relevant news articles.- `ThinkingToolkit` for planning and synthesis.- - `FileWriteToolkit` for saving reports locally.+ - `FileToolkit` for saving reports locally.- `LinkedInToolkit` for potential dissemination.- `OpenAIImageToolkit` for generating illustrative images.- **Streamlit Interface**: Provides an intuitive web interface for users to input topics and receive generated reports.diff --git a/examples/usecases/multi_agent_research_assistant/app.py b/examples/usecases/multi_agent_research_assistant/app.pyindex ab402968a..98ca959f3 100644--- a/examples/usecases/multi_agent_research_assistant/app.py+++ b/examples/usecases/multi_agent_research_assistant/app.py@@ -20,7 +20,7 @@ from camel.types import ModelPlatformType, ModelTypefrom camel.toolkits import (GoogleScholarToolkit, SemanticScholarToolkit, ArxivToolkit,AskNewsToolkit, ThinkingToolkit,- FileWriteToolkit, LinkedInToolkit+ FileToolkit, LinkedInToolkit)from camel.logger import set_log_levelimport logging@@ -76,7 +76,7 @@ if st.button("Generate Report") and topic:*ArxivToolkit().get_tools(),*AskNewsToolkit().get_tools(),*ThinkingToolkit().get_tools(),- *FileWriteToolkit().get_tools(),+ *FileToolkit().get_tools(),*LinkedInToolkit().get_tools(),]diff --git a/examples/workforce/human_in_the_loop/simple_hotkey_demo.py b/examples/workforce/human_in_the_loop/simple_hotkey_demo.pyindex a41668667..170eeb799 100644--- a/examples/workforce/human_in_the_loop/simple_hotkey_demo.py+++ b/examples/workforce/human_in_the_loop/simple_hotkey_demo.py@@ -21,14 +21,14 @@ from camel.messages.base import BaseMessagefrom camel.models import ModelFactoryfrom camel.societies.workforce import Workforcefrom camel.tasks.task import Task-from camel.toolkits import FileWriteToolkit, ThinkingToolkit+from camel.toolkits import FileToolkit, ThinkingToolkitfrom camel.types import ModelPlatformType, ModelTypedef create_simple_workforce():r"""Create a simple workforce for demonstration."""thinking_toolkit = ThinkingToolkit()- file_write_toolkit = FileWriteToolkit()+ file_write_toolkit = FileToolkit()# Create a simple search agentpoet_agent = ChatAgent(diff --git a/test/toolkits/test_agent_toolkit.py b/test/toolkits/test_agent_toolkit.pynew file mode 100644index 000000000..1fd4f85b7--- /dev/null+++ b/test/toolkits/test_agent_toolkit.py@@ -0,0 +1,311 @@+# ========= 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. =========++import time+from types import SimpleNamespace+from typing import ClassVar, List++import pytest++from camel.toolkits.agent_toolkit import AgentToolkit+from camel.toolkits.function_tool import FunctionTool+++def parent_search(query: str) -> str:+ """Search docs.++ Args:+ query (str): Search query.++ Returns:+ str: Search result.+ """+ return query+++def parent_calc(expr: str) -> str:+ """Evaluate expression.++ Args:+ expr (str): Expression to evaluate.++ Returns:+ str: Evaluation result.+ """+ return expr+++class FakeChatAgent:+ created_agents: ClassVar[List["FakeChatAgent"]] = []+ delay_seconds: ClassVar[float] = 0.0++ def __init__(self, **kwargs):+ self.kwargs = kwargs+ self.agent_id = f"fake-agent-{len(self.created_agents) + 1}"+ self.prompts = []+ self.created_agents.append(self)++ def step(self, prompt):+ self.prompts.append(prompt)+ waited = 0.0+ while waited < self.delay_seconds:+ stop_event = getattr(self, "stop_event", None)+ if stop_event is not None and stop_event.is_set():+ return SimpleNamespace(+ msgs=[SimpleNamespace(content=f"stopped::{prompt}")]+ )+ time.sleep(0.01)+ waited += 0.01+ return SimpleNamespace(+ msgs=[SimpleNamespace(content=f"handled::{prompt}")]+ )+++class TestAgentToolkit:+ def _wait_task(self, toolkit, task_id: str, timeout: float = 2.0):+ task = toolkit._tasks[task_id]+ try:+ task.future.result(timeout=timeout)+ except Exception:+ pass+ toolkit._complete_task(task_id)+ return toolkit._tasks[task_id]++ @pytest.fixture(autouse=True)+ def reset_fake_agents(self):+ FakeChatAgent.created_agents = []+ FakeChatAgent.delay_seconds = 0.0++ @pytest.fixture+ def toolkit(self, monkeypatch):+ monkeypatch.setattr(+ "camel.agents.ChatAgent",+ FakeChatAgent,+ raising=False,+ )+ return AgentToolkit()++ @pytest.fixture+ def parent_agent(self):+ def scheduling_strategy():+ return None++ tools = [+ FunctionTool(parent_search),+ FunctionTool(parent_calc),+ ]+ return SimpleNamespace(+ agent_id="parent-agent",+ model_backend=SimpleNamespace(+ models="parent-model",+ scheduling_strategy=scheduling_strategy,+ ),+ memory=SimpleNamespace(+ window_size=12,+ get_context_creator=lambda: SimpleNamespace(token_limit=4096),+ ),+ _output_language="Chinese",+ response_terminators=["DONE"],+ max_iteration=6,+ tool_execution_timeout=18,+ prune_tool_calls_from_memory=True,+ on_request_usage=None,+ stream_accumulate=True,+ _clone_tools=lambda: (tools, ["register-me"]),+ )++ def test_run_subagent_returns_completed_result(+ self, toolkit, parent_agent+ ):+ toolkit.register_agent(parent_agent)++ result = toolkit.agent_run_subagent(+ prompt="Research Eigent AI",+ description="Research Eigent AI",+ subagent_type="research",+ )++ assert result["created"] is True+ assert result["agent_id"] == "fake-agent-1"+ assert result["status"] == "completed"+ assert result["result"] == "handled::Research Eigent AI"+ assert result["error"] is None+ assert toolkit._sessions["fake-agent-1"].turns == 1++ def test_run_subagent_resumes_existing_session(+ self, toolkit, parent_agent+ ):+ toolkit.register_agent(parent_agent)++ first = toolkit.agent_run_subagent(+ prompt="First task",+ description="Deep analysis",+ subagent_type="analysis",+ )+ second = toolkit.agent_run_subagent(+ prompt="Continue the same task",+ agent_id=first["agent_id"],+ )++ assert first["agent_id"] == second["agent_id"]+ assert second["created"] is False+ assert len(FakeChatAgent.created_agents) == 1+ assert FakeChatAgent.created_agents[0].prompts == [+ "First task",+ "Continue the same task",+ ]++ def test_run_subagent_without_wait_returns_running_task(+ self, toolkit, parent_agent+ ):+ FakeChatAgent.delay_seconds = 0.3+ toolkit.register_agent(parent_agent)++ task = toolkit.agent_run_subagent(+ prompt="Slow task",+ description="Background-style polling task",+ wait=False,+ )++ assert task["created"] is True+ assert task["status"] == "running"++ def test_get_task_output_supports_polling_and_blocking(+ self, toolkit, parent_agent+ ):+ FakeChatAgent.delay_seconds = 0.2+ toolkit.register_agent(parent_agent)++ task = toolkit.agent_run_subagent(+ prompt="Poll later",+ description="Polling task",+ wait=False,+ )+ initial = toolkit.agent_get_task_output(task["task_id"], block=False)+ final = toolkit.agent_get_task_output(+ task["task_id"], block=True, timeout=1.0+ )++ assert initial["status"] == "running"+ assert final["status"] == "completed"+ assert final["result"] == "handled::Poll later"++ def test_inherits_all_parent_tools_by_default(self, toolkit, parent_agent):+ toolkit.register_agent(parent_agent)++ toolkit.agent_run_subagent(+ prompt="Use every parent tool",+ description="All tools",+ )++ created_agent = FakeChatAgent.created_agents[0]+ tools = created_agent.kwargs["tools"]+ assert sorted(tool.get_function_name() for tool in tools) == [+ "parent_calc",+ "parent_search",+ ]+ assert created_agent.kwargs["toolkits_to_register_agent"] == [+ "register-me"+ ]++ def test_stop_running_task(self, toolkit, parent_agent):+ FakeChatAgent.delay_seconds = 0.5+ toolkit.register_agent(parent_agent)++ task = toolkit.agent_run_subagent(+ prompt="Long running task",+ description="Coding task",+ timeout=0.0,+ )+ stopped = toolkit.agent_stop_task(task["task_id"])+ output = self._wait_task(toolkit, task["task_id"])++ assert stopped["status"] in {"stopping", "stopped"}+ assert output.status == "stopped"+ assert output.result == "stopped::Long running task"++ def test_empty_prompt_rejected(self, toolkit, parent_agent):+ toolkit.register_agent(parent_agent)++ for bad_prompt in ["", " ", None]:+ result = toolkit.agent_run_subagent(+ prompt=bad_prompt,+ description="test",+ )+ assert result["status"] == "failed"+ assert "empty" in result["error"].lower()++ def test_unknown_agent_id_returns_error(self, toolkit):+ toolkit._agent = SimpleNamespace()++ result = toolkit.agent_run_subagent(+ prompt="Continue",+ agent_id="missing-agent",+ )++ assert result["status"] == "failed"+ assert "No sub-agent session found" in result["error"]++ def test_purge_evicts_oldest_finished_tasks_when_limit_exceeded(+ self, toolkit, parent_agent+ ):+ toolkit.register_agent(parent_agent)+ toolkit._MAX_FINISHED_TASKS = 4++ ids = []+ for i in range(6):+ result = toolkit.agent_run_subagent(prompt=f"task-{i}")+ ids.append(result["task_id"])++ # oldest tasks should have been purged+ for task_id in ids[:2]:+ assert task_id not in toolkit._tasks+ # recent tasks should still exist+ for task_id in ids[2:]:+ assert toolkit._tasks[task_id].status == "completed"++ def test_requires_parent_agent(self, toolkit):+ result = toolkit.agent_run_subagent(+ prompt="Research Eigent AI",+ description="Research Eigent AI",+ subagent_type="research",+ )++ assert result["status"] == "failed"+ assert "must be registered" in result["error"]++ def test_wait_with_timeout_returns_running_on_expiry(+ self, toolkit, parent_agent+ ):+ FakeChatAgent.delay_seconds = 1.0+ toolkit.register_agent(parent_agent)++ result = toolkit.agent_run_subagent(+ prompt="Slow task",+ description="Timeout test",+ wait=True,+ timeout=0.05,+ )++ assert result["status"] == "running"++ def test_get_output_unknown_task_id_returns_error(+ self, toolkit, parent_agent+ ):+ toolkit.register_agent(parent_agent)++ result = toolkit.agent_get_task_output("missing-task-id")++ assert result["status"] == "failed"+ assert "No sub-agent task found" in result["error"]diff --git a/test/toolkits/test_file_toolkit.py b/test/toolkits/test_file_toolkit.pyindex b8bd9c48d..b914bc3e3 100644--- a/test/toolkits/test_file_toolkit.py+++ b/test/toolkits/test_file_toolkit.py@@ -20,7 +20,7 @@ from pathlib import Pathimport pytestimport yaml-from camel.toolkits import FileToolkit, FileWriteToolkit+from camel.toolkits import FileToolkit@pytest.fixture@@ -39,6 +39,31 @@ def temp_dir():yield temp_dir+def _write_notebook(path: Path) -> None:+ notebook = {+ "cells": [+ {+ "id": "cell-1",+ "cell_type": "markdown",+ "metadata": {},+ "source": ["# Title\n"],+ },+ {+ "id": "cell-2",+ "cell_type": "code",+ "metadata": {},+ "execution_count": None,+ "outputs": [],+ "source": ["print('old')\n"],+ },+ ],+ "metadata": {},+ "nbformat": 4,+ "nbformat_minor": 5,+ }+ path.write_text(json.dumps(notebook), encoding="utf-8")++def test_initialization():r"""Test the initialization of FileToolkit with default parameters."""toolkit = FileToolkit()@@ -319,8 +344,9 @@ def test_get_tools(file_write_toolkit):tools = file_write_toolkit.get_tools()# Check that we have the expected number of tools- # (now 4: write_to_file, read_file, edit_file, search_files)- assert len(tools) == 4+ # (now 7: write_to_file, read_file, edit_file, search_files,+ # notebook_edit_cell, glob_files, grep_files)+ assert len(tools) == 7# Check that the tools have the correct function namestool_names = [tool.get_function_name() for tool in tools]@@ -328,6 +354,21 @@ def test_get_tools(file_write_toolkit):assert "read_file" in tool_namesassert "edit_file" in tool_namesassert "search_files" in tool_names+ assert "notebook_edit_cell" in tool_names+ assert "glob_files" in tool_names+ assert "grep_files" in tool_names+++def test_mcp_registers_new_tools(file_write_toolkit):+ r"""Verify the new tools are exposed through the MCP server."""+ mcp_tools = {+ tool.name: tool+ for tool in file_write_toolkit.mcp._tool_manager.list_tools()+ }++ assert "glob_files" in mcp_tools+ assert "grep_files" in mcp_tools+ assert "notebook_edit_cell" in mcp_toolsdef test_sanitize_and_resolve_filepath(file_write_toolkit):@@ -433,28 +474,6 @@ def test_no_backup_when_disabled(tmp_path):assert "Initial content" not in file_content-def test_deprecated_alias():- r"""Test that FileWriteToolkit still works with deprecation warning."""- import warnings-- with warnings.catch_warnings(record=True) as w:- warnings.simplefilter("always")-- # This should trigger a deprecation warning- toolkit = FileWriteToolkit()-- # Check that a deprecation warning was issued- assert len(w) == 1- assert issubclass(w[0].category, DeprecationWarning)- assert "FileWriteToolkit is deprecated" in str(w[0].message)-- # Verify the toolkit still works- assert toolkit is not None- assert hasattr(toolkit, 'write_to_file')- assert hasattr(toolkit, 'read_file')- assert hasattr(toolkit, 'edit_file')--def test_search_files_basic(file_write_toolkit):r"""Test basic file search functionality with default markdown files."""# create test files with content@@ -662,3 +681,181 @@ def test_search_files_path_is_file(file_write_toolkit):# verify error is returnedassert "error" in result_dataassert "not a directory" in result_data["error"]+++def test_glob_sorts_by_modification_time(file_write_toolkit):+ older = file_write_toolkit.working_directory / "a.js"+ newer = file_write_toolkit.working_directory / "b.js"+ older.write_text("console.log('old')", encoding="utf-8")+ newer.write_text("console.log('new')", encoding="utf-8")+ os.utime(older, (1, 1))++ result = file_write_toolkit.glob_files("*.js")++ assert result == [str(newer.resolve()), str(older.resolve())]+++def test_grep_via_function_tool(file_write_toolkit):+ r"""Verify grep_files works correctly when invoked through FunctionTool,+ testing ignore_case, context_lines, and head_limit together."""+ file_path = file_write_toolkit.working_directory / "sample.txt"+ file_path.write_text(+ "alpha\nHello World\nomega\nHELLO again\n",+ encoding="utf-8",+ )+ grep_tool = next(+ tool+ for tool in file_write_toolkit.get_tools()+ if tool.get_function_name() == "grep_files"+ )++ result = grep_tool(+ **{+ "pattern": "hello",+ "path": str(file_write_toolkit.working_directory),+ "glob_pattern": "*.txt",+ "output_mode": "content",+ "ignore_case": True,+ "context_lines": 1,+ "head_limit": 2,+ "multiline": False,+ }+ )++ assert "Hello World" in result+ assert "HELLO again" in result+ # context lines should be present+ assert "alpha" in result+ assert "omega" in result+ # Verify the result contains two blocks separated by "--"+ blocks = result.split("--")+ assert len(blocks) == 2+++def test_grep_count_mode(file_write_toolkit):+ (file_write_toolkit.working_directory / "a.py").write_text(+ "def one():\n pass\n",+ encoding="utf-8",+ )+ (file_write_toolkit.working_directory / "b.py").write_text(+ "def two():\n pass\n",+ encoding="utf-8",+ )++ result = file_write_toolkit.grep_files(+ pattern=r"def\s+\w+",+ path=str(file_write_toolkit.working_directory),+ glob_pattern="*.py",+ output_mode="count",+ )++ assert result == {"files_with_matches": 2, "matches": 2}+++def test_glob_missing_path_returns_error_message(file_write_toolkit):+ result = file_write_toolkit.glob_files(+ "*.py",+ str(file_write_toolkit.working_directory / "does-not-exist"),+ )++ assert result.startswith("Error:")+++def test_grep_invalid_regex_returns_error_message(file_write_toolkit):+ result = file_write_toolkit.grep_files(+ pattern="(",+ path=str(file_write_toolkit.working_directory),+ )++ assert result.startswith("Error:")+++def test_grep_invalid_output_mode_returns_error_message(file_write_toolkit):+ result = file_write_toolkit.grep_files(+ pattern="hello",+ path=str(file_write_toolkit.working_directory),+ output_mode="invalid",+ )++ assert result.startswith("Error:")+ assert "output_mode" in result+++def test_grep_multiline_does_not_overcount_trailing_newline(+ file_write_toolkit,+):+ file_path = file_write_toolkit.working_directory / "multi.txt"+ file_path.write_text("aaa\nbbb\nccc\nddd\n", encoding="utf-8")++ result = file_write_toolkit.grep_files(+ pattern=r"bbb\nccc\n",+ path=str(file_write_toolkit.working_directory),+ glob_pattern="*.txt",+ output_mode="content",+ multiline=True,+ context_lines=1,+ )++ # The match covers lines 2-3 (bbb, ccc).+ # With context_lines=1 we also see aaa (line 1) and ddd (line 4).+ result_lines = result.strip().splitlines()+ markers = {}+ for line in result_lines:+ # format: "path:lineno:marker rest"+ parts = line.split(":", 3)+ lineno = int(parts[1])+ marker = parts[2][0]+ markers[lineno] = marker++ assert markers[1] == " ", "aaa (context) should not be marked"+ assert markers[2] == ">", "bbb should be marked as match"+ assert markers[3] == ">", "ccc should be marked as match"+ assert markers[4] == " ", "ddd should not be marked as match"+++def test_notebook_edit_replace_insert_delete(file_write_toolkit):+ notebook_path = file_write_toolkit.working_directory / "test.ipynb"+ _write_notebook(notebook_path)++ replace_result = file_write_toolkit.notebook_edit_cell(+ notebook_path=str(notebook_path),+ new_source="print('new')",+ cell_id="cell-2",+ edit_mode="replace",+ )+ assert "Updated cell 'cell-2'" in replace_result++ insert_result = file_write_toolkit.notebook_edit_cell(+ notebook_path=str(notebook_path),+ new_source="## Inserted",+ cell_id="cell-1",+ cell_type="markdown",+ edit_mode="insert",+ )+ assert "Inserted new cell" in insert_result++ delete_result = file_write_toolkit.notebook_edit_cell(+ notebook_path=str(notebook_path),+ cell_id="cell-1",+ edit_mode="delete",+ )+ assert "Deleted cell 'cell-1'" in delete_result++ notebook = json.loads(notebook_path.read_text(encoding="utf-8"))+ assert notebook["cells"][0]["source"] == ["## Inserted"]+ assert notebook["cells"][1]["source"] == ["print('new')"]+++def test_notebook_edit_returns_error_message_for_missing_file(+ file_write_toolkit,+):+ result = file_write_toolkit.notebook_edit_cell(+ notebook_path=str(+ file_write_toolkit.working_directory / "does-not-exist.ipynb"+ ),+ new_source="print('x')",+ cell_id="cell-1",+ edit_mode="replace",+ )++ assert result.startswith("Error:")diff --git a/test/toolkits/test_planning_worktree_toolkit.py b/test/toolkits/test_planning_worktree_toolkit.pynew file mode 100644index 000000000..3381ddd10--- /dev/null+++ b/test/toolkits/test_planning_worktree_toolkit.py@@ -0,0 +1,216 @@+# ========= 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. =========++import shutil+import subprocess+import tempfile+import threading+from pathlib import Path++import pytest++from camel.toolkits.planning_worktree_toolkit import (+ PlanningWorktreeToolkit,+)++# ── helpers ──────────────────────────────────────────────────────────+++def _init_git_repo(path: Path) -> None:+ """Create a minimal git repo with one commit at *path*."""+ path.mkdir(parents=True, exist_ok=True)+ subprocess.run(["git", "init"], cwd=path, check=True, capture_output=True)+ subprocess.run(+ ["git", "config", "user.email", "[email protected]"],+ cwd=path,+ check=True,+ capture_output=True,+ )+ subprocess.run(+ ["git", "config", "user.name", "Test User"],+ cwd=path,+ check=True,+ capture_output=True,+ )+ (path / "README.md").write_text("hello\n", encoding="utf-8")+ subprocess.run(+ ["git", "add", "README.md"],+ cwd=path,+ check=True,+ capture_output=True,+ )+ subprocess.run(+ ["git", "commit", "-m", "init"],+ cwd=path,+ check=True,+ capture_output=True,+ )+++# ── plan-mode tests ─────────────────────────────────────────────────+++def test_plan_mode_round_trip():+ """Enter → write plan → exit: plan content is returned correctly."""+ with tempfile.TemporaryDirectory() as temp_dir:+ toolkit = PlanningWorktreeToolkit(working_directory=temp_dir)+ entered = toolkit.planning_enter_plan_mode()++ plan_file = Path(entered["plan_file_path"])+ plan_file.write_text("# Plan\n\n- Step 1\n", encoding="utf-8")+ exited = toolkit.planning_exit_plan_mode(+ allowed_prompts=[{"tool": "Bash", "prompt": "run tests"}]+ )++ assert entered["plan_mode"] is True+ assert exited["plan_mode"] is False+ assert "Step 1" in exited["plan_content"]+ assert exited["allowed_prompts"][0]["tool"] == "Bash"+++def test_exit_plan_mode_without_enter_returns_error():+ """Exiting plan mode before entering it must return an error."""+ toolkit = PlanningWorktreeToolkit()+ result = toolkit.planning_exit_plan_mode()+ assert "error" in result+++# ── worktree tests ───────────────────────────────────────────────────++[email protected](shutil.which("git") is None, reason="git not installed")+def test_worktree_create_and_remove_lifecycle():+ """Create a worktree, verify it exists, remove it, verify cleanup."""+ with tempfile.TemporaryDirectory() as temp_dir:+ repo = Path(temp_dir) / "repo"+ _init_git_repo(repo)++ toolkit = PlanningWorktreeToolkit(working_directory=str(repo))+ enter_result = toolkit.worktree_enter_worktree("feature-search")++ assert enter_result["branch"].startswith("camel/feature-search")+ worktree_path = Path(enter_result["worktree_path"])+ assert worktree_path.exists()+ assert toolkit.working_directory == worktree_path++ remove_result = toolkit.worktree_remove_worktree()+ assert "error" not in remove_result+ assert remove_result["removed_worktree"] == str(worktree_path)+ assert toolkit.current_worktree_path is None+ assert toolkit.working_directory == repo.resolve()+ assert not worktree_path.exists()++[email protected](shutil.which("git") is None, reason="git not installed")+def test_worktree_name_collision_increments_suffix():+ """When a branch/dir already exists, the suffix should increment."""+ with tempfile.TemporaryDirectory() as temp_dir:+ repo = Path(temp_dir) / "repo"+ _init_git_repo(repo)++ toolkit = PlanningWorktreeToolkit(working_directory=str(repo))+ r1 = toolkit.worktree_enter_worktree("dup")+ assert r1["branch"] == "camel/dup"++ # Reset toolkit state so we can create another worktree+ toolkit.current_worktree_path = None+ toolkit.working_directory = repo.resolve()++ r2 = toolkit.worktree_enter_worktree("dup")+ assert r2["branch"] == "camel/dup-1"++ # Cleanup both worktrees+ subprocess.run(+ ["git", "worktree", "remove", "--force", r1["worktree_path"]],+ cwd=repo,+ capture_output=True,+ )+ subprocess.run(+ ["git", "worktree", "remove", "--force", r2["worktree_path"]],+ cwd=repo,+ capture_output=True,+ )+++def test_remove_worktree_without_enter_returns_error():+ """Removing a worktree when none is active must return an error."""+ toolkit = PlanningWorktreeToolkit()+ result = toolkit.worktree_remove_worktree()+ assert "error" in result++[email protected](shutil.which("git") is None, reason="git not installed")+def test_worktree_in_non_git_directory_returns_error():+ """Attempting to create a worktree outside a git repo must fail."""+ with tempfile.TemporaryDirectory() as temp_dir:+ toolkit = PlanningWorktreeToolkit(working_directory=temp_dir)+ result = toolkit.worktree_enter_worktree("should-fail")+ assert "error" in result++[email protected](shutil.which("git") is None, reason="git not installed")+def test_worktree_reentry_returns_error():+ """Entering a worktree while already inside one must return an error."""+ with tempfile.TemporaryDirectory() as temp_dir:+ repo = Path(temp_dir) / "repo"+ _init_git_repo(repo)++ toolkit = PlanningWorktreeToolkit(working_directory=str(repo))+ r1 = toolkit.worktree_enter_worktree("first")+ assert "error" not in r1++ r2 = toolkit.worktree_enter_worktree("second")+ assert "error" in r2++ # Cleanup+ toolkit.worktree_remove_worktree()+++def test_concurrent_plan_mode_enter_exit():+ """Multiple agents can independently enter and exit plan mode."""+ with tempfile.TemporaryDirectory() as temp_dir:+ errors: list = []++ def agent_work(agent_id: int) -> None:+ try:+ # Each agent uses its own plan file to avoid cross-write races+ tk = PlanningWorktreeToolkit(+ working_directory=temp_dir,+ plan_file_name=f".camel-plan-{agent_id}.md",+ )+ entered = tk.planning_enter_plan_mode()+ assert entered["plan_mode"] is True++ plan_file = Path(entered["plan_file_path"])+ plan_file.write_text(+ f"# Plan from agent {agent_id}\n", encoding="utf-8"+ )++ exited = tk.planning_exit_plan_mode()+ assert exited["plan_mode"] is False+ assert exited["plan_content"] == (+ f"# Plan from agent {agent_id}\n"+ )+ except Exception as exc:+ errors.append(exc)++ threads = [+ threading.Thread(target=agent_work, args=(i,)) for i in range(4)+ ]+ for t in threads:+ t.start()+ for t in threads:+ t.join()++ assert errors == [], f"Concurrent plan-mode errors: {errors}"diff --git a/test/toolkits/test_todo_toolkit.py b/test/toolkits/test_todo_toolkit.pynew file mode 100644index 000000000..923607d33--- /dev/null+++ b/test/toolkits/test_todo_toolkit.py@@ -0,0 +1,212 @@+# ========= 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. =========++import pytest++from camel.toolkits import TodoToolkit+from camel.toolkits.todo_toolkit import TodoItem+++def todo_toolkit(tmp_path):+ r"""Create a TodoToolkit instance backed by a temp directory."""+ return TodoToolkit(working_dir=str(tmp_path))+++def test_todo_write_with_raw_dicts(todo_toolkit):+ r"""Test updating the todo list with raw dicts."""+ todos = [+ {+ "content": "Install pptxgenjs dependencies",+ "active_form": "Installing pptxgenjs dependencies",+ "status": "completed",+ },+ {+ "content": "Wire TodoWrite into toolkit exports",+ "active_form": "Wiring TodoWrite into toolkit exports",+ "status": "in_progress",+ },+ ]++ result = todo_toolkit.todo_write(todos)++ assert result == "Todos have been modified successfully."+ assert len(todo_toolkit.todos) == 2+ for stored, raw in zip(todo_toolkit.todos, todos):+ assert isinstance(stored, TodoItem)+ assert stored.model_dump() == raw+++def test_todo_write_with_todoitem_instances(todo_toolkit):+ r"""Test updating the todo list with TodoItem instances."""+ items = [+ TodoItem(+ content="First task",+ active_form="Working on first task",+ status="pending",+ ),+ TodoItem(+ content="Second task",+ active_form="Working on second task",+ status="completed",+ ),+ ]++ result = todo_toolkit.todo_write(items)++ assert result == "Todos have been modified successfully."+ assert len(todo_toolkit.todos) == 2+ assert todo_toolkit.todos[0] is items[0]+ assert todo_toolkit.todos[1] is items[1]+++def test_todo_write_empty_list_clears_todos(todo_toolkit):+ r"""Test that writing an empty list clears existing todos."""+ todo_toolkit.todo_write(+ [+ {+ "content": "Some task",+ "active_form": "Doing some task",+ "status": "pending",+ }+ ]+ )+ assert len(todo_toolkit.todos) == 1++ result = todo_toolkit.todo_write([])++ assert result == "Todos have been modified successfully."+ assert todo_toolkit.todos == []+++def test_todo_write_keeps_previous_state_on_validation_error(todo_toolkit):+ r"""Test that invalid todo payloads do not overwrite prior state."""+ existing = [+ {+ "content": "Keep previous widget state",+ "active_form": "Keeping previous widget state",+ "status": "pending",+ }+ ]+ todo_toolkit.todo_write(existing)++ result = todo_toolkit.todo_write(+ [+ {+ "content": "Use an unsupported status",+ "active_form": "Using an unsupported status",+ "status": "done",+ }+ ]+ )++ assert result.startswith("[ERROR] Failed to update todos:")+ assert len(todo_toolkit.todos) == 1+ assert todo_toolkit.todos[0].content == "Keep previous widget state"+++def test_persistence_creates_files(tmp_path):+ r"""Test that todo_write creates both todo.md and .todo.json."""+ tk = TodoToolkit(working_dir=str(tmp_path))+ tk.todo_write(+ [+ {+ "content": "Persisted task",+ "active_form": "Persisting task",+ "status": "pending",+ }+ ]+ )++ # Markdown — clean, human-readable, no metadata+ md_file = tmp_path / "todo.md"+ assert md_file.exists()+ md_content = md_file.read_text(encoding="utf-8")+ assert "# Todo" in md_content+ assert "Persisted task" in md_content+ assert "<!--" not in md_content+ assert "active_form" not in md_content++ # JSON — structured data for reloading+ json_file = tmp_path / ".todo.json"+ assert json_file.exists()+++def test_persistence_survives_reload(tmp_path):+ r"""Test that a new TodoToolkit instance loads from existing .todo.json."""+ tk1 = TodoToolkit(working_dir=str(tmp_path))+ tk1.todo_write(+ [+ {+ "content": "Task A",+ "active_form": "Working on A",+ "status": "completed",+ },+ {+ "content": "Task B",+ "active_form": "Working on B",+ "status": "in_progress",+ },+ {+ "content": "Task C",+ "active_form": "Working on C",+ "status": "pending",+ },+ ]+ )++ # Create a new instance pointing to the same directory+ tk2 = TodoToolkit(working_dir=str(tmp_path))++ assert len(tk2.todos) == 3+ for original, reloaded in zip(tk1.todos, tk2.todos):+ assert reloaded.model_dump() == original.model_dump()+++def _resolve_ref(schema, root):+ r"""Resolve a ``$ref`` pointer against *root*."""+ ref = schema.get("$ref")+ if ref is None:+ return schema+ parts = ref.lstrip("#/").split("/")+ node = root+ for part in parts:+ node = node[part]+ return node+++def test_get_tools_exposes_todo_write_schema(todo_toolkit):+ r"""Test todo_write tool registration and schema generation."""+ tools = todo_toolkit.get_tools()++ assert len(tools) == 1+ assert tools[0].get_function_name() == "todo_write"++ schema = tools[0].get_openai_tool_schema()+ parameters = schema["function"]["parameters"]+ todos_schema = parameters["properties"]["todos"]+ # Pydantic may emit $ref + $defs; resolve if necessary.+ item_schema = _resolve_ref(todos_schema["items"], parameters)+ status_schema = item_schema["properties"]["status"]++ assert parameters["required"] == ["todos"]+ assert parameters["additionalProperties"] is False+ assert todos_schema["type"] == "array"+ assert set(item_schema["properties"]) == {+ "content",+ "active_form",+ "status",+ }+ assert item_schema["additionalProperties"] is False+ assert status_schema["enum"] == ["pending", "in_progress", "completed"]diff --git a/test/toolkits/test_web_fetch_toolkit.py b/test/toolkits/test_web_fetch_toolkit.pynew file mode 100644index 000000000..29cc9d2c1--- /dev/null+++ b/test/toolkits/test_web_fetch_toolkit.py@@ -0,0 +1,210 @@+# ========= 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. =========++from types import SimpleNamespace++import httpx+import pytest++from camel.toolkits.web_fetch_toolkit import WebFetchToolkit+++class FakeChatAgent:+ last_prompt = None+ reset_count = 0++ def __init__(self, **kwargs):+ self.kwargs = kwargs++ def step(self, prompt):+ FakeChatAgent.last_prompt = prompt+ return SimpleNamespace(msgs=[SimpleNamespace(content="summary")])++ def reset(self):+ FakeChatAgent.reset_count += 1++[email protected](autouse=True)+def _reset_fake_agent_state():+ """Reset FakeChatAgent class-level state before each test."""+ FakeChatAgent.last_prompt = None+ FakeChatAgent.reset_count = 0+++def _fake_get(self, url):+ request = httpx.Request("GET", url)+ return httpx.Response(+ 200,+ request=request,+ headers={"content-type": "text/html"},+ text=(+ "<html><body><h1>Pricing</h1>"+ "<p>Free</p><p>Pro</p></body></html>"+ ),+ )+++def test_web_fetch_analyzes_page(monkeypatch):+ monkeypatch.setattr(httpx.Client, "get", _fake_get)+ monkeypatch.setattr("camel.agents.ChatAgent", FakeChatAgent, raising=False)++ toolkit = WebFetchToolkit(default_model="test-model")+ result = toolkit.web_fetch_and_analyze(+ url="https://example.com/pricing",+ prompt="Extract the pricing tiers",+ )++ assert result == "summary"+ assert "Extract the pricing tiers" in FakeChatAgent.last_prompt+ assert "Pricing Free Pro" in FakeChatAgent.last_prompt+++def test_web_fetch_reuses_agent_with_reset(monkeypatch):+ monkeypatch.setattr(httpx.Client, "get", _fake_get)+ monkeypatch.setattr("camel.agents.ChatAgent", FakeChatAgent, raising=False)++ toolkit = WebFetchToolkit(default_model="test-model")+ toolkit.web_fetch_and_analyze(url="https://example.com/a", prompt="first")+ toolkit.web_fetch_and_analyze(url="https://example.com/b", prompt="second")++ assert FakeChatAgent.reset_count == 1+++def test_web_fetch_tool_name():+ toolkit = WebFetchToolkit(default_model="test-model")+ tool = toolkit.get_tools()[0]++ assert tool.get_function_name() == "web_fetch_and_analyze"+++def test_web_fetch_returns_error_when_no_model(monkeypatch):+ monkeypatch.setattr(httpx.Client, "get", _fake_get)++ toolkit = WebFetchToolkit(default_model=None)+ result = toolkit.web_fetch_and_analyze(+ url="https://example.com",+ prompt="Summarize the page",+ )++ assert result.startswith("Error:")+++def test_web_fetch_rejects_non_http_scheme():+ toolkit = WebFetchToolkit(default_model="test-model")+ result = toolkit.web_fetch_and_analyze(+ url="file:///etc/passwd",+ prompt="read it",+ )++ assert result.startswith("Error:")+ assert "not allowed" in result+++def test_web_fetch_handles_http_error(monkeypatch):+ def fake_get_500(self, url):+ request = httpx.Request("GET", url)+ return httpx.Response(500, request=request)++ monkeypatch.setattr(httpx.Client, "get", fake_get_500)++ toolkit = WebFetchToolkit(default_model="test-model")+ result = toolkit.web_fetch_and_analyze(+ url="https://example.com",+ prompt="Summarize",+ )++ assert result.startswith("Error:")+ assert "500" in result+++def test_web_fetch_handles_plain_text(monkeypatch):+ def fake_get_text(self, url):+ request = httpx.Request("GET", url)+ return httpx.Response(+ 200,+ request=request,+ headers={"content-type": "text/plain"},+ text="Hello world",+ )++ monkeypatch.setattr(httpx.Client, "get", fake_get_text)+ monkeypatch.setattr("camel.agents.ChatAgent", FakeChatAgent, raising=False)++ toolkit = WebFetchToolkit(default_model="test-model")+ result = toolkit.web_fetch_and_analyze(+ url="https://example.com/data.txt",+ prompt="Summarize",+ )++ assert result == "summary"+ assert "Hello world" in FakeChatAgent.last_prompt+++def test_web_fetch_max_chars_truncates(monkeypatch):+ def fake_get_long(self, url):+ request = httpx.Request("GET", url)+ return httpx.Response(+ 200,+ request=request,+ headers={"content-type": "text/plain"},+ text="A" * 1000,+ )++ monkeypatch.setattr(httpx.Client, "get", fake_get_long)+ monkeypatch.setattr("camel.agents.ChatAgent", FakeChatAgent, raising=False)++ toolkit = WebFetchToolkit(default_model="test-model")+ toolkit.web_fetch_and_analyze(+ url="https://example.com/long",+ prompt="Summarize",+ max_chars=100,+ )++ # Only the first 100 chars should appear in the prompt+ assert "A" * 100 in FakeChatAgent.last_prompt+ assert "A" * 101 not in FakeChatAgent.last_prompt+++def test_web_fetch_error_includes_char_count_on_failure(monkeypatch):+ def fake_get_long(self, url):+ request = httpx.Request("GET", url)+ return httpx.Response(+ 200,+ request=request,+ headers={"content-type": "text/plain"},+ text="A" * 500,+ )++ class FailingAgent:+ def __init__(self, **kwargs):+ pass++ def step(self, prompt):+ raise RuntimeError("context length exceeded")++ def reset(self):+ pass++ monkeypatch.setattr(httpx.Client, "get", fake_get_long)+ monkeypatch.setattr("camel.agents.ChatAgent", FailingAgent, raising=False)++ toolkit = WebFetchToolkit(default_model="test-model")+ result = toolkit.web_fetch_and_analyze(+ url="https://example.com/big",+ prompt="Summarize",+ )++ assert result.startswith("Error:")+ assert "500 chars" in result+ assert "max_chars" in result