Skip to content

armgit / camel

Public Imported from GitHub
0

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

feat: use code interpreter as a tool, support internal_python (#685)

maoquan5980962bcf6c
diff --git a/camel/toolkits/__init__.py b/camel/toolkits/__init__.py
index 10652ed28..a02e0c5d4 100644
--- a/camel/toolkits/__init__.py
+++ b/camel/toolkits/__init__.py
@@ -13,9 +13,11 @@
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
from .base import BaseToolkit
+from .code_execution import CodeExecutionToolkit
from .github_toolkit import GithubToolkit
__all__ = [
'BaseToolkit',
'GithubToolkit',
+ 'CodeExecutionToolkit',
]
diff --git a/camel/toolkits/code_execution.py b/camel/toolkits/code_execution.py
new file mode 100644
index 000000000..4f73c48b4
--- /dev/null
+++ b/camel/toolkits/code_execution.py
@@ -0,0 +1,69 @@
+# =========== Copyright 2023 @ 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 @ CAMEL-AI.org. All Rights Reserved. ===========
+from typing import List, Literal
+
+from camel.functions import OpenAIFunction
+from camel.interpreters import InternalPythonInterpreter
+
+from .base import BaseToolkit
+
+
+class CodeExecutionToolkit(BaseToolkit):
+ r"""A tookit for code execution.
+
+ Args:
+ sandbox (str): the environment type used to execute code.
+ """
+
+ def __init__(
+ self,
+ sandbox: Literal[
+ "internal_python", "jupyter", "docker"
+ ] = "internal_python",
+ verbose: bool = False,
+ ) -> None:
+ # TODO: Add support for docker and jupyter.
+ self.verbose = verbose
+ if sandbox == "internal_python":
+ self.interpreter = InternalPythonInterpreter()
+ else:
+ raise RuntimeError(
+ f"The sandbox type `{sandbox}` is not supported."
+ )
+
+ def execute_code(self, code: str) -> str:
+ r"""Execute a given code snippet.
+
+ Args:
+ code (str): The input code to the Code Interpreter tool call.
+
+ Returns:
+ str: The text output from the Code Interpreter tool call.
+ """
+ output = self.interpreter.run(code, "python")
+ # ruff: noqa: E501
+ content = f"Executed the code below:\n```py\n{code}\n```\n> Executed Results:\n{output}"
+ if self.verbose:
+ print(content)
+ return content
+
+ def get_tools(self) -> List[OpenAIFunction]:
+ r"""Returns a list of OpenAIFunction objects representing the
+ functions in the toolkit.
+
+ Returns:
+ List[OpenAIFunction]: A list of OpenAIFunction objects
+ representing the functions in the toolkit.
+ """
+ return [OpenAIFunction(self.execute_code)]
diff --git a/examples/function_call/code_execution.py b/examples/function_call/code_execution.py
new file mode 100644
index 000000000..c0dfe39d0
--- /dev/null
+++ b/examples/function_call/code_execution.py
@@ -0,0 +1,91 @@
+# =========== Copyright 2023 @ 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 @ CAMEL-AI.org. All Rights Reserved. ===========
+
+from colorama import Fore
+
+from camel.agents import ChatAgent
+from camel.configs import ChatGPTConfig
+from camel.messages import BaseMessage
+from camel.models import ModelFactory
+from camel.toolkits.code_execution import CodeExecutionToolkit
+from camel.types import ModelPlatformType, ModelType
+from camel.utils import print_text_animated
+
+# tools
+toolkit = CodeExecutionToolkit(verbose=True)
+tools = toolkit.get_tools()
+
+# set up LLM model
+assistant_model_config = ChatGPTConfig(
+ temperature=0.0,
+ tools=tools,
+)
+
+model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_3_5_TURBO,
+ model_config_dict=assistant_model_config.__dict__,
+)
+
+
+# set up agent
+assistant_sys_msg = BaseMessage.make_assistant_message(
+ role_name="Teacher",
+ content=(
+ "You are a personal math tutor and programmer. "
+ "When asked a math question, "
+ "write and run Python code to answer the question."
+ ),
+)
+
+agent = ChatAgent(
+ assistant_sys_msg,
+ model,
+ tools=tools,
+)
+agent.reset()
+
+
+# set up agent
+
+prompt = (
+ "Weng earns $12 an hour for babysitting. "
+ "Yesterday, she just did 51 minutes of babysitting. How much did she earn?"
+)
+user_msg = BaseMessage.make_user_message(role_name="User", content=prompt)
+print(Fore.YELLOW + f"user prompt:\n{prompt}\n")
+
+response = agent.step(user_msg)
+for msg in response.msgs:
+ print_text_animated(Fore.GREEN + f"Agent response:\n{msg.content}\n")
+
+# ruff: noqa: E501
+"""
+===============================================================================
+user prompt:
+Weng earns $12 an hour for babysitting. Yesterday, she just did 51 minutes of babysitting. How much did she earn?
+
+Executed the code below:
+```py
+hourly_rate = 12
+minutes_worked = 51
+hourly_earnings = hourly_rate / 60 * minutes_worked
+hourly_earnings
+```
+> Executed Results:
+10.200000000000001
+Agent response:
+Weng earned $10.20 for babysitting for 51 minutes at a rate of $12 per hour.
+===============================================================================
+"""
diff --git a/test/functions/test_code_execution.py b/test/functions/test_code_execution.py
new file mode 100644
index 000000000..47653c42b
--- /dev/null
+++ b/test/functions/test_code_execution.py
@@ -0,0 +1,25 @@
+# =========== Copyright 2023 @ 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 @ CAMEL-AI.org. All Rights Reserved. ===========
+
+from camel.toolkits.code_execution import CodeExecutionToolkit
+
+
+def test_execute_code():
+ toolkit = CodeExecutionToolkit()
+ code = "x = 'a'\ny = 'b'\nx + y"
+ result = toolkit.execute_code(code)
+
+ # ruff: noqa: E501
+ expected_result = f"Executed the code below:\n```py\n{code}\n```\n> Executed Results:\nab"
+ assert expected_result == result