Skip to content

armgit / camel

Public Imported from GitHub
0

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

docs: update camel doc and build cicd (#3885)

Tao Sun258a8173ed17
diff --git a/.camel/skills/docs-incremental-update/SKILL.md b/.camel/skills/docs-incremental-update/SKILL.md
new file mode 100644
index 000000000..e31b39f15
--- /dev/null
+++ b/.camel/skills/docs-incremental-update/SKILL.md
@@ -0,0 +1,173 @@
+---
+name: docs-incremental-update
+description: >
+ Incrementally update Mintlify documentation (.mdx) from Python source
+ changes only. Use when: (1) Python files referenced in doc_code_map
+ frontmatter have changed, (2) a PR touches Python modules documented in
+ docs/mintlify/key_modules/ or docs/mintlify/mcp/, (3) the user asks to
+ sync docs after Python code changes. Prefer minimal diffs and leave correct
+ content untouched.
+---
+
+# Docs Incremental Update
+
+Update Mintlify .mdx documentation so it stays in sync with CAMEL source code.
+
+## Scope
+
+- Only use this skill when the driver is **Python source changes** referenced
+ by a target document's `doc_code_map`.
+- Do **not** use it for docs-only edits, workflow/YAML changes, or broad
+ wording cleanups without Python changes.
+- Prefer **no document change** when Python edits are internal and do not
+ affect public API, behavior, configuration, examples, or reader understanding.
+
+## Edit Rule
+
+Use terminal tools to inspect the target doc, inspect any relevant code, and
+edit the target doc directly. Keep changes scoped to that doc and preserve its
+frontmatter.
+CI treats the run as successful based on the resulting target doc file state,
+not on any special status token in the chat response.
+
+
+## Quick Reference
+
+| Item | Path |
+|------|------|
+| Doc roots | `docs/mintlify/` |
+| Mapping utility | `docs/mintlify/scripts/docs_sync/doc_code_map.py` |
+| Auto-sync script | `.camel/skills/docs-incremental-update/scripts/auto_sync_docs_with_chatagent.py` |
+| Workflow | `.github/workflows/docs_release_auto_sync_pr.yml` |
+
+## Workflow
+
+### Step 1 — Identify Impacted Docs
+
+Determine which `.mdx` files are affected by the code change.
+
+```bash
+# From repo root, pass only changed Python files
+python docs/mintlify/scripts/docs_sync/doc_code_map.py impacted \
+ --changed-file <file1> --changed-file <file2>
+
+# Or using git refs
+python docs/mintlify/scripts/docs_sync/doc_code_map.py impacted \
+ --base-ref <base> --head-ref <head>
+```
+
+Each `.mdx` file declares a `doc_code_map` block in its YAML frontmatter:
+
+```yaml
+---
+title: MCP Toolkit
+doc_code_map:
+ - "camel/toolkits/mcp_toolkit.py"
+ - "camel/runtimes/llm_guard_runtime.py"
+---
+```
+
+### Step 2 — Read Current Doc and Relevant Code
+
+For each impacted doc:
+
+1. Open the target `.mdx` file and inspect its `doc_code_map` frontmatter.
+2. Use the provided changed Python file list as initial context.
+3. Read any source files needed to judge whether the doc is still accurate.
+4. Compare the target doc against the current code and decide whether a
+ reader-facing update is actually needed.
+
+### Step 3 — Update the Document Body
+
+Rewrite only the parts of the body that are outdated relative to the code.
+
+Rules:
+- **Edit the target doc directly through terminal tools** for this run.
+- **Let file changes speak for themselves** — if no update is needed, leave the
+ target doc untouched instead of relying on a sentinel reply.
+- **Use changed Python files as context, not a hard boundary** — inspect other
+ relevant code when needed to make a correct documentation decision.
+- **Ignore non-Python changes** — docs, workflow, YAML, test-only, and release
+ metadata changes should not trigger doc edits by themselves.
+- **Prefer the smallest possible diff** — keep all already-correct content.
+- **Preserve frontmatter** — never modify the `---` block.
+- **Preserve style** — keep existing section structure and tone.
+- **Preserve Mintlify components** — keep Card, Accordion, Tab, CodeGroup, etc.
+- **Update code snippets** — fix imports, class names, method signatures, parameters.
+- **Update prose** — fix descriptions that no longer match the code.
+- **Remove references** to deleted classes/methods/parameters.
+- **Add references** to newly introduced public API when relevant.
+- **Skip the document entirely** if the Python change is internal and does not
+ require reader-facing doc updates.
+- After finishing, either leave the file unchanged or update it in place.
+- Do not return the full rewritten document body in chat; a short status note
+ is enough.
+
+### Step 4 — Verify
+
+```bash
+# Ensure all patterns still resolve
+python docs/mintlify/scripts/docs_sync/doc_code_map.py verify
+```
+
+Check that no frontmatter was accidentally removed or duplicated.
+
+## Mintlify Component Cheatsheet
+
+Use these components in `.mdx` files:
+
+```mdx
+<Card title="Title" icon="icon-name" href="/path">
+ Description text.
+</Card>
+```
+
+```mdx
+<Accordion title="Click to expand">
+ Hidden content revealed on click.
+</Accordion>
+```
+
+```mdx
+<Tabs>
+ <Tab title="Python">
+ Python content here.
+ </Tab>
+ <Tab title="TypeScript">
+ TypeScript content here.
+ </Tab>
+</Tabs>
+```
+
+~~~~mdx
+<CodeGroup>
+```python title="example.py"
+print("hello")
+```
+```bash title="shell"
+echo hello
+```
+</CodeGroup>
+~~~~
+
+```mdx
+<Note>Important information the reader should know.</Note>
+<Warning>Critical warning about potential issues.</Warning>
+<Tip>Helpful suggestion or best practice.</Tip>
+```
+
+## Automated Workflow
+
+The GitHub Actions workflow `docs_release_auto_sync_pr.yml` runs
+automatically on each release:
+
+1. Verifies `doc_code_map` patterns (`doc_code_map.py verify`).
+2. Writes `changed_python_files.txt` from the release diff for all changed
+ `*.py` files that may match `doc_code_map`.
+3. Computes `impacted_docs.txt` from that changed Python file list.
+4. Runs `auto_sync_docs_with_chatagent.py` with both files so the agent knows
+ which target doc it may inspect and update directly through terminal tools,
+ while using `changed_python_files.txt` as context. The script accepts
+ success based on whether the target doc actually changed and rejects edits
+ outside the target doc.
+5. Opens a PR with the changes.
diff --git a/.camel/skills/docs-incremental-update/scripts/auto_sync_docs_with_chatagent.py b/.camel/skills/docs-incremental-update/scripts/auto_sync_docs_with_chatagent.py
new file mode 100644
index 000000000..8f35b8573
--- /dev/null
+++ b/.camel/skills/docs-incremental-update/scripts/auto_sync_docs_with_chatagent.py
@@ -0,0 +1,301 @@
+# ========= 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. =========
+"""Auto-sync impacted docs using CAMEL ChatAgent.
+
+Reads a list of impacted .mdx doc paths plus an optional list of changed
+Python files, then asks a CAMEL ChatAgent to inspect and update each target
+document directly through TerminalToolkit.
+"""
+
+from __future__ import annotations
+
+import argparse
+import subprocess
+import sys
+import traceback
+from datetime import datetime, timezone
+from pathlib import Path
+
+SKILL_NAME = "docs-incremental-update"
+
+SYSTEM_PROMPT = """\
+You are a technical documentation writer for the CAMEL-AI framework.
+
+You will receive:
+1. The target doc path.
+2. The Python files changed in this run.
+
+Your task:
+- First load the docs-incremental-update skill and follow it.
+- Use the terminal to inspect the target doc, inspect any relevant code, and
+ update only the target document when needed.
+- Keep tool-based edits scoped to the current target doc.
+- Preserve the target document frontmatter.
+- Treat the provided changed Python files as optional context rather than a
+ hard restriction.
+- CI determines success from the resulting target doc file state. Do not rely
+ on special sentinel strings in your final chat reply.
+- If no reader-facing update is needed, leave the target doc untouched.
+- Rewrite the documentation so it accurately reflects the latest code.
+- Preserve the existing writing style, section structure, and Mintlify
+ components (Card, Accordion, Tab, CodeGroup, etc.) as much as possible.
+- Only change content that is outdated or inaccurate relative to the changed
+ Python behavior and the mapped source code.
+- Prefer no changes for small internal refactors, logging changes, test-only
+ changes, or implementation details that readers do not need.
+- If the current doc is already accurate, or the code changes are internal and
+ do not affect public API, behavior, configuration, examples, or reader
+ understanding, leave the file unchanged.
+- Do NOT return the rewritten doc body in chat. A brief status note is fine.
+"""
+
+
+def _read_path_list(list_path: Path) -> list[str]:
+ """Read a text file containing one path per line."""
+ return [
+ line.strip()
+ for line in list_path.read_text(encoding="utf-8").splitlines()
+ if line.strip()
+ ]
+
+
+def _filter_changed_python_files(changed_files: list[str]) -> list[str]:
+ """Keep only normalized Python file paths."""
+ filtered: set[str] = set()
+ for path in changed_files:
+ normalized = Path(path).as_posix()
+ if not normalized.endswith(".py"):
+ continue
+ filtered.add(normalized)
+ return sorted(filtered)
+
+
+def _format_path_section(title: str, paths: list[str]) -> str:
+ """Format a markdown section for path lists."""
+ if not paths:
+ body = "(none)"
+ else:
+ body = "\n".join(f"- {path}" for path in paths)
+ return f"## {title}\n\n{body}"
+
+
+def _git_status_paths(repo_root: Path) -> set[str] | None:
+ """Return modified or untracked repo paths from git status."""
+ try:
+ output = subprocess.check_output(
+ ["git", "status", "--porcelain", "--untracked-files=all"],
+ cwd=repo_root,
+ text=True,
+ stderr=subprocess.PIPE,
+ )
+ except (FileNotFoundError, subprocess.CalledProcessError):
+ return None
+
+ paths: set[str] = set()
+ for line in output.splitlines():
+ if len(line) < 4:
+ continue
+ path = line[3:]
+ if " -> " in path:
+ path = path.split(" -> ", 1)[1]
+ paths.add(Path(path).as_posix())
+ return paths
+
+
+def _write_agent_response_log(
+ log_dir: Path,
+ doc_path: Path,
+ result: str,
+ status: str,
+) -> None:
+ """Append the final agent response to a debug log for investigation."""
+ log_dir.mkdir(parents=True, exist_ok=True)
+ log_path = log_dir / "agent_response.log"
+ timestamp = datetime.now(timezone.utc).isoformat()
+ with log_path.open("a", encoding="utf-8") as handle:
+ handle.write(f"[{timestamp}] {status} {doc_path.as_posix()}\n")
+ handle.write(result)
+ if not result.endswith("\n"):
+ handle.write("\n")
+ handle.write("\n")
+
+
+def _build_user_message(
+ doc_path: Path,
+ changed_python_files: list[str],
+) -> str:
+ """Build the user message for a single impacted doc."""
+ changed_files_section = _format_path_section(
+ "Changed Python files for this run",
+ changed_python_files,
+ )
+ return (
+ f"## Target doc\n\n{doc_path.as_posix()}\n\n"
+ f"{changed_files_section}\n\n"
+ "Use the terminal to inspect this target doc and any relevant code, "
+ "then update this target doc directly if needed."
+ )
+
+
+def _update_single_doc(
+ doc_path: Path,
+ repo_root: Path,
+ log_dir: Path,
+ model_platform: str,
+ model_type: str,
+ changed_python_files: list[str],
+) -> None:
+ """Update a single .mdx document in place through the agent."""
+ # Lazy imports so --help works without CAMEL installed
+ from camel.agents import ChatAgent
+ from camel.models import ModelFactory
+ from camel.toolkits import SkillToolkit, TerminalToolkit
+ from camel.types import ModelPlatformType
+
+ original_text = doc_path.read_text(encoding="utf-8")
+ user_message = _build_user_message(doc_path, changed_python_files)
+ baseline_paths = _git_status_paths(repo_root)
+
+ platform = ModelPlatformType(model_platform)
+ model = ModelFactory.create(
+ model_platform=platform,
+ model_type=model_type,
+ )
+ skill_toolkit = SkillToolkit(
+ working_directory=str(repo_root),
+ allowed_skills={SKILL_NAME},
+ )
+ terminal_log_dir = str(log_dir / "terminal_sessions")
+ terminal_toolkit = TerminalToolkit(
+ working_directory=str(repo_root),
+ safe_mode=True,
+ session_logs_dir=terminal_log_dir,
+ )
+ agent = ChatAgent(
+ system_message=SYSTEM_PROMPT,
+ model=model,
+ tools=[
+ *skill_toolkit.get_tools(),
+ *terminal_toolkit.get_tools(),
+ ],
+ )
+ response = agent.step(user_message)
+
+ current_paths = _git_status_paths(repo_root)
+ target_posix = doc_path.as_posix()
+ log_dir_posix = log_dir.relative_to(repo_root).as_posix() + "/"
+ if baseline_paths is not None and current_paths is not None:
+ unexpected_paths = sorted(
+ path
+ for path in (current_paths - baseline_paths)
+ if path != target_posix and not path.startswith(log_dir_posix)
+ )
+ if unexpected_paths:
+ raise RuntimeError(
+ "Agent modified files outside the target doc: "
+ + ", ".join(unexpected_paths)
+ )
+
+ current_text = doc_path.read_text(encoding="utf-8")
+ doc_changed = current_text != original_text
+ result = response.msgs[0].content.strip() if response.msgs else ""
+ status = "UPDATED" if doc_changed else "NO_WRITE"
+ _write_agent_response_log(log_dir, doc_path, result, status)
+
+ if not doc_changed:
+ print(f" SKIP (no doc update needed): {doc_path}")
+ return
+
+ if not current_text.endswith("\n"):
+ doc_path.write_text(current_text + "\n", encoding="utf-8")
+ print(f" UPDATED: {doc_path}")
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(
+ description="Auto-sync impacted Mintlify docs with CAMEL ChatAgent."
+ )
+ parser.add_argument(
+ "--docs-file",
+ required=True,
+ help="Path to a text file listing impacted .mdx paths (one per line).",
+ )
+ parser.add_argument(
+ "--changed-files-file",
+ default=None,
+ help="Optional text file listing changed Python files for this run.",
+ )
+ parser.add_argument(
+ "--changed-file",
+ action="append",
+ default=[],
+ help="Changed Python file path. Can be passed multiple times.",
+ )
+ parser.add_argument(
+ "--model-platform",
+ default="openai",
+ help="Model platform for CAMEL ChatAgent (default: openai).",
+ )
+ parser.add_argument(
+ "--model-type",
+ default="gpt-5.4",
+ help="Model type for CAMEL ChatAgent (default: gpt-5.4).",
+ )
+ args = parser.parse_args()
+
+ docs_file = Path(args.docs_file)
+ if not docs_file.exists():
+ print(f"docs-file not found: {docs_file}")
+ return 1
+
+ doc_paths = [Path(line) for line in _read_path_list(docs_file)]
+ if not doc_paths:
+ print("No impacted docs listed. Nothing to do.")
+ return 0
+
+ changed_files = list(args.changed_file)
+ if args.changed_files_file:
+ changed_files.extend(_read_path_list(Path(args.changed_files_file)))
+ changed_python_files = _filter_changed_python_files(changed_files)
+
+ repo_root = Path(".").resolve()
+ # Use a dedicated log directory separate from TerminalToolkit's log dir
+ # to avoid TerminalToolkit's init from cleaning up our response logs.
+ log_dir = repo_root / "docs_sync_logs"
+ success = 0
+ fail = 0
+
+ print(f"Auto-syncing {len(doc_paths)} doc(s) ...")
+ for doc_path in doc_paths:
+ try:
+ _update_single_doc(
+ doc_path,
+ repo_root,
+ log_dir,
+ args.model_platform,
+ args.model_type,
+ changed_python_files,
+ )
+ success += 1
+ except Exception as exc:
+ print(f" FAIL: {doc_path} — {exc}")
+ traceback.print_exc()
+ fail += 1
+
+ print(f"\nDone. success={success} fail={fail}")
+ return 1 if fail > 0 else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/.github/workflows/docs_release_auto_sync_pr.yml b/.github/workflows/docs_release_auto_sync_pr.yml
new file mode 100644
index 000000000..9bc86d554
--- /dev/null
+++ b/.github/workflows/docs_release_auto_sync_pr.yml
@@ -0,0 +1,123 @@
+name: docs-release-auto-sync-pr
+
+on:
+ release:
+ types: [published]
+
+jobs:
+ auto-sync-docs-pr:
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ pull-requests: write
+ concurrency:
+ group: docs-release-auto-sync-${{ github.ref }}
+ cancel-in-progress: false
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+
+ - name: Setup Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.11"
+
+ - name: Install CAMEL
+ run: python -m pip install -e .
+
+ - name: Verify doc_code_map
+ run: python docs/mintlify/scripts/docs_sync/doc_code_map.py verify
+
+ - name: Determine refs
+ id: refs
+ run: |
+ current_tag="${{ github.event.release.tag_name }}"
+ prev_tag=$(git describe --tags --abbrev=0 "${current_tag}^" 2>/dev/null || true)
+ if [ -z "$prev_tag" ]; then
+ echo "No previous tag found; skip auto docs sync."
+ echo "base=" >> "$GITHUB_OUTPUT"
+ echo "head=" >> "$GITHUB_OUTPUT"
+ exit 0
+ fi
+
+ echo "base=$prev_tag" >> "$GITHUB_OUTPUT"
+ echo "head=$current_tag" >> "$GITHUB_OUTPUT"
+
+ - name: Compute impacted docs
+ if: steps.refs.outputs.base != ''
+ id: impacted
+ run: |
+ git diff --name-only "${{ steps.refs.outputs.base }}..${{ steps.refs.outputs.head }}" -- '*.py' > changed_python_files.txt || true
+ echo "Changed Python files:"
+ cat changed_python_files.txt || true
+ if [ ! -s changed_python_files.txt ]; then
+ echo "No changed Python files. Skip auto docs PR."
+ echo "has_impacted_docs=false" >> "$GITHUB_OUTPUT"
+ exit 0
+ fi
+
+ python docs/mintlify/scripts/docs_sync/doc_code_map.py impacted \
+ --changed-files-file changed_python_files.txt > impacted_docs.txt
+ cat impacted_docs.txt
+ if [ -s impacted_docs.txt ]; then
+ echo "has_impacted_docs=true" >> "$GITHUB_OUTPUT"
+ else
+ echo "has_impacted_docs=false" >> "$GITHUB_OUTPUT"
+ fi
+
+ - name: Skip when no impacted docs
+ if: steps.refs.outputs.base != '' && steps.impacted.outputs.has_impacted_docs != 'true'
+ run: |
+ echo "No impacted docs. Skip auto docs PR."
+
+ - name: Auto update impacted docs with ChatAgent
+ if: steps.impacted.outputs.has_impacted_docs == 'true'
+ env:
+ OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
+ run: |
+ if [ -z "${OPENAI_API_KEY}" ]; then
+ echo "OPENAI_API_KEY is required for auto doc sync."
+ exit 1
+ fi
+ python .camel/skills/docs-incremental-update/scripts/auto_sync_docs_with_chatagent.py \
+ --docs-file impacted_docs.txt \
+ --changed-files-file changed_python_files.txt \
+ --model-platform openai \
+ --model-type gpt-5.4
+
+ - name: Detect generated doc changes
+ if: steps.impacted.outputs.has_impacted_docs == 'true'
+ id: changes
+ run: |
+ if git diff --quiet -- docs/mintlify/key_modules docs/mintlify/mcp; then
+ echo "has_changes=false" >> "$GITHUB_OUTPUT"
+ echo "Docs were already in sync after auto-update."
+ exit 0
+ fi
+
+ echo "has_changes=true" >> "$GITHUB_OUTPUT"
+ git diff --stat -- docs/mintlify/key_modules docs/mintlify/mcp
+
+ - name: Create docs sync PR
+ if: steps.changes.outputs.has_changes == 'true'
+ uses: peter-evans/create-pull-request@v6
+ with:
+ base: ${{ github.event.repository.default_branch }}
+ branch: bot/docs-sync-${{ github.run_id }}
+ delete-branch: true
+ commit-message: "docs: auto sync mapped docs for ${{ steps.refs.outputs.head }}"
+ title: "docs: auto sync mapped docs for ${{ steps.refs.outputs.head }}"
+ body: |
+ Auto-generated docs sync PR for a release diff.
+
+ Base ref: `${{ steps.refs.outputs.base }}`
+ Head ref: `${{ steps.refs.outputs.head }}`
+
+ Updated by CAMEL ChatAgent for docs selected via `doc_code_map`,
+ with `changed_python_files.txt` provided as context.
+ labels: documentation, automated-pr
+ add-paths: |
+ docs/mintlify/key_modules
+ docs/mintlify/mcp
diff --git a/camel/models/watsonx_model.py b/camel/models/watsonx_model.py
index 24f262d28..fa4a6403b 100644
--- a/camel/models/watsonx_model.py
+++ b/camel/models/watsonx_model.py
@@ -199,7 +199,7 @@ class WatsonXModel(BaseModelBackend):
# WatsonX expects messages as a list of dictionaries
response = self._model.chat(
- messages=messages,
+ messages=[dict(m) for m in messages],
params=request_config,
tools=tools,
)
@@ -251,7 +251,7 @@ class WatsonXModel(BaseModelBackend):
# WatsonX expects messages as a list of dictionaries
response = await self._model.achat(
- messages=messages,
+ messages=[dict(m) for m in messages],
params=request_config,
tools=tools,
)
diff --git a/docs/mintlify/key_modules/Benchmark.mdx b/docs/mintlify/key_modules/Benchmark.mdx
index a873ff6bc..2c793e416 100644
--- a/docs/mintlify/key_modules/Benchmark.mdx
+++ b/docs/mintlify/key_modules/Benchmark.mdx
@@ -1,6 +1,9 @@
---
title: "BenchMarks"
description: "Learn about CAMEL's Benchmark module."
+
+doc_code_map:
+ - "camel/benchmarks/**/*.py"
---
## Overview
diff --git a/docs/mintlify/key_modules/agents.mdx b/docs/mintlify/key_modules/agents.mdx
index 9a97f0d7b..773a06c57 100644
--- a/docs/mintlify/key_modules/agents.mdx
+++ b/docs/mintlify/key_modules/agents.mdx
@@ -2,6 +2,9 @@
title: "Agents"
description: "Learn about CAMEL's agent types, with a focus on ChatAgent and advanced agent architectures for AI-powered automation."
icon: user-helmet-safety
+
+doc_code_map:
+ - "camel/agents/**/*.py"
---
diff --git a/docs/mintlify/key_modules/browsertoolkit.mdx b/docs/mintlify/key_modules/browsertoolkit.mdx
index bc91e83ca..4e2b73f4a 100644
--- a/docs/mintlify/key_modules/browsertoolkit.mdx
+++ b/docs/mintlify/key_modules/browsertoolkit.mdx
@@ -1,6 +1,10 @@
---
title: "Browser Toolkit"
icon: "globe"
+
+doc_code_map:
+ - "camel/toolkits/hybrid_browser_toolkit/**/*.py"
+ - "camel/toolkits/hybrid_browser_toolkit_py/**/*.py"
---
<Note type="info" title="What is the HybridBrowserToolkit?">
diff --git a/docs/mintlify/key_modules/datagen.mdx b/docs/mintlify/key_modules/datagen.mdx
index d3816ea31..52c15ebad 100644
--- a/docs/mintlify/key_modules/datagen.mdx
+++ b/docs/mintlify/key_modules/datagen.mdx
@@ -2,6 +2,9 @@
title: "Datagen"
description: "CAMEL’s data generation modules for high-quality, instruction-tuned, and reasoning-rich datasets."
icon: arrow-progress
+
+doc_code_map:
+ - "camel/datagen/**/*.py"
---
This page introduces CAMEL's **data generation modules** for creating high-quality training data with explicit reasoning, diverse instructions, and advanced automated refinement.
diff --git a/docs/mintlify/key_modules/embeddings.mdx b/docs/mintlify/key_modules/embeddings.mdx
index 6a3927f02..a6bd197cd 100644
--- a/docs/mintlify/key_modules/embeddings.mdx
+++ b/docs/mintlify/key_modules/embeddings.mdx
@@ -1,6 +1,9 @@
---
title: "Embeddings"
icon: vector-square
+
+doc_code_map:
+ - "camel/embeddings/**/*.py"
---
<Card title="What Are Embeddings??" icon="file-vector">
diff --git a/docs/mintlify/key_modules/interpreters.mdx b/docs/mintlify/key_modules/interpreters.mdx
index f90576db4..596f5811f 100644
--- a/docs/mintlify/key_modules/interpreters.mdx
+++ b/docs/mintlify/key_modules/interpreters.mdx
@@ -2,6 +2,9 @@
title: "Interpreters"
description: "Execute code safely and flexibly with CAMEL’s suite of interpreters: local, isolated, and cloud-based execution environments."
icon: terminal
+
+doc_code_map:
+ - "camel/interpreters/**/*.py"
---
Interpreters allow CAMEL agents to **execute code snippets** in various secure and flexible environments—from local safe execution to isolated Docker containers and managed cloud sandboxes.
@@ -184,4 +187,3 @@ print(result)
</ul>
</Accordion>
</AccordionGroup>
-```
diff --git a/docs/mintlify/key_modules/loaders.mdx b/docs/mintlify/key_modules/loaders.mdx
index 628d040ac..709a20690 100644
--- a/docs/mintlify/key_modules/loaders.mdx
+++ b/docs/mintlify/key_modules/loaders.mdx
@@ -1,12 +1,15 @@
---
title: "Loaders"
icon: loader
+
+doc_code_map:
+ - "camel/loaders/**/*.py"
---
<Card title="What are Loaders?" icon="loader">
CAMEL’s Loaders provide flexible ways to ingest and process all kinds of data
structured files, unstructured text, web content, and even OCR from images.
- They power your agent’s ability to interact with the outside world. itionally,
+ They power your agent’s ability to interact with the outside world. Additionally,
several data readers were added, including `Apify Reader`, `Chunkr Reader`,
`Firecrawl Reader`, `Jina_url Reader`, and `Mistral Reader`, which enable
retrieval of external data for improved data integration and analysis.
@@ -80,7 +83,7 @@ from camel.loaders import create_file_from_raw_bytes
# Read a pdf file from disk
with open("test.pdf", "rb") as file:
-file_content = file.read()
+ file_content = file.read()
# Use the create_file function to create an object based on the file extension
@@ -128,13 +131,24 @@ print(("\n\n".join([str(el) for el in elements])))
<strong>2. Clean unstructured text data:</strong>
<CodeGroup>
- ```python unstructured_io_clean.py example_dirty_text = ("\x93Some dirty text
- ñ€ℱ with extra spaces and – dashes.") options = [ ('replace_unicode_quotes',{" "}
- {}), ('clean_dashes', {}), ('clean_non_ascii_chars', {}),
- ('clean_extra_whitespace', {}), ] cleaned_text =
- uio.clean_text_data(text=example_dirty_text, clean_options=options)
- print(cleaned_text) ``` ```markdown cleaned_text.md >>> Some dirty text with
- extra spaces and dashes. ```
+```python unstructured_io_clean.py
+example_dirty_text = "\u201cSome dirty text\u201d with extra spaces and \u2013 dashes."
+options = [
+ ("replace_unicode_quotes", {}),
+ ("clean_dashes", {}),
+ ("clean_non_ascii_chars", {}),
+ ("clean_extra_whitespace", {}),
+]
+cleaned_text = uio.clean_text_data(
+ text=example_dirty_text,
+ clean_options=options,
+)
+print(cleaned_text)
+````
+
+```markdown cleaned_text.md
+>>> "Some dirty text" with extra spaces and dashes.
+````
</CodeGroup>
<br />
@@ -165,8 +179,8 @@ print(extracted_text)
chunks = uio.chunk_elements(elements=elements, chunk_type="chunk_by_title")
for chunk in chunks:
-print(chunk)
-print("\n" + "-" \* 80)
+ print(chunk)
+ print("\n" + "-" * 80)
````
```markdown chunked_content.md
diff --git a/docs/mintlify/key_modules/memory.mdx b/docs/mintlify/key_modules/memory.mdx
index 91e941da1..26f5f0e2a 100644
--- a/docs/mintlify/key_modules/memory.mdx
+++ b/docs/mintlify/key_modules/memory.mdx
@@ -1,6 +1,9 @@
---
title: "Memory"
icon: memory
+
+doc_code_map:
+ - "camel/memories/**/*.py"
---
<Card title="What is Memory?" icon="memory">
diff --git a/docs/mintlify/key_modules/messages.mdx b/docs/mintlify/key_modules/messages.mdx
index 4adff636f..ab4cf7ae1 100644
--- a/docs/mintlify/key_modules/messages.mdx
+++ b/docs/mintlify/key_modules/messages.mdx
@@ -1,6 +1,9 @@
---
title: "Messages"
icon: messages
+
+doc_code_map:
+ - "camel/messages/**/*.py"
---
<Card title="What is BaseMessage?" icon="message">
diff --git a/docs/mintlify/key_modules/models.mdx b/docs/mintlify/key_modules/models.mdx
index e67ce8afe..76664ac38 100644
--- a/docs/mintlify/key_modules/models.mdx
+++ b/docs/mintlify/key_modules/models.mdx
@@ -2,6 +2,9 @@
title: "Models"
description: "CAMEL-AI: Flexible integration and deployment of top LLMs and multimodal models like [OpenAI](https://openai.com/), [Mistral](https://mistral.ai/), [Gemini](https://ai.google.dev/gemini-api/docs/models), [Llama](https://www.llama.com/), [Nebius](https://nebius.com/), and more."
icon: gear-code
+
+doc_code_map:
+ - "camel/models/**/*.py"
---
<Note type="info" title="What is a Model in CAMEL?">
diff --git a/docs/mintlify/key_modules/prompts.mdx b/docs/mintlify/key_modules/prompts.mdx
index 4b1dd9ccf..7fdb60817 100644
--- a/docs/mintlify/key_modules/prompts.mdx
+++ b/docs/mintlify/key_modules/prompts.mdx
@@ -1,6 +1,9 @@
---
title: "Prompts"
icon: message-pen
+
+doc_code_map:
+ - "camel/prompts/**/*.py"
---
<Card title="What is the Prompt Module?" icon="lightbulb">
diff --git a/docs/mintlify/key_modules/retrievers.mdx b/docs/mintlify/key_modules/retrievers.mdx
index 133185baa..161c39f78 100644
--- a/docs/mintlify/key_modules/retrievers.mdx
+++ b/docs/mintlify/key_modules/retrievers.mdx
@@ -1,6 +1,9 @@
---
title: "Retrievers"
icon: code-compare
+
+doc_code_map:
+ - "camel/retrievers/**/*.py"
---
## What Are Retrievers?
diff --git a/docs/mintlify/key_modules/runtimes.mdx b/docs/mintlify/key_modules/runtimes.mdx
index 977fb3ef0..fc083b087 100644
--- a/docs/mintlify/key_modules/runtimes.mdx
+++ b/docs/mintlify/key_modules/runtimes.mdx
@@ -2,6 +2,9 @@
title: "Runtimes"
description: "Flexible, secure, and scalable code execution with CAMEL’s runtime environments: guardrails, Docker, remote, and cloud sandboxes."
icon: server
+
+doc_code_map:
+ - "camel/runtimes/**/*.py"
---
CAMEL’s **runtime module** enables the secure, flexible, and isolated execution of tools and code. Runtimes allow agents to safely run functions in controlled environments—from in-process security checks to Docker isolation and remote/cloud sandboxes.
@@ -9,53 +12,64 @@ CAMEL’s **runtime module** enables the secure, flexible, and isolated executio
## What are Runtimes?
<Note type="info" title="Runtime Concept">
- Modern agent systems often require more than a simple interpreter. <b>Runtimes</b> provide safe, scalable execution via guardrails, isolation, or remote/cloud endpoints—ideal for complex or untrusted code.
+ Modern agent systems often require more than a simple interpreter.{" "}
+ <b>Runtimes</b> provide safe, scalable execution via guardrails, isolation, or
+ remote/cloud endpoints—ideal for complex or untrusted code.
</Note>
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-2 gap-4 my-6">
- <Card icon="shield" title="LLMGuardRuntime">
- <b>Guardrail layer</b> for safe function execution.<br/>
- <ul>
- <li>LLM-based risk scoring (1=safe, 3=unsafe)</li>
- <li>Threshold control for blocking risky calls</li>
- <li>Pre-configured safety system prompt/tool</li>
- </ul>
- </Card>
-
- <Card icon="docker" title="DockerRuntime / UbuntuDockerRuntime">
- <b>Isolated, reproducible containers</b> via Docker.<br/>
- <ul>
- <li>Sandbox tool execution for safety</li>
- <li>FastAPI server for tool endpoints</li>
- <li>Ubuntu flavor supports .py script execution, env vars, and more</li>
- </ul>
- </Card>
-
- <Card icon="globe" title="RemoteHttpRuntime">
- <b>Remote, distributed execution</b> on HTTP servers.<br/>
- <ul>
- <li>Tool execution via FastAPI HTTP APIs</li>
- <li>Distribute compute and offload risky code</li>
- <li>Easy integration with remote endpoints</li>
- </ul>
- </Card>
-
- <Card icon="cloud" title="DaytonaRuntime" className="col-span-1 xl:col-span-3">
- <b>Cloud-managed sandboxing</b> with <a href="https://docs.daytona.io/" target="_blank" rel="noopener">Daytona SDK</a>.<br/>
- <ul>
- <li>Secure remote sandbox per tool</li>
- <li>Upload, run, and manage source code safely</li>
- <li>Automated input/output handling</li>
- </ul>
- </Card>
+<Card icon="shield" title="LLMGuardRuntime">
+ <b>Guardrail layer</b> for safe function execution.
+ <br />
+ <ul>
+ <li>LLM-based risk scoring (1=safe, 3=unsafe)</li>
+ <li>Threshold control for blocking risky calls</li>
+ <li>Pre-configured safety system prompt/tool</li>
+ </ul>
+</Card>
+
+<Card icon="docker" title="DockerRuntime / UbuntuDockerRuntime">
+ <b>Isolated, reproducible containers</b> via Docker.
+ <br />
+ <ul>
+ <li>Sandbox tool execution for safety</li>
+ <li>FastAPI server for tool endpoints</li>
+ <li>Ubuntu flavor supports .py script execution, env vars, and more</li>
+ </ul>
+</Card>
+
+<Card icon="globe" title="RemoteHttpRuntime">
+ <b>Remote, distributed execution</b> on HTTP servers.
+ <br />
+ <ul>
+ <li>Tool execution via FastAPI HTTP APIs</li>
+ <li>Distribute compute and offload risky code</li>
+ <li>Easy integration with remote endpoints</li>
+ </ul>
+</Card>
+
+<Card icon="cloud" title="DaytonaRuntime" className="col-span-1 xl:col-span-3">
+ <b>Cloud-managed sandboxing</b> with{" "}
+ <a href="https://docs.daytona.io/" target="_blank" rel="noopener">
+ Daytona SDK
+ </a>
+ .<br />
+ <ul>
+ <li>Secure remote sandbox per tool</li>
+ <li>Upload, run, and manage source code safely</li>
+ <li>Automated input/output handling</li>
+ </ul>
+</Card>
</div>
## Runtime Interface
All runtimes inherit from <b>BaseRuntime</b>, which defines core methods:
-- <code>add(funcs)</code>: Register one or more <code>FunctionTool</code> objects for execution
+
+- <code>add(funcs)</code>: Register one or more <code>FunctionTool</code>
+ objects for execution
- <code>reset()</code>: Reset the runtime to its initial state
- <code>get_tools()</code>: List all tools managed by the runtime
@@ -91,38 +105,38 @@ All runtimes inherit from <b>BaseRuntime</b>, which defines core methods:
## Runtime Types: Key Features
<AccordionGroup>
- <Accordion title="LLMGuardRuntime">
- <ul>
- <li>Evaluates risk before executing functions or tool calls (risk scores 1-3)</li>
- <li>Customizable LLM-driven safety logic</li>
- <li>Blocks or allows function execution based on threshold</li>
- </ul>
- </Accordion>
- <Accordion title="DockerRuntime / UbuntuDockerRuntime">
- <ul>
- <li>Runs CAMEL tools/agents in Docker containers for isolation and reproducibility</li>
- <li>UbuntuDocker flavor adds support for full script execution and system-level configuration</li>
- <li>Preconfigures <code>PYTHON_EXECUTABLE</code>, <code>PYTHONPATH</code>, and more for custom envs</li>
- </ul>
- </Accordion>
- <Accordion title="RemoteHttpRuntime">
- <ul>
- <li>Executes registered tools on a remote FastAPI server via HTTP endpoints</li>
- <li>Ideal for distributed, scalable, or cross-server tool execution</li>
- </ul>
- </Accordion>
- <Accordion title="DaytonaRuntime">
- <ul>
- <li>Runs code in a managed, remote cloud sandbox using Daytona SDK</li>
- <li>Uploads user code, executes with input/output capture</li>
- <li>Safety and resource guarantees from cloud provider</li>
- </ul>
- </Accordion>
+<Accordion title="LLMGuardRuntime">
+ <ul>
+ <li>Evaluates risk before executing functions or tool calls (risk scores 1-3)</li>
+ <li>Customizable LLM-driven safety logic</li>
+ <li>Blocks or allows function execution based on threshold</li>
+ </ul>
+</Accordion>
+<Accordion title="DockerRuntime / UbuntuDockerRuntime">
+ <ul>
+ <li>Runs CAMEL tools/agents in Docker containers for isolation and reproducibility</li>
+ <li>UbuntuDocker flavor adds support for full script execution and system-level configuration</li>
+ <li>Preconfigures <code>PYTHON_EXECUTABLE</code>, <code>PYTHONPATH</code>, and more for custom envs</li>
+ </ul>
+</Accordion>
+<Accordion title="RemoteHttpRuntime">
+ <ul>
+ <li>Executes registered tools on a remote FastAPI server via HTTP endpoints</li>
+ <li>Ideal for distributed, scalable, or cross-server tool execution</li>
+ </ul>
+</Accordion>
+<Accordion title="DaytonaRuntime">
+ <ul>
+ <li>Runs code in a managed, remote cloud sandbox using Daytona SDK</li>
+ <li>Uploads user code, executes with input/output capture</li>
+ <li>Safety and resource guarantees from cloud provider</li>
+ </ul>
+</Accordion>
</AccordionGroup>
## More Examples
-You’ll find runnable scripts for each runtime in <b>[examples/runtime](https://github.com/camel-ai/camel/tree/master/examples/runtimes)/</b> in our main repo.
+You’ll find runnable scripts for each runtime in <b>[examples/runtimes](https://github.com/camel-ai/camel/tree/master/examples/runtimes)/</b> in our main repo.
Each script demonstrates how to initialize and use a specific runtime—perfect for experimentation or production setups.
## Final Note
diff --git a/docs/mintlify/key_modules/societies.mdx b/docs/mintlify/key_modules/societies.mdx
index 9312e8f02..c94f72f03 100644
--- a/docs/mintlify/key_modules/societies.mdx
+++ b/docs/mintlify/key_modules/societies.mdx
@@ -2,6 +2,9 @@
title: "Societies"
description: "Collaborative agent frameworks in CAMEL: autonomous social behaviors, role-based task solving, and turn-based agent societies."
icon: people-group
+
+doc_code_map:
+ - "camel/societies/**/*.py"
---
<Note type="info" title="What is the Society Module?">
diff --git a/docs/mintlify/key_modules/storages.mdx b/docs/mintlify/key_modules/storages.mdx
index 9c374f95f..1d24ebf08 100644
--- a/docs/mintlify/key_modules/storages.mdx
+++ b/docs/mintlify/key_modules/storages.mdx
@@ -1,15 +1,22 @@
---
title: "Storages"
icon: database
+
+doc_code_map:
+ - "camel/storages/**/*.py"
---
## What Are Storages in CAMEL-AI?
<Card icon="database">
-The <b>Storage</b> module in CAMEL-AI gives you a **unified interface for saving, searching, and managing your data** from simple key-value records to high-performance vector databases and modern graph engines. It’s your plug-and-play toolkit for building robust, AI-ready storage layers.
+ The <b>Storage</b> module in CAMEL-AI gives you a **unified interface for
+ saving, searching, and managing your data** from simple key-value records to
+ high-performance vector databases and modern graph engines. It’s your
+ plug-and-play toolkit for building robust, AI-ready storage layers.
</Card>
---
+
## Types of Storages
<AccordionGroup>
@@ -32,6 +39,7 @@ The <b>Storage</b> module in CAMEL-AI gives you a **unified interface for saving
- Human-readable, portable JSON file storage
- Supports custom JSON encoder (for Enums, etc)
- Good for configs, small persistent datasets, export/import flows
+
</Accordion>
<Accordion title="VectorDB Storages" icon="file-vector">
@@ -71,6 +79,7 @@ The <b>Storage</b> module in CAMEL-AI gives you a **unified interface for saving
**PgVectorStorage**
- For [PostgreSQL with pgvector](https://github.com/pgvector/pgvector) (open-source vector engine)
- Leverages PostgreSQL for vector search
+
</Accordion>
<Accordion title="Graph Storages" icon="chart-waterfall">
@@ -87,11 +96,11 @@ The <b>Storage</b> module in CAMEL-AI gives you a **unified interface for saving
**Neo4jGraph**
- For [Neo4jGraph](https://neo4j.com/) (most popular enterprise graph DB)
- Widely used for graph analytics, recommendations
+
</Accordion>
</AccordionGroup>
-
## Get Started
Here are practical usage patterns for each storage type—pick the ones you need and mix them as you like.
@@ -119,6 +128,7 @@ Here are practical usage patterns for each storage type—pick the ones you need
>>> [{'key1': 'value1'}, {'key2': 'value2'}]
```
</Tab>
+
</Tabs>
</Card>
@@ -146,6 +156,7 @@ Here are practical usage patterns for each storage type—pick the ones you need
>>> [{'key1': 'value1'}, {'key2': 'value2'}]
```
</Tab>
+
</Tabs>
</Card>
@@ -181,6 +192,7 @@ Here are practical usage patterns for each storage type—pick the ones you need
>>> {'key2': 'value2'} 0.5669466853141785
```
</Tab>
+
</Tabs>
</Card>
@@ -198,7 +210,7 @@ Here are practical usage patterns for each storage type—pick the ones you need
os.environ["TIDB_DATABASE_URL"] = "The database url of your TiDB cluster."
tidb_storage = TiDBStorage(
- url_and_api_key=(os.getenv("DATABASE_URL"), ''),
+ url_and_api_key=(os.getenv("TIDB_DATABASE_URL"), ''),
vector_dim=4,
collection_name="my_collection"
)
@@ -218,10 +230,10 @@ Here are practical usage patterns for each storage type—pick the ones you need
>>> {'key2': 'value2'} 0.5669466755703252
```
</Tab>
+
</Tabs>
</Card>
-
<Card title="Qdrant Vector Storage" icon="square-q">
<b>Use for:</b> Fast, scalable open-source vector search.
<b>Perfect for:</b> RAG, document search, and high-scale retrieval tasks.
@@ -254,6 +266,7 @@ Here are practical usage patterns for each storage type—pick the ones you need
>>> {'key2': 'value2'} 0.5669467095138407
```
</Tab>
+
</Tabs>
</Card>
@@ -297,6 +310,7 @@ Here are practical usage patterns for each storage type—pick the ones you need
>>> {'key2': 'value2'} 0.7834733426570892
```
</Tab>
+
</Tabs>
</Card>
@@ -310,8 +324,9 @@ Here are practical usage patterns for each storage type—pick the ones you need
<Tab title="Python Example">
```python
import os
- from camel.storages import SurrealStorage, VectorDBQuery, VectorRecord
-
+ from camel.storages.vectordb_storages import SurrealStorage
+ from camel.storages import VectorDBQuery, VectorRecord
+
# Set environment variables for SurrealDB connection
os.environ["SURREAL_URL"] = "ws://localhost:8000/rpc"
os.environ["SURREAL_PASSWORD"] = "your_password"
@@ -347,6 +362,7 @@ Here are practical usage patterns for each storage type—pick the ones you need
>>> {'key2': 'value2'} 0.5669467095138407
```
</Tab>
+
</Tabs>
</Card>
@@ -443,6 +459,7 @@ Here are practical usage patterns for each storage type—pick the ones you need
'''
```
</Tab>
+
</Tabs>
</Card>
@@ -485,6 +502,7 @@ Here are practical usage patterns for each storage type—pick the ones you need
>>> {'key2': 'value2'} 0.7834733128547668
```
</Tab>
+
</Tabs>
</Card>
@@ -504,6 +522,7 @@ Here are practical usage patterns for each storage type—pick the ones you need
query = 'SHOW TAGS;'
print(nebula_graph.query(query))
```
+
</CodeGroup>
</Card>
@@ -526,6 +545,7 @@ Here are practical usage patterns for each storage type—pick the ones you need
print(neo4j_graph.query(query))
```
</CodeGroup>
+
</Card>
---
@@ -575,5 +595,6 @@ Here are practical usage patterns for each storage type—pick the ones you need
>>> {'key2': 'value2'} 0.5669467
```
</Tab>
+
</Tabs>
</Card>
diff --git a/docs/mintlify/key_modules/tasks.mdx b/docs/mintlify/key_modules/tasks.mdx
index 7fc0aae81..b3e814a1c 100644
--- a/docs/mintlify/key_modules/tasks.mdx
+++ b/docs/mintlify/key_modules/tasks.mdx
@@ -1,6 +1,9 @@
---
title: "Tasks"
icon: list-check
+
+doc_code_map:
+ - "camel/tasks/**/*.py"
---
For more detailed usage information, please refer to our cookbook: [Task Generation Cookbook](../cookbooks/multi_agent_society/task_generation.ipynb)
diff --git a/docs/mintlify/key_modules/terminaltoolkit.mdx b/docs/mintlify/key_modules/terminaltoolkit.mdx
index 51f1d63f0..d27914099 100644
--- a/docs/mintlify/key_modules/terminaltoolkit.mdx
+++ b/docs/mintlify/key_modules/terminaltoolkit.mdx
@@ -1,8 +1,10 @@
---
title: "Terminal Toolkit"
icon: "terminal"
----
+doc_code_map:
+ - "camel/toolkits/terminal_toolkit/**/*.py"
+---
<Note type="info" title="What is the Terminal Toolkit?">
The <b>Terminal Toolkit</b> provides a secure and powerful way for CAMEL agents to interact with a terminal. It allows agents to execute shell commands, manage files, and even ask for human help, all within a controlled, sandboxed environment.
</Note>
@@ -14,8 +16,8 @@ icon: "terminal"
<Card title="Multi-Session Management" icon="window-restore">
Run multiple, independent terminal sessions concurrently. Each session maintains its own state and history, allowing for complex, parallel workflows.
</Card>
- <Card title="Virtual Environment Management" icon="binary">
- Automatically create and manage isolated Python virtual environments, ensuring that package installations and script executions don't conflict with your system setup.
+ <Card title="Managed Runtime Environments" icon="binary">
+ The toolkit can create an isolated Python environment automatically and can optionally make additional runtimes like Go and Java available for commands started by this toolkit instance.
</Card>
<Card title="Human-in-the-Loop" icon="hand">
When an agent gets stuck, it can pause its execution and request human assistance. A human can then take over the terminal session to resolve the issue before handing control back.
@@ -66,6 +68,7 @@ The `shell_exec` function is the primary way to execute commands. Each command i
- `block=True` (default): waits for completion and returns combined stdout/stderr.
- `block=False`: starts a background session for interactive/long-running tasks.
- The `id` is how you later view output or terminate the session.
+- If a blocking command exceeds `timeout`, it is converted into a tracked background session automatically.
<Tabs>
<Tab title="Listing Files">
@@ -179,8 +182,9 @@ terminal_toolkit = TerminalToolkit(
#### Environment and Dependencies
Clone the current environment or preinstall dependencies into the sandboxed workspace.
-Use this to ensure tools like `python`, `pip`, or `uv` are available
-inside the sandboxed workspace.
+By default, the local backend tries to create an isolated Python environment in
+the workspace. It first attempts to use `uv`, then falls back to standard
+`venv` if needed.
```python
terminal_toolkit = TerminalToolkit(
@@ -190,6 +194,26 @@ terminal_toolkit = TerminalToolkit(
)
```
+#### Additional Language Runtimes
+You can optionally enable Go and Java for commands launched by this toolkit.
+
+When requested, the toolkit checks whether each runtime is already available. If
+not, it attempts to auto-install:
+- Go under `~/.camel/runtimes/go/`
+- Java (Adoptium Temurin JDK 21) under `~/.camel/runtimes/java/`
+
+These runtime paths are applied only to subprocesses started by this
+`TerminalToolkit` instance.
+
+```python
+from camel.toolkits import TerminalToolkit
+from camel.toolkits.terminal_toolkit.runtime_utils import Runtime
+
+terminal_toolkit = TerminalToolkit(
+ enable_other_runtimes=[Runtime.GO, Runtime.JAVA]
+)
+```
+
#### Write Files Directly
Use `shell_write_content_to_file` to write large files without shell escaping issues.
@@ -208,6 +232,10 @@ print(result)
### Safe Mode
When `safe_mode` is enabled (default), the toolkit blocks commands that could be harmful to your system.
+It also prevents local `cd`/`pushd` operations from escaping the configured
+`working_directory`, including chained directory changes that cannot be safely
+validated.
+
<Card title="Example of a Blocked Command" icon="shield-halved">
```python
# This command attempts to delete a file outside the workspace.
@@ -216,17 +244,22 @@ output = terminal_toolkit.shell_exec(id='session_1', command='rm /etc/hosts')
print(output)
# Expected Output:
-# Command rejected: Safety restriction: Cannot delete files outside of working directory ...
+# Error: Command rejected by TerminalToolkit safe mode.
+# Command 'rm' is blocked for safety.
```
</Card>
-
### Human-in-the-Loop
When an agent gets stuck, it can use `shell_ask_user_for_help` to request human intervention.
This call blocks and waits for a human response in the console, then returns
the user's input or the resulting command output.
+If the provided session `id` already exists, the toolkit shows the latest
+session output and lets the user send input to that running process. If the
+session does not exist, it can collect a one-off response and execute it as a
+new blocking command.
+
<Card title="Asking for Human Help" icon="hand">
```python
# The agent is stuck, so it asks for help in 'session_1'
diff --git a/docs/mintlify/key_modules/tools.mdx b/docs/mintlify/key_modules/tools.mdx
index 2d4a75841..c975a8e1c 100644
--- a/docs/mintlify/key_modules/tools.mdx
+++ b/docs/mintlify/key_modules/tools.mdx
@@ -1,28 +1,37 @@
---
title: "Tools"
icon: screwdriver-wrench
+
+doc_code_map:
+ - "camel/toolkits/**/*.py"
---
For more detailed usage information, please refer to our cookbook: [Tools Cookbook](../cookbooks/advanced_features/agents_with_tools.ipynb)
<Card title="What is a Tool?" icon="toolbox">
- A <b>Tool</b> in CAMEL is a callable function with a name, description, input parameters, and an output type.
- Tools act as the interface between agents and the outside world—think of them like <b>OpenAI Functions</b> you can easily convert, extend, or use directly.
+ A <b>Tool</b> in CAMEL is a callable function with a name, description, input
+ parameters, and an output type. Tools act as the interface between agents and
+ the outside world—think of them like <b>OpenAI Functions</b> you can easily
+ convert, extend, or use directly.
</Card>
<Card title="What is a Toolkit?" icon="screwdriver-wrench">
- A <b>Toolkit</b> is a curated collection of related tools designed to work together for a specific purpose.
- CAMEL provides a range of built-in toolkits—covering everything from web search and data extraction to code execution, GitHub integration, and much more.
+ A <b>Toolkit</b> is a curated collection of related tools designed to work
+ together for a specific purpose. CAMEL provides a range of built-in
+ toolkits—covering everything from web search and data extraction to code
+ execution, GitHub integration, and much more.
</Card>
## Get Started
<Card title="Install Toolkits" icon="terminal">
-To unlock advanced capabilities for your agents, install CAMEL's extra tools package:
-<CodeBlock language="sh" title="Install with pip">
-pip install 'camel-ai[tools]'
-</CodeBlock>
-A tool in CAMEL is just a <b>FunctionTool</b>—an interface any agent can call to run custom logic or access APIs.
+ To unlock advanced capabilities for your agents, install CAMEL's extra tools
+ package:
+ <CodeBlock language="sh" title="Install with pip">
+ pip install 'camel-ai[tools]'
+ </CodeBlock>
+ A tool in CAMEL is just a <b>FunctionTool</b>—an interface any agent can call
+ to run custom logic or access APIs.
</Card>
<Card title="Define a Custom Tool" icon="toolbox">
@@ -38,8 +47,8 @@ def add(a: int, b: int) -> int:
add_tool = FunctionTool(add)
```
-
Inspect your tool’s properties—such as its name, description, and OpenAI-compatible schema—using built-in methods:
+
<CodeGroup>
```python tool_properties.py
print(add_tool.get_function_name()) # add
@@ -54,7 +63,8 @@ Adds two numbers.
{'name': 'add', 'description': 'Adds two numbers.', 'parameters': {'properties': {'a': {'type': 'integer', 'description': 'The first number to be added.'}, 'b': {'type': 'integer', 'description': 'The second number to be added.'}}, 'required': ['a', 'b'], 'type': 'object'}}
{'type': 'function', 'function': {'name': 'add', 'description': 'Adds two numbers.', 'parameters': {'properties': {'a': {'type': 'integer', 'description': 'The first number to be added.'}, 'b': {'type': 'integer', 'description': 'The second number to be added.'}}, 'required': ['a', 'b'], 'type': 'object'}}}
-```
+
+````
</CodeGroup>
</Card>
@@ -65,7 +75,7 @@ Toolkits group related tools for specialized tasks—search, math, or automation
from camel.toolkits import SearchToolkit
toolkit = SearchToolkit()
tools = toolkit.get_tools()
-```
+````
You can also wrap toolkit methods as individual FunctionTools:
@@ -74,6 +84,7 @@ from camel.toolkits import FunctionTool, SearchToolkit
google_tool = FunctionTool(SearchToolkit().search_google)
wiki_tool = FunctionTool(SearchToolkit().search_wiki)
```
+
</Card>
<Card title="Passing Tools to ChatAgent" icon="user-cog">
@@ -86,69 +97,76 @@ tool_agent = ChatAgent(
)
response = tool_agent.step("A query related to the tool you added")
```
+
</Card>
## Built-in Toolkits
CAMEL provides a variety of built-in toolkits that you can use right away. Here's a comprehensive list of available toolkits:
-| Toolkit | Description |
-|---------|-------------|
-| ArxivToolkit | A toolkit for interacting with the arXiv API to search and download academic papers. |
-| AskNewsToolkit | A toolkit for fetching news, stories, and other content based on user queries using the AskNews API. |
-| AudioAnalysisToolkit | A toolkit for audio processing and analysis, including transcription and question answering about audio content. |
-| BrowserToolkit | A toolkit for browsing the web and interacting with web pages, including browser simulation and content extraction. |
-| CodeExecutionToolkit | A toolkit for code execution which can run code in various sandboxes including internal Python, Jupyter, Docker, subprocess, or e2b. |
-| OpenAIImageToolkit | A toolkit for image generation using OpenAI's DALL-E model. |
-| DappierToolkit | A toolkit for searching real-time data and fetching AI recommendations across key verticals like News, Finance, Stock Market, Sports, Weather and more using the Dappier API. |
-| DataCommonsToolkit | A toolkit for querying and retrieving data from the Data Commons knowledge graph, including SPARQL queries, statistical time series data, and property analysis. |
-| ExcelToolkit | A toolkit for extracting and processing content from Excel files, including conversion to markdown tables. |
-| FunctionTool | A base toolkit for creating function-based tools that OpenAI chat models can call, with support for schema parsing and synthesis. |
-| FileWriteTool | A toolkit for creating, writing, and modifying text in files. |
-| GitHubToolkit | A toolkit for interacting with GitHub repositories, including retrieving issues and creating pull requests. |
-| GoogleCalendarToolkit | A toolkit for creating events, retrieving events, updating events, and deleting events from a Google Calendar |
-| GoogleMapsToolkit | A toolkit for accessing Google Maps services, including address validation, elevation data, and timezone information. |
-| GoogleScholarToolkit | A toolkit for retrieving information about authors and their publications from Google Scholar. |
-| HumanToolkit | A toolkit for facilitating human-in-the-loop interactions and feedback in AI systems. |
-| ImageAnalysisToolkit | A toolkit for comprehensive image analysis and understanding using vision-capable language models. |
-| IMAPMailToolkit | A toolkit for IMAP email operations to spring agents into email action |
-| JinaRerankerToolkit | A toolkit for reranking documents (text or images) based on their relevance to a given query using the Jina Reranker model. |
-| LinkedInToolkit | A toolkit for LinkedIn operations including creating posts, deleting posts, and retrieving user profile information. |
-| MathToolkit | A toolkit for performing basic mathematical operations such as addition, subtraction, and multiplication. |
-| MCPToolkit | A toolkit for interacting with external tools using the Model Context Protocol (MCP). |
-| MemoryToolkit | A toolkit for saving, loading, and clearing a ChatAgent's memory. |
-| MeshyToolkit | A toolkit for working with 3D mesh data and operations. |
-| MinerUToolkit | A toolkit for extracting and processing document content using the MinerU API, with support for OCR, formula recognition, and table detection. |
-| NetworkXToolkit | A toolkit for graph operations and analysis using the NetworkX library. |
-| NotionToolkit | A toolkit for retrieving information from Notion pages and workspaces using the Notion API. |
-| OpenAPIToolkit | A toolkit for working with OpenAPI specifications and REST APIs. |
-| OpenBBToolkit | A toolkit for accessing and analyzing financial market data through the OpenBB Platform, including stocks, ETFs, cryptocurrencies, and economic indicators. |
-| PPTXToolkit | A toolkit for creating and manipulating PowerPoint (PPTX) files, including adding slides, text, and images. |
-| PubMedToolkit | A toolkit for interacting with PubMed's E-utilities API to access MEDLINE data. |
-| RedditToolkit | A toolkit for Reddit operations including collecting top posts, performing sentiment analysis on comments, and tracking keyword discussions. |
-| RetrievalToolkit | A toolkit for retrieving information from local vector storage systems based on specified queries. |
-| SearchToolkit | A toolkit for performing web searches using various search engines like Google, DuckDuckGo, Wikipedia, Bing, BaiDu and Wolfram Alpha. |
-| SemanticScholarToolkit | A toolkit for interacting with the Semantic Scholar API to fetch paper and author data from academic publications. |
-| SlackToolkit | A toolkit for Slack operations including creating channels, joining channels, and managing channel membership. |
-| StripeToolkit | A toolkit for processing payments and managing financial transactions via Stripe. |
-| SymPyToolkit | A toolkit for performing symbolic computations using SymPy, including algebraic manipulation, calculus, and linear algebra. |
-| TerminalToolkit | A toolkit for terminal operations such as searching for files by name or content, executing shell commands, and managing terminal sessions across multiple operating systems. |
-| TwitterToolkit | A toolkit for Twitter operations including creating tweets, deleting tweets, and retrieving user profile information. |
-| VideoAnalysisToolkit | A toolkit for analyzing video content with vision-language models, including frame extraction and question answering about video content. |
-| VideoDownloaderToolkit | A toolkit for downloading videos and optionally splitting them into chunks, with support for various video services. |
-| WeatherToolkit | A toolkit for fetching weather data for cities using the OpenWeatherMap API. |
-| WhatsAppToolkit | A toolkit for interacting with the WhatsApp Business API, including sending messages, managing message templates, and accessing business profile information. |
-| ZapierToolkit | A toolkit for interacting with Zapier's NLA API to execute actions through natural language commands and automate workflows. |
-| KlavisToolkit | A toolkit for interacting with Kavis AI's API to create remote hosted production-ready MCP servers. |
+| Toolkit | Description |
+| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| ArxivToolkit | A toolkit for interacting with the arXiv API to search and download academic papers. |
+| AskNewsToolkit | A toolkit for fetching news, stories, and other content based on user queries using the AskNews API. |
+| AudioAnalysisToolkit | A toolkit for audio processing and analysis, including transcription and question answering about audio content. |
+| BrowserToolkit | A toolkit for browsing the web and interacting with web pages, including browser simulation and content extraction. |
+| CodeExecutionToolkit | A toolkit for code execution which can run code in various sandboxes including internal Python, Jupyter, Docker, subprocess, or e2b. |
+| OpenAIImageToolkit | A toolkit for image generation using OpenAI's DALL-E model. |
+| DappierToolkit | A toolkit for searching real-time data and fetching AI recommendations across key verticals like News, Finance, Stock Market, Sports, Weather and more using the Dappier API. |
+| DataCommonsToolkit | A toolkit for querying and retrieving data from the Data Commons knowledge graph, including SPARQL queries, statistical time series data, and property analysis. |
+| ExcelToolkit | A toolkit for extracting and processing content from Excel files, including conversion to markdown tables. |
+| FunctionTool | A base toolkit for creating function-based tools that OpenAI chat models can call, with support for schema parsing and synthesis. |
+| FileWriteTool | A toolkit for creating, writing, and modifying text in files. |
+| GitHubToolkit | A toolkit for interacting with GitHub repositories, including retrieving issues and creating pull requests. |
+| GoogleCalendarToolkit | A toolkit for creating events, retrieving events, updating events, and deleting events from a Google Calendar |
+| GoogleMapsToolkit | A toolkit for accessing Google Maps services, including address validation, elevation data, and timezone information. |
+| GoogleScholarToolkit | A toolkit for retrieving information about authors and their publications from Google Scholar. |
+| HumanToolkit | A toolkit for facilitating human-in-the-loop interactions and feedback in AI systems. |
+| ImageAnalysisToolkit | A toolkit for comprehensive image analysis and understanding using vision-capable language models. |
+| IMAPMailToolkit | A toolkit for IMAP email operations to spring agents into email action |
+| JinaRerankerToolkit | A toolkit for reranking documents (text or images) based on their relevance to a given query using the Jina Reranker model. |
+| LinkedInToolkit | A toolkit for LinkedIn operations including creating posts, deleting posts, and retrieving user profile information. |
+| MathToolkit | A toolkit for performing basic mathematical operations such as addition, subtraction, and multiplication. |
+| MCPToolkit | A toolkit for interacting with external tools using the Model Context Protocol (MCP). |
+| MemoryToolkit | A toolkit for saving, loading, and clearing a ChatAgent's memory. |
+| MeshyToolkit | A toolkit for working with 3D mesh data and operations. |
+| MinerUToolkit | A toolkit for extracting and processing document content using the MinerU API, with support for OCR, formula recognition, and table detection. |
+| NetworkXToolkit | A toolkit for graph operations and analysis using the NetworkX library. |
+| NotionToolkit | A toolkit for retrieving information from Notion pages and workspaces using the Notion API. |
+| OpenAPIToolkit | A toolkit for working with OpenAPI specifications and REST APIs. |
+| OpenBBToolkit | A toolkit for accessing and analyzing financial market data through the OpenBB Platform, including stocks, ETFs, cryptocurrencies, and economic indicators. |
+| PPTXToolkit | A toolkit for creating and manipulating PowerPoint (PPTX) files, including adding slides, text, and images. |
+| PubMedToolkit | A toolkit for interacting with PubMed's E-utilities API to access MEDLINE data. |
+| RedditToolkit | A toolkit for Reddit operations including collecting top posts, performing sentiment analysis on comments, and tracking keyword discussions. |
+| RetrievalToolkit | A toolkit for retrieving information from local vector storage systems based on specified queries. |
+| SearchToolkit | A toolkit for performing web searches using various search engines like Google, DuckDuckGo, Wikipedia, Bing, BaiDu and Wolfram Alpha. |
+| SemanticScholarToolkit | A toolkit for interacting with the Semantic Scholar API to fetch paper and author data from academic publications. |
+| SlackToolkit | A toolkit for Slack operations including creating channels, joining channels, and managing channel membership. |
+| StripeToolkit | A toolkit for processing payments and managing financial transactions via Stripe. |
+| SymPyToolkit | A toolkit for performing symbolic computations using SymPy, including algebraic manipulation, calculus, and linear algebra. |
+| TerminalToolkit | A toolkit for terminal operations such as searching for files by name or content, executing shell commands, and managing terminal sessions across multiple operating systems. |
+| TwitterToolkit | A toolkit for Twitter operations including creating tweets, deleting tweets, and retrieving user profile information. |
+| VideoAnalysisToolkit | A toolkit for analyzing video content with vision-language models, including frame extraction and question answering about video content. |
+| VideoDownloaderToolkit | A toolkit for downloading videos and optionally splitting them into chunks, with support for various video services. |
+| WeatherToolkit | A toolkit for fetching weather data for cities using the OpenWeatherMap API. |
+| WhatsAppToolkit | A toolkit for interacting with the WhatsApp Business API, including sending messages, managing message templates, and accessing business profile information. |
+| ZapierToolkit | A toolkit for interacting with Zapier's NLA API to execute actions through natural language commands and automate workflows. |
+| KlavisToolkit | A toolkit for interacting with Klavis AI's API to create remote hosted production-ready MCP servers. |
## Using Toolkits as MCP Servers
<Card title="MCP Servers in CAMEL" icon="server">
-CAMEL supports the <b>Model Context Protocol (MCP)</b>, letting you expose any toolkit as a standalone server. This enables distributed tool execution and seamless integration across multiple systems—clients can remotely discover and invoke tools via a consistent protocol.
+ CAMEL supports the <b>Model Context Protocol (MCP)</b>, letting you expose any
+ toolkit as a standalone server. This enables distributed tool execution and
+ seamless integration across multiple systems—clients can remotely discover and
+ invoke tools via a consistent protocol.
</Card>
<Card title="What is MCP?" icon="anchor">
-MCP (Model Context Protocol) is a unified protocol for connecting LLMs with external tools and services. In CAMEL, you can turn any toolkit into an MCP server, making its tools available for remote calls—ideal for building distributed, modular, and language-agnostic AI workflows.
+ MCP (Model Context Protocol) is a unified protocol for connecting LLMs with
+ external tools and services. In CAMEL, you can turn any toolkit into an MCP
+ server, making its tools available for remote calls—ideal for building
+ distributed, modular, and language-agnostic AI workflows.
</Card>
<Card title="Expose a Toolkit as an MCP Server" icon="rocket">
@@ -181,6 +199,7 @@ if __name__ == "__main__":
toolkit = ArxivToolkit(timeout=args.timeout)
toolkit.run_mcp_server(mode=args.mode)
```
+
</Card>
<Card title="MCP Server Configuration" icon="settings">
@@ -233,6 +252,7 @@ async def run_example():
if __name__ == "__main__":
asyncio.run(run_example())
+
```
</CodeGroup>
</Card>
diff --git a/docs/mintlify/key_modules/workforce.mdx b/docs/mintlify/key_modules/workforce.mdx
index 2e33e5a04..58848d0d2 100644
--- a/docs/mintlify/key_modules/workforce.mdx
+++ b/docs/mintlify/key_modules/workforce.mdx
@@ -1,6 +1,9 @@
---
title: "Workforce"
icon: "users"
+
+doc_code_map:
+ - "camel/societies/workforce/**/*.py"
---
<Card title="Concept" icon="users">
@@ -21,11 +24,16 @@ class Workforce(BaseNode):
coordinator_agent: Optional[ChatAgent] = None,
task_agent: Optional[ChatAgent] = None,
new_worker_agent: Optional[ChatAgent] = None,
+ default_model: Optional[Union[BaseModelBackend, ModelManager]] = None,
graceful_shutdown_timeout: float = 15.0,
task_timeout_seconds: Optional[float] = None,
share_memory: bool = False,
use_structured_output_handler: bool = True,
callbacks: Optional[List[WorkforceCallback]] = None,
+ mode: WorkforceMode = WorkforceMode.AUTO_DECOMPOSE,
+ failure_handling_config: Optional[
+ Union[FailureHandlingConfig, Dict]
+ ] = None,
) -> None:
# ...
```
@@ -41,6 +49,8 @@ class Workforce(BaseNode):
- `share_memory`: If `True`, `SingleAgentWorker` instances will share memory.
- `use_structured_output_handler`: Defaults to `True`. Enables structured output handling so models without native JSON + tool-calling can still interop reliably.
- `callbacks`: Optional A list of callback handlers to observe and record workforce lifecycle events and metrics.
+- `mode`: Execution mode, either `WorkforceMode.AUTO_DECOMPOSE` (default) or `WorkforceMode.PIPELINE`.
+- `failure_handling_config`: Controls retry count, enabled recovery strategies, and whether to halt on max retries.
</Card>
<Card title="Worker Types" icon="users-gear">
@@ -103,12 +113,15 @@ workforce.add_single_agent_worker(
from camel.societies.workforce import Workforce
from camel.agents import ChatAgent
from camel.models import ModelFactory
-from camel.types import ModelType
+from camel.types import ModelPlatformType, ModelType
workforce = Workforce("Creative Writing Team")
# Create an agent with a specific model for creative tasks
-creative_model = ModelFactory.create(model_type=ModelType.GPT_5_MINI)
+creative_model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_5_MINI
+)
creative_agent = ChatAgent(
system_message="A creative writer for generating stories.",
model=creative_model
@@ -181,6 +194,37 @@ graph TD
5. **Failure Handling**: If a task fails, the `Workforce` initiates its recovery protocols.
</Card>
+<Card title="Pipeline Mode (Dependency Graph)" icon="diagram-project">
+Besides automatic decomposition, Workforce also supports predefined pipeline execution (`WorkforceMode.PIPELINE`) for deterministic multi-step workflows.
+
+```python
+from camel.societies.workforce import Workforce, WorkforceMode
+from camel.tasks import Task
+
+workforce = Workforce("Report Pipeline", mode=WorkforceMode.PIPELINE)
+
+workforce.pipeline_add("Collect data", task_id="collect") \
+ .pipeline_fork(["Analyze market", "Analyze risks"]) \
+ .pipeline_join("Write final report", task_id="report") \
+ .pipeline_build()
+
+result = workforce.process_task(Task(content="Generate weekly report"))
+```
+
+In pipeline mode, downstream tasks can still receive failure context from upstream tasks, which is useful for robust join/aggregation steps.
+</Card>
+
+<Card title="Runtime Control (Pause/Resume/Snapshot)" icon="hand">
+Workforce provides built-in runtime control APIs for human intervention and safe operations:
+
+- `pause()` / `resume()`
+- `stop_gracefully()` / `stop_immediately()` / `skip_gracefully()`
+- `save_snapshot()` / `list_snapshots()` / `restore_from_snapshot(...)`
+- `add_main_task(...)`, `add_subtask(...)`, `modify_task_content(...)`, `reorder_tasks(...)`
+
+This makes it possible to inspect and adjust execution while tasks are in progress.
+</Card>
+
<Card title="Advanced Usage: Human-in-the-Loop (HITL)" icon="hand">
To enable HITL inside a Workforce, equip the agents (coordinator, task agent, or workers) with the `HumanToolkit`. Agents can then call a human during execution (e.g., to clarify requirements, approve actions, or unblock errors).
@@ -189,14 +233,11 @@ from camel.societies.workforce import Workforce
from camel.agents import ChatAgent
from camel.toolkits import HumanToolkit
-# 1) Create the workforce
-workforce = Workforce("Interactive Workforce")
-
-# 2) Prepare human-in-the-loop tools
+# 1) Prepare human-in-the-loop tools
human_toolkit = HumanToolkit()
human_tools = human_toolkit.get_tools() # includes ask_human_via_console, send_message_to_user, ...
-# 3) Attach HumanToolkit to any agents that may need human help
+# 2) Attach HumanToolkit to any agents that may need human help
coordinator = ChatAgent(
system_message="You coordinate tasks and may ask a human for help when needed.",
tools=human_tools,
@@ -207,7 +248,7 @@ worker = ChatAgent(
tools=[human_toolkit.ask_human_via_console], # or use `human_tools`
)
-# 4) Register agents into the workforce
+# 3) Register agents into the workforce
workforce = Workforce(
description="Interactive Workforce",
coordinator_agent=coordinator,
@@ -215,7 +256,7 @@ workforce = Workforce(
)
workforce.add_single_agent_worker(description="Worker", worker=worker)
-# 5) Run tasks as usual. When an agent invokes a human tool, it will prompt via console.
+# 4) Run tasks as usual. When an agent invokes a human tool, it will prompt via console.
# workforce.process_task(Task(content="Build a quick demo and confirm requirements with the human."))
```
@@ -224,6 +265,16 @@ Notes:
- If you need async control, `process_task_async` is available, but it is not required for HITL.
</Card>
+<Card title="Workflow Memory" icon="database">
+For recurring tasks, `SingleAgentWorker` can persist and reuse workflow traces:
+
+- `save_workflow_memories_async()` (recommended async path)
+- `load_workflow_memories(...)`
+- Selection metadata via `WorkflowSelectionMethod`
+
+This helps workers reuse proven execution patterns across similar tasks.
+</Card>
+
<Card title="Key Data Structures" icon="database">
The `workforce` module uses several Pydantic models to ensure structured data exchange.
@@ -231,7 +282,7 @@ The `workforce` module uses several Pydantic models to ensure structured data ex
- **`TaskResult`**: Represents the output of a completed task.
- **`TaskAssignment`**: A single task-to-worker assignment, including dependencies.
- **`TaskAssignResult`**: A list of `TaskAssignment` objects.
-- **`RecoveryDecision`**: The output of the failure analysis process, dictating the recovery strategy.
+- **`TaskAnalysisResult`**: Unified output for failure/quality analysis, including recommended recovery strategy.
Understanding these models is key to interpreting the workforce's internal state and logs.
</Card>
@@ -247,7 +298,7 @@ Understanding these models is key to interpreting the workforce's internal state
<Card
title="API Reference"
icon="book"
- href="/reference/#societies.workforce"
+ href="/reference/camel.societies.workforce.workforce"
>
Full documentation for advanced usage and configuration.
</Card>
diff --git a/docs/mintlify/mcp/camel_agents_as_an_mcp_clients.mdx b/docs/mintlify/mcp/camel_agents_as_an_mcp_clients.mdx
index 033e8a71b..accb1df38 100644
--- a/docs/mintlify/mcp/camel_agents_as_an_mcp_clients.mdx
+++ b/docs/mintlify/mcp/camel_agents_as_an_mcp_clients.mdx
@@ -1,6 +1,11 @@
---
title: "CAMEL Agents as an MCP Client"
icon: plug
+
+doc_code_map:
+ - "camel/agents/mcp_agent.py"
+ - "camel/toolkits/mcp_toolkit.py"
+ - "camel/utils/mcp_client.py"
---
This guide walks you through turning your CAMEL AI agent into an MCP client, letting your agent easily use tools from multiple MCP servers.
@@ -11,8 +16,6 @@ This guide walks you through turning your CAMEL AI agent into an MCP client, let
2. **Use MCPToolkit to Connect**: Load your config file to connect to the servers.
3. **Enable Tools in CAMEL Agent**: Pass the server tools to your CAMEL agent to use.
-This guide walks you through turning your CAMEL AI agent into an MCP client, letting your agent easily use tools from multiple MCP servers.
-
## Step-by-Step Setup
<Steps>
@@ -51,34 +54,35 @@ This guide walks you through turning your CAMEL AI agent into an MCP client, let
}
```
</Tab>
- <Tab title="ACI.dev Server (configurable transport)">
- ```json
- {
- "mcpServers": {
- "aci_apps": {
- "command": "uvx",
- "args": [
- "aci-mcp",
- "apps-server",
- "--apps=BRAVE_SEARCH,GITHUB,ARXIV",
- "--linked-account-owner-id",
- "<your_linked_acc_owner_id>"
- ],
- "env": {
- "ACI_API_KEY": "your_aci_api_key"
- },
- "transport": "sse" // or "streamable-http"
+
+ <Tab title="ACI.dev Server (configurable transport)">
+ ```json
+ {
+ "mcpServers": {
+ "aci_apps": {
+ "command": "uvx",
+ "args": [
+ "aci-mcp",
+ "apps-server",
+ "--apps=BRAVE_SEARCH,GITHUB,ARXIV",
+ "--linked-account-owner-id",
+ "<your_linked_acc_owner_id>"
+ ],
+ "env": {
+ "ACI_API_KEY": "your_aci_api_key"
+ },
+ "transport": "sse" // or "streamable-http"
+ }
}
}
- }
- ```
- <Note type="info">
-You can use <code>sse</code> or <code>streamable-http</code> for ACI.dev, pick whichever is supported by your agent/server.
-</Note>
- </Tab>
-
+ ```
+ <Note type="info">
+ You can use <code>sse</code> or <code>streamable-http</code> for ACI.dev, pick whichever is supported by your agent/server.
+ </Note>
+ </Tab>
</Tabs>
+
</Step>
<Step title="Step 2: Connect & Build the Agent">
@@ -86,14 +90,22 @@ You can use <code>sse</code> or <code>streamable-http</code> for ACI.dev, pick w
```python
import asyncio
- from camel.toolkits.mcp_toolkit import MCPToolkit
+
from camel.agents import ChatAgent
+ from camel.models import ModelFactory
+ from camel.toolkits import MCPToolkit
+ from camel.types import ModelPlatformType, ModelType
+
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_4O,
+ )
async def main():
async with MCPToolkit(config_path="config/time.json") as toolkit:
- agent = ChatAgent(model=model, tools=toolkit.get_tools())
- response = await agent.astep("What time is it now?")
- print(response.msgs[0].content)
+ agent = ChatAgent(model=model, tools=toolkit.get_tools())
+ response = await agent.astep("What time is it now?")
+ print(response.msgs[0].content)
asyncio.run(main())
```
@@ -116,19 +128,21 @@ You can use <code>sse</code> or <code>streamable-http</code> for ACI.dev, pick w
## How It Works – System Diagram
<Card title="CAMEL Agent as an MCP Client" img="/images/camel_toolks_as_mcp_server.png">
-This diagram illustrates how CAMEL agents use MCPToolkit to seamlessly connect with MCP servers. Servers provide external tools from platforms like GitHub, Gmail, Notion, and more.
+ This diagram illustrates how CAMEL agents use MCPToolkit to seamlessly connect
+ with MCP servers. Servers provide external tools from platforms like GitHub,
+ Gmail, Notion, and more.
</Card>
-<Card title="Advanced: Register with MCP Hubs & Registries">
-
<Card title="Connect your agent to an MCP registry" icon="link">
Want your MCP agent discoverable by thousands of clients?
Register it with a hub like <a href="https://aci.dev/" target="_blank">ACI.dev</a> or similar.
-```python Register with ACI Registry lines icon="python"
-from camel.agents import MCPAgent
-from camel.types import ACIRegistryConfig, ModelFactory, ModelPlatformType, ModelType
+```python title="register_with_aci.py"
import os
+from camel.agents import MCPAgent
+from camel.models import ModelFactory
+from camel.types import ACIRegistryConfig, ModelPlatformType, ModelType
+
aci_config = ACIRegistryConfig(
api_key=os.getenv("ACI_API_KEY"),
linked_account_owner_id=os.getenv("ACI_LINKED_ACCOUNT_OWNER_ID"),
@@ -146,21 +160,17 @@ agent = MCPAgent(
Your agent is now connected to the <a href="https://aci.dev/" target="_blank">ACI.dev</a> registry and visible in the ecosystem.
</Card>
-<Card title = "Discover MCP Servers Easily with PulseMCP">
-
+<Card title="Discover MCP Servers Easily with PulseMCP" icon="wave-pulse">
Finding MCP servers is now a breeze with PulseMCP integration.
You don’t have to guess which MCP servers are available, just search, browse, and connect.
-
-<Card title="Discover MCP Servers Instantly" icon="wave-pulse">
-PulseMCP acts as a living directory of the entire MCP ecosystem.
-CAMEL toolkits can plug directly into PulseMCP, letting you browse and connect to thousands of servers, all kept up to date in real time.
+PulseMCP acts as a living directory of the entire MCP ecosystem. CAMEL toolkits can plug directly into PulseMCP, letting you browse and connect to thousands of servers, all kept up to date in real time.
You can visit [PulseMCP.com](https://pulsemcp.com) to browse all available MCP servers—everything from file systems and search to specialized APIs.
If you prefer to search programmatically inside your CAMEL code, just use:
<CodeBlock language="python" title="pulse_mcp_search.py">
-from camel.toolkits.mcp import PulseMCPSearchToolkit
+from camel.toolkits import PulseMCPSearchToolkit
search_toolkit = PulseMCPSearchToolkit()
results = search_toolkit.search_mcp_servers(query="Slack", top_k=1)
@@ -169,13 +179,11 @@ print(results)
PulseMCP does the heavy lifting of finding, categorizing, and keeping MCP servers fresh—your agents just connect and go.
</Card>
-</Card>
<Card title="Minimal agent without function-calling" icon="function">
Don’t need advanced tool-calling?
See <a href="https://github.com/camel-ai/camel/blob/master/examples/agents/mcp_agent/mcp_agent_without_function_calling.py" target="_blank">this example</a> for a super-lightweight setup.
</Card>
-</Card>
## Using Transport Methods
diff --git a/docs/mintlify/mcp/camel_toolkits_as_an_mcp_server.mdx b/docs/mintlify/mcp/camel_toolkits_as_an_mcp_server.mdx
index 67d7a85fb..03b9d6a3c 100644
--- a/docs/mintlify/mcp/camel_toolkits_as_an_mcp_server.mdx
+++ b/docs/mintlify/mcp/camel_toolkits_as_an_mcp_server.mdx
@@ -2,6 +2,12 @@
title: "Toolkit as MCP Server"
icon: "server"
description: "Share any CAMEL toolkit as an MCP server so external clients and agents can use your tools."
+
+doc_code_map:
+ - "camel/toolkits/base.py"
+ - "camel/toolkits/function_tool.py"
+ - "camel/toolkits/mcp_toolkit.py"
+ - "camel/utils/mcp_client.py"
---
<CardGroup cols={2}>
diff --git a/docs/mintlify/mcp/connecting_existing_mcp_tools.mdx b/docs/mintlify/mcp/connecting_existing_mcp_tools.mdx
index f6adcebca..b9759968d 100644
--- a/docs/mintlify/mcp/connecting_existing_mcp_tools.mdx
+++ b/docs/mintlify/mcp/connecting_existing_mcp_tools.mdx
@@ -2,6 +2,10 @@
title: 'Connect to Existing MCP Tools in CAMEL ChatAgent'
description: 'How to plug any MCP protocol tool (like file systems, web APIs) into your CAMEL ChatAgent for seamless tool-using agents.'
icon: 'network'
+
+doc_code_map:
+ - "camel/toolkits/mcp_toolkit.py"
+ - "camel/utils/mcp_client.py"
---
## Overview
diff --git a/docs/mintlify/mcp/export_camel_agent_as_mcp_server.mdx b/docs/mintlify/mcp/export_camel_agent_as_mcp_server.mdx
index 7ea13a9fb..a264b1e60 100644
--- a/docs/mintlify/mcp/export_camel_agent_as_mcp_server.mdx
+++ b/docs/mintlify/mcp/export_camel_agent_as_mcp_server.mdx
@@ -2,11 +2,17 @@
title: "CAMEL Agent as an MCP Server"
icon: server
description: "Turn your CAMEL ChatAgent into an MCP server—let any client (Claude, Cursor, custom apps) connect and use your agent as a universal AI backend."
+
+doc_code_map:
+ - "services/agent_mcp/agent_mcp_server.py"
+ - "camel/agents/mcp_agent.py"
---
<Card title="Why export a ChatAgent as an MCP server?" icon="server">
-Publishing your <b>ChatAgent</b> as an MCP server turns your agent into a universal AI backend.
-Any MCP-compatible client (Claude, Cursor, editors, or your own app) can connect, chat, and run tools through your agent as if it were a native API—no custom integration required.
+ Publishing your <b>ChatAgent</b> as an MCP server turns your agent into a
+ universal AI backend. Any MCP-compatible client (Claude, Cursor, editors, or
+ your own app) can connect, chat, and run tools through your agent as if it
+ were a native API—no custom integration required.
</Card>
## Quick Start
@@ -22,7 +28,7 @@ Configure your MCP client (Claude, Cursor, etc.) to connect:
"camel-chat-agent": {
"command": "/path/to/python",
"args": [
- "/path/to/camel/services/agent_mcp_server.py"
+ "/path/to/camel/services/agent_mcp/agent_mcp_server.py"
],
"env": {
"OPENAI_API_KEY": "...",
@@ -43,16 +49,20 @@ Turn any <code>ChatAgent</code> into an MCP server instantly with <code>to_mcp()
from camel.agents import ChatAgent
# Create a chat agent with your model
+
agent = ChatAgent(model="gpt-4o-mini")
# Convert to an MCP server
+
mcp_server = agent.to_mcp(
- name="demo", description="A demonstration of ChatAgent to MCP conversion"
+ name="demo",
+ description="A demonstration of ChatAgent to MCP conversion",
)
if __name__ == "__main__":
print("Starting MCP server on http://localhost:8000")
mcp_server.run(transport="streamable-http")
+
```
<Info>
<b>Supported transports:</b> <code>stdio</code>, <code>sse</code>, <code>streamable-http</code>
diff --git a/docs/mintlify/mcp/mcp_hub.mdx b/docs/mintlify/mcp/mcp_hub.mdx
index 4077a53ea..04d4fd60a 100644
--- a/docs/mintlify/mcp/mcp_hub.mdx
+++ b/docs/mintlify/mcp/mcp_hub.mdx
@@ -2,4 +2,7 @@
title: "CAMEL-AI MCPHub"
icon: warehouse
url: "https://mcp.camel-ai.org/"
+
+doc_code_map:
+ - "camel/toolkits/mcp_toolkit.py"
---
diff --git a/docs/mintlify/mcp/overview.mdx b/docs/mintlify/mcp/overview.mdx
index 60e3ef12f..a2bcd7ba2 100644
--- a/docs/mintlify/mcp/overview.mdx
+++ b/docs/mintlify/mcp/overview.mdx
@@ -2,6 +2,10 @@
title: 'Overview'
description: 'Introduction to MCP: what it is, why it matters, and how it transforms agent integration.'
icon: 'play'
+
+doc_code_map:
+ - "camel/toolkits/mcp_toolkit.py"
+ - "camel/utils/mcp_client.py"
---
## What is MCP all about?
diff --git a/docs/mintlify/scripts/docs_sync/README.md b/docs/mintlify/scripts/docs_sync/README.md
new file mode 100644
index 000000000..4fd8c4473
--- /dev/null
+++ b/docs/mintlify/scripts/docs_sync/README.md
@@ -0,0 +1,106 @@
+# docs code map tooling
+
+This folder keeps Mintlify documentation in sync with CAMEL source code.
+
+## Scripts
+
+| Script | Purpose |
+|--------|---------|
+| `doc_code_map.py` | Validate `doc_code_map` frontmatter and find impacted docs after code changes. |
+| `auto_sync_docs_with_chatagent.py` | Ask a CAMEL ChatAgent to inspect impacted docs with terminal tools and update them directly. Located at `.camel/skills/docs-incremental-update/scripts/`. |
+
+Documented doc roots:
+
+- `docs/mintlify/key_modules/*.mdx`
+- `docs/mintlify/mcp/*.mdx`
+
+## How It Works
+
+Each `.mdx` doc declares a `doc_code_map` block in its YAML frontmatter listing
+glob patterns for the source files it documents. When code changes land,
+`doc_code_map.py impacted` matches the changed files against those patterns to
+produce a list of impacted docs. `auto_sync_docs_with_chatagent.py` then passes
+each target doc path plus `changed_python_files.txt` to a CAMEL ChatAgent. The
+agent uses terminal tools to inspect the target doc and any relevant code, then
+updates the target doc directly when a reader-facing change is needed.
+
+The GitHub Actions workflow `.github/workflows/docs_release_auto_sync_pr.yml`
+orchestrates this end-to-end on every release tag diff and opens a PR
+automatically when mapped docs actually changed.
+
+## Commands
+
+Verify all mappings and ensure every pattern resolves to at least one file:
+
+```bash
+python docs/mintlify/scripts/docs_sync/doc_code_map.py verify
+```
+
+Print impacted docs from an explicit changed-file list:
+
+```bash
+python docs/mintlify/scripts/docs_sync/doc_code_map.py impacted \
+ --changed-file camel/toolkits/mcp_toolkit.py \
+ --changed-file camel/societies/workforce/workforce.py
+```
+
+Print impacted docs from a file containing changed paths:
+
+```bash
+python docs/mintlify/scripts/docs_sync/doc_code_map.py impacted \
+ --changed-files-file changed_python_files.txt
+```
+
+Print impacted docs from git refs:
+
+```bash
+python docs/mintlify/scripts/docs_sync/doc_code_map.py impacted --base-ref <base> --head-ref <head>
+```
+
+Auto-sync impacted docs with CAMEL ChatAgent:
+
+```bash
+python .camel/skills/docs-incremental-update/scripts/auto_sync_docs_with_chatagent.py \
+ --docs-file impacted_docs.txt \
+ --changed-files-file changed_python_files.txt \
+ --model-platform openai \
+ --model-type gpt-5.4
+```
+
+## Environment Variables
+
+The auto-sync script requires an API key for the chosen model platform.
+The release workflow is fixed to OpenAI `gpt-5.4` and expects
+`OPENAI_API_KEY`.
+
+| Platform | Variable |
+|----------|----------|
+| OpenAI (default) | `OPENAI_API_KEY` |
+| Anthropic | `ANTHROPIC_API_KEY` |
+| Other platforms | See CAMEL `ModelPlatformType` docs |
+
+Example:
+
+```bash
+export OPENAI_API_KEY=...
+```
+
+## Manual Multi-Platform Support
+
+When you run the script directly, both `--model-platform` and `--model-type`
+can be overridden to use any backend supported by CAMEL's `ModelFactory`.
+For example:
+
+```bash
+python .camel/skills/docs-incremental-update/scripts/auto_sync_docs_with_chatagent.py \
+ --docs-file impacted_docs.txt \
+ --model-platform anthropic \
+ --model-type claude-sonnet-4-20250514
+```
+
+## Repo Skill
+
+The repo skill at `.camel/skills/docs-incremental-update/` guides the agent to
+inspect the impacted doc, use `changed_python_files.txt` as context, inspect
+any other relevant code when needed, and edit that doc directly through
+terminal tools with the smallest necessary diff.
diff --git a/docs/mintlify/scripts/docs_sync/doc_code_map.py b/docs/mintlify/scripts/docs_sync/doc_code_map.py
new file mode 100644
index 000000000..fe2acbc64
--- /dev/null
+++ b/docs/mintlify/scripts/docs_sync/doc_code_map.py
@@ -0,0 +1,239 @@
+# ========= 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. =========
+"""Utilities for validating and using doc_code_map in Mintlify docs."""
+
+from __future__ import annotations
+
+import argparse
+import subprocess
+import sys
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Iterable
+
+
+DEFAULT_DOC_ROOTS = (
+ Path("docs/mintlify/key_modules"),
+ Path("docs/mintlify/mcp"),
+)
+
+
+@dataclass
+class DocMap:
+ doc_path: Path
+ patterns: list[str]
+
+
+def _iter_docs(roots: Iterable[Path]) -> list[Path]:
+ docs: list[Path] = []
+ for root in roots:
+ if not root.exists():
+ continue
+ docs.extend(sorted(root.glob("*.mdx")))
+ return docs
+
+
+def _extract_doc_code_map(doc_path: Path) -> list[str]:
+ text = doc_path.read_text(encoding="utf-8")
+ if not text.startswith("---\n"):
+ return []
+ end = text.find("\n---\n", 4)
+ if end == -1:
+ return []
+ frontmatter = text[4:end].splitlines()
+
+ patterns: list[str] = []
+ in_block = False
+ for line in frontmatter:
+ if not in_block:
+ if line.startswith("doc_code_map:"):
+ in_block = True
+ continue
+ if line.startswith(" - "):
+ item = line[4:].strip()
+ if (
+ len(item) >= 2
+ and item[0] == item[-1]
+ and item[0] in ('"', "'")
+ ):
+ item = item[1:-1]
+ if item:
+ patterns.append(item)
+ continue
+ break
+ return patterns
+
+
+def _collect_doc_maps(roots: Iterable[Path]) -> list[DocMap]:
+ docs = _iter_docs(roots)
+ return [DocMap(doc, _extract_doc_code_map(doc)) for doc in docs]
+
+
+def _run_git_diff(base_ref: str, head_ref: str) -> list[str]:
+ cmd = ["git", "diff", "--name-only", f"{base_ref}..{head_ref}"]
+ try:
+ out = subprocess.check_output(cmd, text=True, stderr=subprocess.PIPE)
+ except subprocess.CalledProcessError as exc:
+ print(f"git diff failed (exit {exc.returncode}): {exc.stderr.strip()}")
+ raise SystemExit(1) from exc
+ except FileNotFoundError as exc:
+ print("git is not available on PATH. Please install git.")
+ raise SystemExit(1) from exc
+ return [line.strip() for line in out.splitlines() if line.strip()]
+
+
+def _read_path_list(path: Path) -> list[str]:
+ """Read a text file containing one path per line."""
+ return [
+ line.strip()
+ for line in path.read_text(encoding="utf-8").splitlines()
+ if line.strip()
+ ]
+
+
+def _verify(doc_maps: list[DocMap], repo_root: Path) -> int:
+ errors: list[str] = []
+ checked = 0
+ for doc_map in doc_maps:
+ checked += 1
+ if not doc_map.patterns:
+ errors.append(
+ f"{doc_map.doc_path}: missing or empty doc_code_map block"
+ )
+ continue
+
+ for pattern in doc_map.patterns:
+ matches = list(repo_root.glob(pattern))
+ if not matches:
+ errors.append(
+ f"{doc_map.doc_path}: pattern has no matches -> {pattern}"
+ )
+
+ if errors:
+ print("doc_code_map verification failed:")
+ for err in errors:
+ print(f"- {err}")
+ return 1
+
+ print(f"doc_code_map verification passed for {checked} documents.")
+ return 0
+
+
+def _impacted_docs(
+ doc_maps: list[DocMap],
+ changed_files: list[str],
+ repo_root: Path,
+) -> list[Path]:
+ changed = {str(Path(p).as_posix()) for p in changed_files}
+ impacted: list[Path] = []
+ for doc_map in doc_maps:
+ matched = False
+ for pattern in doc_map.patterns:
+ for path in repo_root.glob(pattern):
+ rel = str(path.resolve().relative_to(repo_root).as_posix())
+ if rel in changed:
+ matched = True
+ break
+ if matched:
+ break
+ if matched:
+ impacted.append(doc_map.doc_path)
+ return sorted(impacted)
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(
+ description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ )
+ subparsers = parser.add_subparsers(dest="command")
+
+ verify_p = subparsers.add_parser(
+ "verify", help="Verify doc_code_map blocks and pattern matches."
+ )
+ verify_p.add_argument(
+ "--docs-root",
+ action="append",
+ default=[],
+ help="Root directory containing .mdx docs. Can be passed multiple times.",
+ )
+
+ impacted_p = subparsers.add_parser(
+ "impacted",
+ help="Print impacted docs based on changed files or git refs.",
+ )
+ impacted_p.add_argument(
+ "--docs-root",
+ action="append",
+ default=[],
+ help="Root directory containing .mdx docs. Can be passed multiple times.",
+ )
+ impacted_p.add_argument(
+ "--base-ref",
+ default=None,
+ help="Base git ref for diff, used with --head-ref.",
+ )
+ impacted_p.add_argument(
+ "--head-ref",
+ default="HEAD",
+ help="Head git ref for diff.",
+ )
+ impacted_p.add_argument(
+ "--changed-file",
+ action="append",
+ default=[],
+ help="Changed file path. Can be passed multiple times.",
+ )
+ impacted_p.add_argument(
+ "--changed-files-file",
+ default=None,
+ help="Path to a text file listing changed files (one per line).",
+ )
+
+ args = parser.parse_args()
+ if not args.command:
+ parser.print_help()
+ return 0
+
+ repo_root = Path(".").resolve()
+
+ roots = [Path(p) for p in args.docs_root] if args.docs_root else list(
+ DEFAULT_DOC_ROOTS
+ )
+ doc_maps = _collect_doc_maps(roots)
+
+ if args.command == "verify":
+ return _verify(doc_maps, repo_root)
+
+ changed_files: list[str] = []
+ if args.changed_file:
+ changed_files.extend(args.changed_file)
+ if args.changed_files_file:
+ changed_files.extend(_read_path_list(Path(args.changed_files_file)))
+ if not changed_files and args.base_ref:
+ changed_files.extend(_run_git_diff(args.base_ref, args.head_ref))
+ if not changed_files and not args.changed_file and not args.changed_files_file and not args.base_ref:
+ parser.error(
+ "impacted requires --changed-file, --changed-files-file, or "
+ "--base-ref/--head-ref."
+ )
+
+ impacted = _impacted_docs(doc_maps, changed_files, repo_root)
+ for doc in impacted:
+ print(str(doc))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/test/docs/test_docs_sync.py b/test/docs/test_docs_sync.py
new file mode 100644
index 000000000..8d95763b8
--- /dev/null
+++ b/test/docs/test_docs_sync.py
@@ -0,0 +1,138 @@
+# ========= 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 importlib.util
+import sys
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+
+
+def _load_module(module_name: str, file_path: Path):
+ spec = importlib.util.spec_from_file_location(module_name, file_path)
+ assert spec is not None
+ assert spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[module_name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+doc_code_map = _load_module(
+ "test_doc_code_map_module",
+ REPO_ROOT / "docs/mintlify/scripts/docs_sync/doc_code_map.py",
+)
+auto_sync_docs = _load_module(
+ "test_auto_sync_docs_module",
+ REPO_ROOT / ".camel/skills/docs-incremental-update/scripts/"
+ "auto_sync_docs_with_chatagent.py",
+)
+
+
+def test_impacted_docs_detect_matching_source_changes(tmp_path):
+ docs_root = tmp_path / "docs" / "mintlify" / "key_modules"
+ source_root = tmp_path / "camel" / "runtimes"
+ docs_root.mkdir(parents=True)
+ source_root.mkdir(parents=True)
+
+ doc_path = docs_root / "runtimes.mdx"
+ doc_path.write_text(
+ "---\n"
+ 'doc_code_map:\n'
+ ' - "camel/runtimes/**/*.py"\n'
+ "---\n"
+ "body\n",
+ encoding="utf-8",
+ )
+ (source_root / "remote.py").write_text(
+ "print('hello')\n", encoding="utf-8"
+ )
+
+ doc_maps = doc_code_map._collect_doc_maps([docs_root])
+ impacted = doc_code_map._impacted_docs(
+ doc_maps=doc_maps,
+ changed_files=["camel/runtimes/remote.py"],
+ repo_root=tmp_path,
+ )
+
+ assert impacted == [doc_path]
+
+
+def test_read_path_list_file(tmp_path):
+ path_list = tmp_path / "changed_files.txt"
+ path_list.write_text(
+ "\ncamel/agents/chat_agent.py\n\ncamel/models/base_model.py\n",
+ encoding="utf-8",
+ )
+
+ changed_files = doc_code_map._read_path_list(path_list)
+
+ assert changed_files == [
+ "camel/agents/chat_agent.py",
+ "camel/models/base_model.py",
+ ]
+
+
+def test_filter_changed_python_files_keeps_all_python_paths():
+ changed_files = [
+ "camel/agents/chat_agent.py",
+ "camel/models/base_model.py",
+ "docs/mintlify/key_modules/agents.mdx",
+ "services/doc_sync.py",
+ "tests/test_docs.py",
+ "camel/agents/README.md",
+ ]
+
+ filtered = auto_sync_docs._filter_changed_python_files(changed_files)
+
+ assert filtered == [
+ "camel/agents/chat_agent.py",
+ "camel/models/base_model.py",
+ "services/doc_sync.py",
+ "tests/test_docs.py",
+ ]
+
+
+def test_build_user_message_includes_target_doc_and_changed_files():
+ message = auto_sync_docs._build_user_message(
+ Path("docs/mintlify/key_modules/runtimes.mdx"),
+ [
+ "camel/runtimes/base.py",
+ "camel/runtimes/docker_runtime.py",
+ ],
+ )
+
+ assert "## Target doc" in message
+ assert "docs/mintlify/key_modules/runtimes.mdx" in message
+ assert "## Changed Python files for this run" in message
+ assert "camel/runtimes/base.py" in message
+ assert "camel/runtimes/docker_runtime.py" in message
+ assert "any relevant code" in message
+
+
+def test_write_agent_response_log_appends_entries(tmp_path):
+ log_dir = tmp_path / "docs_sync_logs"
+ auto_sync_docs._write_agent_response_log(
+ log_dir,
+ Path("docs/mintlify/mcp/example.mdx"),
+ "UPDATED",
+ "UPDATED",
+ )
+
+ log_path = log_dir / "agent_response.log"
+
+ assert log_path.exists()
+ content = log_path.read_text(encoding="utf-8")
+ assert "UPDATED docs/mintlify/mcp/example.mdx" in content
+ assert content.rstrip().endswith("UPDATED")