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

fix: ChatAgent astep bug (#2273)

Wendong-Fan9228b32b0c6c
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
index 3f978bea1..fdee85829 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.yml
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -26,7 +26,7 @@ body:
attributes:
label: What version of camel are you using?
description: Run command `python3 -c 'print(__import__("camel").__version__)'` in your shell and paste the output here.
- placeholder: E.g., 0.2.47
+ placeholder: E.g., 0.2.48
validations:
required: true
diff --git a/camel/__init__.py b/camel/__init__.py
index eb24405b6..c91b547b5 100644
--- a/camel/__init__.py
+++ b/camel/__init__.py
@@ -14,7 +14,7 @@
from camel.logger import disable_logging, enable_logging, set_log_level
-__version__ = '0.2.47'
+__version__ = '0.2.48'
__all__ = [
'__version__',
diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.py
index 64405469d..c2d6c6645 100644
--- a/camel/agents/chat_agent.py
+++ b/camel/agents/chat_agent.py
@@ -715,11 +715,11 @@ class ChatAgent(BaseAgent):
if external_tool_call_requests is None:
external_tool_call_requests = []
external_tool_call_requests.append(tool_call_request)
-
- tool_call_record = await self._aexecute_tool(
- tool_call_request
- )
- tool_call_records.append(tool_call_record)
+ else:
+ tool_call_record = await self._aexecute_tool(
+ tool_call_request
+ )
+ tool_call_records.append(tool_call_record)
# If we found an external tool call, break the loop
if external_tool_call_requests:
diff --git a/camel/toolkits/dalle_toolkit.py b/camel/toolkits/dalle_toolkit.py
index f6fe5c474..312258943 100644
--- a/camel/toolkits/dalle_toolkit.py
+++ b/camel/toolkits/dalle_toolkit.py
@@ -20,10 +20,13 @@ from typing import List, Optional
from openai import OpenAI
from PIL import Image
+from camel.logger import get_logger
from camel.toolkits import FunctionTool
from camel.toolkits.base import BaseToolkit
from camel.utils import MCPServer
+logger = get_logger(__name__)
+
@MCPServer()
class DalleToolkit(BaseToolkit):
@@ -63,7 +66,10 @@ class DalleToolkit(BaseToolkit):
image = Image.open(image_buffer)
return image
except Exception as e:
- print(f"An error occurred while converting base64 to image: {e}")
+ error_msg = (
+ f"An error occurred while converting base64 to image: {e}"
+ )
+ logger.error(error_msg)
return None
def image_path_to_base64(self, image_path: str) -> str:
@@ -80,10 +86,11 @@ class DalleToolkit(BaseToolkit):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
except Exception as e:
- print(
+ error_msg = (
f"An error occurred while converting image path to base64: {e}"
)
- return ""
+ logger.error(error_msg)
+ return error_msg
def image_to_base64(self, image: Image.Image) -> str:
r"""Converts an image into a base64-encoded string.
@@ -108,8 +115,9 @@ class DalleToolkit(BaseToolkit):
base64_str = base64.b64encode(image_bytes).decode('utf-8')
return base64_str
except Exception as e:
- print(f"An error occurred: {e}")
- return ""
+ error_msg = f"An error occurred: {e}"
+ logger.error(error_msg)
+ return error_msg
def get_dalle_img(self, prompt: str, image_dir: str = "img") -> str:
r"""Generate an image using OpenAI's DALL-E model.
@@ -134,11 +142,17 @@ class DalleToolkit(BaseToolkit):
n=1, # NOTE: now dall-e-3 only supports n=1
response_format="b64_json",
)
+ if response.data is None or len(response.data) == 0:
+ error_msg = "No image data returned from DALL-E API."
+ logger.error(error_msg)
+ return error_msg
image_b64 = response.data[0].b64_json
image = self.base64_to_image(image_b64) # type: ignore[arg-type]
if image is None:
- raise ValueError("Failed to convert base64 string to image.")
+ error_msg = "Failed to convert base64 string to image."
+ logger.error(error_msg)
+ return error_msg
os.makedirs(image_dir, exist_ok=True)
image_path = os.path.join(image_dir, f"{uuid.uuid4()}.png")
diff --git a/docs/conf.py b/docs/conf.py
index 6adc7d693..e97cc658e 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -27,7 +27,7 @@ sys.path.insert(0, os.path.abspath('..'))
project = 'CAMEL'
copyright = '2024, CAMEL-AI.org'
author = 'CAMEL-AI.org'
-release = '0.2.47'
+release = '0.2.48'
html_favicon = (
'https://raw.githubusercontent.com/camel-ai/camel/master/misc/favicon.png'
diff --git a/docs/key_modules/loaders.md b/docs/key_modules/loaders.md
index 346f71355..0cc47218d 100644
--- a/docs/key_modules/loaders.md
+++ b/docs/key_modules/loaders.md
@@ -340,14 +340,14 @@ response = jina_reader.read_content("https://docs.camel-ai.org/")
print(response)
```
```markdown
->>>Welcome to CAMEL’s documentation! — CAMEL 0.2.47 documentation
+>>>Welcome to CAMEL’s documentation! — CAMEL 0.2.48 documentation
===============
[Skip to main content](https://docs.camel-ai.org/#main-content)
Back to top Ctrl+K
- [![Image 1](https://raw.githubusercontent.com/camel-ai/camel/master/misc/logo_light.png) ![Image 2](https://raw.githubusercontent.com/camel-ai/camel/master/misc/logo_light.png)CAMEL 0.2.47](https://docs.camel-ai.org/#)
+ [![Image 1](https://raw.githubusercontent.com/camel-ai/camel/master/misc/logo_light.png) ![Image 2](https://raw.githubusercontent.com/camel-ai/camel/master/misc/logo_light.png)CAMEL 0.2.48](https://docs.camel-ai.org/#)
Search Ctrl+K
diff --git a/pyproject.toml b/pyproject.toml
index 1d900312b..f3b031988 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "camel-ai"
-version = "0.2.47"
+version = "0.2.48"
description = "Communicative Agents for AI Society Study"
authors = [{ name = "CAMEL-AI.org" }]
requires-python = ">=3.10,<3.13"
diff --git a/test/agents/test_chat_agent.py b/test/agents/test_chat_agent.py
index dd5589943..e5ff62660 100644
--- a/test/agents/test_chat_agent.py
+++ b/test/agents/test_chat_agent.py
@@ -369,6 +369,150 @@ def test_chat_agent_step_with_external_tools(step_call_count=3):
), f"Error in calling round {i+1}"
+async def test_chat_agent_astep_with_external_tools(step_call_count=3):
+ internal_tools = [FunctionTool(SearchToolkit().search_wiki)]
+ external_tools = MathToolkit().get_tools()
+ tool_list = internal_tools + external_tools
+
+ model_config_dict = ChatGPTConfig(
+ tools=tool_list,
+ temperature=0.0,
+ ).as_dict()
+
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_4O_MINI,
+ model_config_dict=model_config_dict,
+ )
+ model_backend_external1 = ChatCompletion(
+ id='mock_id_123456',
+ choices=[
+ Choice(
+ finish_reason='tool_calls',
+ index=0,
+ logprobs=None,
+ message=ChatCompletionMessage(
+ content=None,
+ refusal=None,
+ role='assistant',
+ audio=None,
+ function_call=None,
+ tool_calls=[
+ ChatCompletionMessageToolCall(
+ id='call_mock_123456',
+ function=Function(
+ arguments='{ \
+ "entity": "Portal game release year" \
+ }',
+ name='search_wiki',
+ ),
+ type='function',
+ ),
+ ChatCompletionMessageToolCall(
+ id='call_mock_123457',
+ function=Function(
+ arguments='{ \
+ "entity": "United States founding year" \
+ }',
+ name='search_wiki',
+ ),
+ type='function',
+ ),
+ ],
+ ),
+ )
+ ],
+ created=1730745899,
+ model='gpt-4o-mini-2024-07-18',
+ object='chat.completion',
+ service_tier=None,
+ usage=CompletionUsage(
+ completion_tokens=56, prompt_tokens=292, total_tokens=348
+ ),
+ )
+
+ model_backend_external2 = ChatCompletion(
+ id='chatcmpl-mock_id_123456',
+ choices=[
+ Choice(
+ finish_reason='tool_calls',
+ index=0,
+ logprobs=None,
+ message=ChatCompletionMessage(
+ content=None,
+ refusal=None,
+ role='assistant',
+ audio=None,
+ function_call=None,
+ tool_calls=[
+ ChatCompletionMessageToolCall(
+ id='call_mock_123456',
+ function=Function(
+ arguments='{"a":1776,"b":2007}', name='sub'
+ ),
+ type='function',
+ )
+ ],
+ ),
+ )
+ ],
+ created=1730745902,
+ model='gpt-4o-mini-2024-07-18',
+ object='chat.completion',
+ service_tier=None,
+ usage=CompletionUsage(
+ completion_tokens=19, prompt_tokens=991, total_tokens=1010
+ ),
+ )
+
+ # Mock the arun method with an async function that returns the
+ # ChatCompletion objects
+ async def mock_arun(*args, **kwargs):
+ # Alternate between the two responses
+ if mock_arun.call_count % 2 == 0:
+ mock_arun.call_count += 1
+ return model_backend_external1
+ else:
+ mock_arun.call_count += 1
+ return model_backend_external2
+
+ # Initialize the counter
+ mock_arun.call_count = 0
+
+ # Assign the mock function
+ model.arun = mock_arun
+
+ # Set external_tools
+ external_tool_agent = ChatAgent(
+ system_message=BaseMessage.make_assistant_message(
+ role_name="Tools calling operator",
+ content="You are a helpful assistant",
+ ),
+ model=model,
+ tools=internal_tools,
+ external_tools=external_tools,
+ )
+
+ usr_msg = BaseMessage.make_user_message(
+ role_name="User",
+ content="What's the result of the release year of Portal subtracted "
+ "from the year that United States was founded?",
+ )
+
+ for i in range(step_call_count):
+ response = await external_tool_agent.astep(usr_msg)
+ assert not response.msg.content
+
+ external_tool_call_requests = response.info[
+ "external_tool_call_requests"
+ ]
+ assert (
+ external_tool_call_requests[0].tool_name == "sub"
+ ), f"Error in calling round {i+1}"
+
+
@pytest.mark.model_backend
def test_chat_agent_messages_window():
system_msg = BaseMessage(
diff --git a/test/toolkits/test_dalle_functions.py b/test/toolkits/test_dalle_functions.py
index 7373a4a65..729d3d17e 100644
--- a/test/toolkits/test_dalle_functions.py
+++ b/test/toolkits/test_dalle_functions.py
@@ -87,8 +87,11 @@ def test_image_to_base64_with_invalid_input(dalle_toolkit):
# Intentionally pass a non-image object to simulate an error condition
invalid_input = "This is not an image"
- # Expect the function to return None when an error occurs during encoding
+ # Expect the function to return an error message when an error occurs
+ # during encoding
result = dalle_toolkit.image_to_base64(invalid_input)
- # Assert that the function correctly returns None for invalid inputs
- assert result == ""
+ # Assert that the function correctly returns an error message for invalid
+ # inputs
+ assert "An error occurred:" in result
+ assert "'str' object has no attribute 'save'" in result
diff --git a/uv.lock b/uv.lock
index f07c5182a..293504538 100644
--- a/uv.lock
+++ b/uv.lock
@@ -539,7 +539,7 @@ wheels = [
[[package]]
name = "camel-ai"
-version = "0.2.47"
+version = "0.2.48"
source = { editable = "." }
dependencies = [
{ name = "colorama" },