🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
chore: Small enhancement and fix (#1599)
Wendong-Fanad14a383315e
diff --git a/camel/interpreters/docker/Dockerfile b/camel/interpreters/docker/Dockerfilenew file mode 100644index 000000000..10d6ec470--- /dev/null+++ b/camel/interpreters/docker/Dockerfile@@ -0,0 +1,12 @@+FROM python:3.9-slim++# Install R and required dependencies+RUN apt-get update && apt-get install -y \+ r-base \+ && rm -rf /var/lib/apt/lists/*++# Set working directory+WORKDIR /workspace++# Keep container running+CMD ["tail", "-f", "/dev/null"]diff --git a/camel/interpreters/docker_interpreter.py b/camel/interpreters/docker_interpreter.pyindex b3ccbf68e..d38c6e060 100644--- a/camel/interpreters/docker_interpreter.py+++ b/camel/interpreters/docker_interpreter.py@@ -52,11 +52,13 @@ class DockerInterpreter(BaseInterpreter):_CODE_EXECUTE_CMD_MAPPING: ClassVar[Dict[str, str]] = {"python": "python {file_name}","bash": "bash {file_name}",+ "r": "Rscript {file_name}",}_CODE_EXTENSION_MAPPING: ClassVar[Dict[str, str]] = {"python": "py","bash": "sh",+ "r": "R",}_CODE_TYPE_MAPPING: ClassVar[Dict[str, str]] = {@@ -67,6 +69,8 @@ class DockerInterpreter(BaseInterpreter):"shell": "bash","bash": "bash","sh": "bash",+ "r": "r",+ "R": "r",}def __init__(@@ -104,8 +108,22 @@ class DockerInterpreter(BaseInterpreter):import dockerclient = docker.from_env()++ # Build custom image with Python and R+ dockerfile_path = Path(__file__).parent / "docker"+ image_tag = "camel-interpreter:latest"+ try:+ client.images.get(image_tag)+ except docker.errors.ImageNotFound:+ logger.info("Building custom interpreter image...")+ client.images.build(+ path=str(dockerfile_path),+ tag=image_tag,+ rm=True,+ )+self._container = client.containers.run(- "python:3.10",+ image_tag,detach=True,name=f"camel-interpreter-{uuid.uuid4()}",command="tail -f /dev/null",diff --git a/camel/interpreters/subprocess_interpreter.py b/camel/interpreters/subprocess_interpreter.pyindex 82951755a..37e3b3521 100644--- a/camel/interpreters/subprocess_interpreter.py+++ b/camel/interpreters/subprocess_interpreter.py@@ -48,11 +48,13 @@ class SubprocessInterpreter(BaseInterpreter):_CODE_EXECUTE_CMD_MAPPING: ClassVar[Dict[str, str]] = {"python": "python {file_name}","bash": "bash {file_name}",+ "r": "Rscript {file_name}",}_CODE_EXTENSION_MAPPING: ClassVar[Dict[str, str]] = {"python": "py","bash": "sh",+ "r": "R",}_CODE_TYPE_MAPPING: ClassVar[Dict[str, str]] = {@@ -63,6 +65,8 @@ class SubprocessInterpreter(BaseInterpreter):"shell": "bash","bash": "bash","sh": "bash",+ "r": "r",+ "R": "r",}def __init__(@@ -98,7 +102,7 @@ class SubprocessInterpreter(BaseInterpreter):if not file.is_file():raise RuntimeError(f"{file} is not a file.")code_type = self._check_code_type(code_type)- if code_type == "python":+ if self._CODE_TYPE_MAPPING[code_type] == "python":# For Python code, use ast to analyze and modify the codeimport ast@@ -113,23 +117,41 @@ class SubprocessInterpreter(BaseInterpreter):# Get the last nodeif tree.body:last_node = tree.body[-1]- # If it's an expression, wrap it in a print+ # Handle expressions that would normally not produce output+ # For example: In a REPL, typing '1 + 2' should show '3'+if isinstance(last_node, ast.Expr):- tree.body[-1] = ast.Expr(- value=ast.Call(- func=ast.Name(id='print', ctx=ast.Load()),- args=[- ast.Call(- func=ast.Name(- id='repr', ctx=ast.Load()- ),- args=[last_node.value],- keywords=[],- )- ],- keywords=[],+ # Only wrap in print(repr()) if it's not already a+ # print call+ if not (+ isinstance(last_node.value, ast.Call)+ and isinstance(last_node.value.func, ast.Name)+ and last_node.value.func.id == 'print'+ ):+ # Transform the AST to wrap the expression in print+ # (repr())+ # Example transformation:+ # Before: x + y+ # After: print(repr(x + y))+ tree.body[-1] = ast.Expr(+ value=ast.Call(+ # Create print() function call+ func=ast.Name(id='print', ctx=ast.Load()),+ args=[+ ast.Call(+ # Create repr() function call+ func=ast.Name(+ id='repr', ctx=ast.Load()+ ),+ # Pass the original expression as+ # argument to repr()+ args=[last_node.value],+ keywords=[],+ )+ ],+ keywords=[],+ ))- )# Fix missing source locationsast.fix_missing_locations(tree)# Convert back to source@@ -159,7 +181,10 @@ class SubprocessInterpreter(BaseInterpreter):return_code = proc.returncode# Clean up temporary file if it was created- if code_type == "python" and 'temp_file' in locals():+ if (+ self._CODE_TYPE_MAPPING[code_type] == "python"+ and 'temp_file' in locals()+ ):temp_file.unlink()if self.print_stdout and stdout:diff --git a/camel/toolkits/sympy_toolkit.py b/camel/toolkits/sympy_toolkit.pyindex da39a3e26..4f641d2f0 100644--- a/camel/toolkits/sympy_toolkit.py+++ b/camel/toolkits/sympy_toolkit.py@@ -721,6 +721,43 @@ class SymPyToolkit(BaseToolkit):except Exception as e:return self.handle_exception("compute_rank", e)+ def compute_inner_product(+ self, vector1: List[float], vector2: List[float]+ ) -> str:+ r"""Computes the inner (dot) product of two vectors.++ Args:+ vector1 (List[float]): The first vector as a list of floats.+ vector2 (List[float]): The second vector as a list of floats.++ Returns:+ str: JSON string containing the inner product in the `"result"`+ field. If an error occurs, the JSON string will include an+ `"error"` field with the corresponding error message.++ Raises:+ ValueError: If the vectors have different dimensions.+ """+ import sympy as sp++ try:+ # Convert the lists into sympy Matrix objects (column vectors)+ v1 = sp.Matrix(vector1)+ v2 = sp.Matrix(vector2)++ # Check that the vectors have the same dimensions.+ if v1.shape != v2.shape:+ raise ValueError(+ "Vectors must have the same dimensions to compute "+ "the inner product."+ )++ # Compute the dot (inner) product.+ inner_product = v1.dot(v2)+ return json.dumps({"result": str(inner_product)})+ except Exception as e:+ return self.handle_exception("compute_inner_product", e)+def handle_exception(self, func_name: str, error: Exception) -> str:r"""Handles exceptions by logging and returning error details.@@ -775,4 +812,5 @@ class SymPyToolkit(BaseToolkit):FunctionTool(self.compute_eigenvectors),FunctionTool(self.compute_nullspace),FunctionTool(self.compute_rank),+ FunctionTool(self.compute_inner_product),]diff --git a/docs/index.rst b/docs/index.rstindex 112b63f90..1f2f84c4a 100644--- a/docs/index.rst+++ b/docs/index.rst@@ -34,6 +34,8 @@ Main Documentation:caption: Key Modules:name: key_modules+ key_modules/agents.md+ key_modules/datagen.mdkey_modules/models.mdkey_modules/messages.mdkey_modules/memory.mddiff --git a/docs/key_modules/agents.md b/docs/key_modules/agents.mdnew file mode 100644index 000000000..ec49173bc--- /dev/null+++ b/docs/key_modules/agents.md@@ -0,0 +1,128 @@+# Agents++## 1. Concept++Agents in CAMEL are autonomous entities capable of performing specific tasks through interaction with language models and other components. Each agent is designed with a particular role and capability, allowing them to work independently or collaboratively to achieve complex goals.++### 1.1. Base Agent Architecture+All CAMEL agents inherit from the `BaseAgent` abstract class, which defines two core methods:+- `reset()`: Resets the agent to its initial state+- `step()`: Performs a single step of the agent's operation++### 1.2. Chat Agent+The `ChatAgent` is the primary implementation that handles conversations with language models. It supports:+- System message configuration for role definition+- Memory management for conversation history+- Tool/function calling capabilities+- Response formatting and structured outputs+- Multiple model backend support with scheduling strategies+- Async operation support++## 2. Types++### 2.1. `ChatAgent`+The main agent implementation for handling conversations with language models. Features include:+- Tool integration and management+- Memory management with customizable window sizes+- Output language control+- Response termination handling+- Structured output support via Pydantic models++### 2.2. `CriticAgent`+Specialized agent for evaluating and critiquing responses or solutions. Used in scenarios requiring quality assessment or validation.++### 2.3. `DeductiveReasonerAgent`+Agent focused on logical reasoning and deduction. Breaks down complex problems into smaller, manageable steps.++### 2.4. `EmbodiedAgent`+Agent designed for embodied AI scenarios, capable of understanding and responding to physical world contexts.++### 2.5. `KnowledgeGraphAgent`+Specialized in building and utilizing knowledge graphs for enhanced reasoning and information management.++### 2.6. `MultiHopGeneratorAgent`+Agent designed for handling multi-hop reasoning tasks, generating intermediate steps to reach conclusions.++### 2.7. `SearchAgent`+Focused on information retrieval and search tasks across various data sources.++### 2.8. `TaskAgent`+Handles task decomposition and management, breaking down complex tasks into manageable subtasks.++## 3. Usage++### 3.1. Basic Chat Agent Usage+```python+from camel.agents import ChatAgent++# Create a chat agent with a system message+agent = ChatAgent(system_message="You are a helpful assistant.")++# Step through a conversation+response = agent.step("Hello, can you help me?")+```++### 3.2. Using Tools with Chat Agent+```python+from camel.agents import ChatAgent+from camel.functions import FunctionTool++# Define a tool+def calculator(a: int, b: int) -> int:+ return a + b++# Create agent with tool+agent = ChatAgent(tools=[calculator])++# The agent can now use the calculator tool in conversations+response = agent.step("What is 5 + 3?")+```++### 3.3. Structured Output+```python+from pydantic import BaseModel+from typing import List++class ResponseFormat(BaseModel):+ points: List[str]+ summary: str++# Create agent with structured output+agent = ChatAgent()+response = agent.step("List benefits of exercise", response_format=ResponseFormat)+```++## 4. Best Practices++### 4.1. Memory Management+- Use appropriate window sizes to manage conversation history+- Consider token limits when dealing with long conversations+- Utilize the memory system for maintaining context++### 4.2. Tool Integration+- Keep tool functions focused and well-documented+- Handle tool errors gracefully+- Use external tools for operations that should be handled by the user++### 4.3. Response Handling+- Implement appropriate response terminators for conversation control+- Use structured outputs when specific response formats are needed+- Handle async operations properly when dealing with long-running tasks++## 5. Advanced Features++### 5.1. Model Scheduling+The agent supports multiple model backends with customizable scheduling strategies:+```python+def custom_strategy(models):+ # Custom model selection logic+ return models[0]++agent.add_model_scheduling_strategy("custom", custom_strategy)+```++### 5.2. Output Language Control+Control the language of agent responses:+```python+agent.set_output_language("Spanish")+```diff --git a/docs/key_modules/datagen.md b/docs/key_modules/datagen.mdindex 43a9c094c..f695205f8 100644--- a/docs/key_modules/datagen.md+++ b/docs/key_modules/datagen.md@@ -1,6 +1,11 @@-# Data Generation Modules+# Data Generation-This document describes the key data generation modules in CAMEL: Chain of Thought (CoT), Self-Instruct, Source2Synth, and STaR.+This document describes CAMEL's key data generation modules that enable high-quality training data creation through advanced reasoning and instruction tuning techniques. The modules include:++- Chain of Thought (CoT): Generates explicit reasoning paths+- Self-Instruct: Creates diverse instruction-following data+- Source2Synth: Converts source code into natural language+- Self-Improving CoT: Iteratively refines reasoning chains through self-critique## Chain of Thought (CoT) Data Generationdiff --git a/examples/ai_society/babyagi_playing.py b/examples/ai_society/babyagi_playing.pyindex ed8400e78..b8c155d0d 100644--- a/examples/ai_society/babyagi_playing.py+++ b/examples/ai_society/babyagi_playing.py@@ -26,7 +26,6 @@ def main(model=None, chat_turn_limit=15) -> None:user_role_name="Stock Trader",task_prompt=task_prompt,task_specify_agent_kwargs=dict(model=model),- message_window_size=5,)print(diff --git a/examples/bots/discord_bot.py b/examples/bots/discord_bot.pyindex 28d58f528..29822892d 100644--- a/examples/bots/discord_bot.py+++ b/examples/bots/discord_bot.py@@ -96,7 +96,6 @@ class BotAgent:self._agent = ChatAgent(assistant_sys_msg,- message_window_size=10,)self._auto_retriever = Nonediff --git a/examples/bots/discord_bot_use_msg_queue.py b/examples/bots/discord_bot_use_msg_queue.pyindex c7f260d82..d1e729fa0 100644--- a/examples/bots/discord_bot_use_msg_queue.py+++ b/examples/bots/discord_bot_use_msg_queue.py@@ -92,7 +92,6 @@ class BotAgent:self._agent = ChatAgent(assistant_sys_msg,- message_window_size=10,)self._auto_retriever = Nonediff --git a/examples/bots/slack_bot.py b/examples/bots/slack_bot.pyindex 5ff0f81a6..6ba9648c5 100644--- a/examples/bots/slack_bot.py+++ b/examples/bots/slack_bot.py@@ -98,7 +98,6 @@ class BotAgent:self._agent = ChatAgent(content,- message_window_size=10,)self._auto_retriever = Nonediff --git a/examples/bots/slack_bot_use_msg_queue.py b/examples/bots/slack_bot_use_msg_queue.pyindex 4e8b2bd12..d2c08184b 100644--- a/examples/bots/slack_bot_use_msg_queue.py+++ b/examples/bots/slack_bot_use_msg_queue.py@@ -101,7 +101,6 @@ class BotAgent:self._agent = ChatAgent(assistant_sys_msg,- message_window_size=10,)self._auto_retriever = Nonediff --git a/examples/models/role_playing_with_sambanova.py b/examples/models/role_playing_with_sambanova.pyindex 9b8834fe2..cbab132e2 100644--- a/examples/models/role_playing_with_sambanova.py+++ b/examples/models/role_playing_with_sambanova.py@@ -64,7 +64,6 @@ def main(model_config_dict=assistant_model_config.as_dict(),),tools=tools_list,- message_window_size=2,),user_agent_kwargs=dict(model=ModelFactory.create(@@ -73,7 +72,6 @@ def main(url="https://api.sambanova.ai/v1",model_config_dict=user_model_config.as_dict(),),- message_window_size=5,),task_prompt=task_prompt,with_task_specify=False,diff --git a/examples/structured_response/structure_response_prompt_engineering.py b/examples/structured_response/structure_response_prompt_engineering.pyindex 2458ccef8..4c85584e4 100644--- a/examples/structured_response/structure_response_prompt_engineering.py+++ b/examples/structured_response/structure_response_prompt_engineering.py@@ -39,7 +39,6 @@ qwen_model = ModelFactory.create(qwen_agent = ChatAgent(model=qwen_model,- message_window_size=10,)user_msg = """give me 1 student info."""diff --git a/test/interpreters/test_docker_interpreter.py b/test/interpreters/test_docker_interpreter.pyindex 9c91b1f98..32629b0a7 100644--- a/test/interpreters/test_docker_interpreter.py+++ b/test/interpreters/test_docker_interpreter.py@@ -102,6 +102,42 @@ if __name__ == "__main__":assert "ZeroDivisionError: division by zero" in result+def test_run_r_code(docker_interpreter: DockerInterpreter):+ code = """+ fibonacci <- function(n) {+ if (n <= 1) {+ return(n)+ } else {+ return(fibonacci(n-1) + fibonacci(n-2))+ }+ }++ result <- fibonacci(10)+ print(result)+ """+ result = docker_interpreter.run(code, "r")+ assert "[1] 55" in result+++def test_run_r_stderr(docker_interpreter: DockerInterpreter):+ code = """+ undefined_function(123)+ """+ result = docker_interpreter.run(code, "r")+ assert "Error" in result+++def test_r_code_type_variants(docker_interpreter: DockerInterpreter):+ code = "print('Hello')"+ # Test lowercase 'r'+ result1 = docker_interpreter.run(code, "r")+ assert "[1] \"Hello\"" in result1++ # Test uppercase 'R'+ result2 = docker_interpreter.run(code, "R")+ assert "[1] \"Hello\"" in result2++def test_run_unsupported_code_type(docker_interpreter: DockerInterpreter):with pytest.raises(InterpreterError) as exc_info:docker_interpreter.run("print('Hello')", "unsupported_code_type")diff --git a/test/interpreters/test_subprocess_interpreter.py b/test/interpreters/test_subprocess_interpreter.pyindex bb45c490f..c5cd24025 100644--- a/test/interpreters/test_subprocess_interpreter.py+++ b/test/interpreters/test_subprocess_interpreter.py@@ -94,6 +94,41 @@ def test_run_unsupported_code_type(subprocess_interpreter):)[email protected](reason="R may not installed on system")+def test_run_r_code(subprocess_interpreter):+ r_code = """+ add <- function(a, b) {+ return(a + b)+ }++ result <- add(10, 20)+ print(result)+ """+ result = subprocess_interpreter.run(r_code, "r")+ assert "[1] 30" in result++[email protected](reason="R may not installed on system")+def test_r_stderr(subprocess_interpreter):+ r_code = """+ undefined_function()+ """+ result = subprocess_interpreter.run(r_code, "r")+ assert "Error" in result++[email protected](reason="R may not installed on system")+def test_r_code_type_variants(subprocess_interpreter):+ r_code = "print('Hello')"+ # Test lowercase 'r'+ result1 = subprocess_interpreter.run(r_code, "r")+ assert "[1] \"Hello\"" in result1++ # Test uppercase 'R'+ result2 = subprocess_interpreter.run(r_code, "R")+ assert "[1] \"Hello\"" in result2++def test_require_confirm(subprocess_interpreter, monkeypatch):subprocess_interpreter.require_confirm = Truepython_code = "print('Hello')"diff --git a/test/prompts/test_prompt_base.py b/test/prompts/test_prompt_base.pyindex 688e08c9d..c7a249a38 100644--- a/test/prompts/test_prompt_base.py+++ b/test/prompts/test_prompt_base.py@@ -140,7 +140,7 @@ def test_code_prompt_execute(monkeypatch):"a = 1\nprint('Hello, World!')", code_type="python")result = code_prompt.execute()- assert result == "Hello, World!\nNone\n"+ assert result == "Hello, World!\n"def test_code_prompt_execute_error(monkeypatch):