🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
feat: task support adding multi modal information (#2697)
Melodyssb9c213a34459
diff --git a/camel/messages/base.py b/camel/messages/base.pyindex e47904bec..9dd379831 100644--- a/camel/messages/base.py+++ b/camel/messages/base.py@@ -69,7 +69,7 @@ class BaseMessage:image_detail (Literal["auto", "low", "high"]): Detail level of theimages associated with the message. (default: :obj:`auto`)video_detail (Literal["auto", "low", "high"]): Detail level of the- videos associated with the message. (default: :obj:`low`)+ videos associated with the message. (default: :obj:`auto`)parsed: Optional[Union[Type[BaseModel], dict]]: Optional object whichis parsed from the content. (default: :obj:`None`)"""@@ -82,7 +82,7 @@ class BaseMessage:video_bytes: Optional[bytes] = Noneimage_list: Optional[List[Image.Image]] = Noneimage_detail: Literal["auto", "low", "high"] = "auto"- video_detail: Literal["auto", "low", "high"] = "low"+ video_detail: Literal["auto", "low", "high"] = "auto"parsed: Optional[Union[BaseModel, dict]] = None@classmethoddiff --git a/camel/tasks/task.py b/camel/tasks/task.pyindex cd56bf1e3..ee22c6c6a 100644--- a/camel/tasks/task.py+++ b/camel/tasks/task.py@@ -25,7 +25,8 @@ from typing import (Union,)-from pydantic import BaseModel, Field+from PIL import Image+from pydantic import BaseModel, ConfigDict, Fieldif TYPE_CHECKING:from camel.agents import ChatAgent@@ -158,6 +159,14 @@ class Task(BaseModel):(default: :obj:`0`)additional_info (Optional[Dict[str, Any]]): Additional information forthe task. (default: :obj:`None`)+ image_list (Optional[List[Image.Image]]): Optional list of PIL Image+ objects associated with the task. (default: :obj:`None`)+ image_detail (Literal["auto", "low", "high"]): Detail level of the+ images associated with the task. (default: :obj:`auto`)+ video_bytes (Optional[bytes]): Optional bytes of a video associated+ with the task. (default: :obj:`None`)+ video_detail (Literal["auto", "low", "high"]): Detail level of the+ videos associated with the task. (default: :obj:`auto`)"""content: str@@ -180,6 +189,16 @@ class Task(BaseModel):additional_info: Optional[Dict[str, Any]] = None+ image_list: Optional[List[Image.Image]] = None++ image_detail: Literal["auto", "low", "high"] = "auto"++ video_bytes: Optional[bytes] = None++ video_detail: Literal["auto", "low", "high"] = "auto"++ model_config = ConfigDict(arbitrary_types_allowed=True)+def __repr__(self) -> str:r"""Return a string representation of the task."""content_preview = self.content@@ -363,6 +382,10 @@ class Task(BaseModel):role_name=role_name,content=self.content,additional_info=self.additional_info,+ image_list=self.image_list,+ image_detail=self.image_detail,+ video_bytes=self.video_bytes,+ video_detail=self.video_detail,other_results=sub_tasks_result,)msg = BaseMessage.make_user_message(@@ -513,7 +536,12 @@ class TaskManager:role_name = agent.role_namecontent = template.format(role_name=role_name, content=task.content)msg = BaseMessage.make_user_message(- role_name=role_name, content=content+ role_name=role_name,+ content=content,+ image_list=task.image_list,+ image_detail=task.image_detail,+ video_bytes=task.video_bytes,+ video_detail=task.video_detail,)response = agent.step(msg)if task_parser is None:diff --git a/examples/tasks/multi_modal_task_generation.py b/examples/tasks/multi_modal_task_generation.pynew file mode 100644index 000000000..b93aa5f98--- /dev/null+++ b/examples/tasks/multi_modal_task_generation.py@@ -0,0 +1,141 @@+# ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. =========++import io+import os++from PIL import Image++from camel.agents import ChatAgent+from camel.configs import ChatGPTConfig+from camel.models import ModelFactory+from camel.tasks import (+ Task,+ TaskManager,+)+from camel.types import (+ ModelPlatformType,+ ModelType,+)++# set up LLM model+assistant_model_config = ChatGPTConfig(+ temperature=0.0,+)++model = ModelFactory.create(+ model_platform=ModelPlatformType.QWEN,+ model_type=ModelType.QWEN_VL_MAX,+ model_config_dict={"temperature": 0.0},+)+++def load_image(image_path: str) -> Image.Image:+ """+ Load an image and ensure it has a valid format like PNG or JPEG.+ """+ if not os.path.exists(image_path):+ raise FileNotFoundError(f"Image file not found: {image_path}")++ with Image.open(image_path) as img:+ img_format = img.format or "PNG"++ buffer = io.BytesIO()+ img.save(buffer, format=img_format)+ buffer.seek(0)+ return Image.open(buffer)+++def load_video(video_path: str) -> bytes:+ if not os.path.exists(video_path):+ raise FileNotFoundError(f"Video file not found: {video_path}")+ with open(video_path, "rb") as f:+ return f.read()+++# set up agent+assistant_sys_msg = "You are a personal math tutor and programmer."+agent = ChatAgent(assistant_sys_msg, model=model)+agent.reset()+++def create_image_task(image_path: str, task_id: str = "0") -> Task:+ image = load_image(image_path)+ return Task(+ content="The task is in the image.", image_list=[image], id=task_id+ )+++def create_video_task(video_path: str, task_id: str = "1") -> Task:+ video_bytes = load_video(video_path)+ return Task(+ content="The task is in the video.",+ video_bytes=video_bytes,+ id=task_id,+ )+++# Example usage+img_path = "./examples/tasks/task_image.png"+video_path = "./examples/tasks/task_video.mov"++tasks = []+try:+ image_task = create_image_task(img_path, task_id="0")+ tasks.append(image_task)+except FileNotFoundError as e:+ print(f"Skipping image task: {e}")++try:+ video_task = create_video_task(video_path, task_id="1")+ tasks.append(video_task)+except FileNotFoundError as e:+ print(f"Skipping video task: {e}")++if not tasks:+ print("No valid tasks found. Please ensure example files exist.")+ exit(1)++for task in tasks:+ task_manager = TaskManager(task)++ evolved_task = task_manager.evolve(task, agent=agent)+ if evolved_task is not None:+ print(evolved_task.to_string())+ else:+ print("Evolved task is None.")++ new_tasks = task.decompose(agent=agent)+ for t in new_tasks:+ print(t.to_string())++# ruff: noqa: E501+"""+===============================================================================+Task 0: Weng earns $12 an hour for babysitting. Yesterday, she just did 51+minutes of babysitting. How much did she earn?++Task 0.0: Weng earns $12 an hour for babysitting. However, her hourly rate+increases by $2 for every additional hour worked beyond the first hour.+Yesterday, she babysat for a total of 3 hours and 45 minutes. How much did she+earn in total for her babysitting services?++Task 0.0: Convert 51 minutes to hours.++Task 0.1: Calculate the proportion of 51 minutes to an hour.++Task 0.2: Multiply the proportion by Weng's hourly rate to find out how much+she earned for 51 minutes of babysitting.+===============================================================================+"""diff --git a/examples/tasks/task_image.png b/examples/tasks/task_image.pngnew file mode 100644index 000000000..3ea553737Binary files /dev/null and b/examples/tasks/task_image.png differdiff --git a/examples/tasks/task_video.mov b/examples/tasks/task_video.movnew file mode 100644index 000000000..d903662a1Binary files /dev/null and b/examples/tasks/task_video.mov differdiff --git a/examples/workforce/eigent.py b/examples/workforce/eigent.pyindex 1b4014f6c..ea40f2235 100644--- a/examples/workforce/eigent.py+++ b/examples/workforce/eigent.py@@ -28,7 +28,7 @@ from camel.toolkits import (EdgeOnePagesMCPToolkit,FileWriteToolkit,FunctionTool,- GoogleDriveMCPToolkit,+ # GoogleDriveMCPToolkit,HumanToolkit,ImageAnalysisToolkit,LinkedInToolkit,@@ -172,14 +172,14 @@ Here are some tips that help you perform web search:def document_agent_factory(model: BaseModelBackend,task_id: str,- google_drive_mcp_toolkit: GoogleDriveMCPToolkit,+ # google_drive_mcp_toolkit: GoogleDriveMCPToolkit,):r"""Factory for creating a document agent, based on user-provided codestructure."""tools = [*FileWriteToolkit().get_tools(),*PPTXToolkit().get_tools(),- *google_drive_mcp_toolkit.get_tools(),+ # *google_drive_mcp_toolkit.get_tools(),# *RetrievalToolkit().get_tools(),HumanToolkit().ask_human_via_console,*MarkItDownToolkit().get_tools(),@@ -353,12 +353,12 @@ operations.async def main():edgeone_pages_mcp_toolkit = EdgeOnePagesMCPToolkit()- google_drive_mcp_toolkit = GoogleDriveMCPToolkit(- credentials_path="path/to/credentials.json"- )+ # google_drive_mcp_toolkit = GoogleDriveMCPToolkit(+ # credentials_path="path/to/credentials.json"+ # )try:await edgeone_pages_mcp_toolkit.connect()- await google_drive_mcp_toolkit.connect()+ # await google_drive_mcp_toolkit.connect()# Create a single model backend for all agentsmodel_backend = ModelFactory.create(@@ -390,7 +390,9 @@ async def main():model_backend, task_id, edgeone_pages_mcp_toolkit)document_agent = document_agent_factory(- model_backend, task_id, google_drive_mcp_toolkit+ model_backend,+ task_id,+ # google_drive_mcp_toolkit)multi_modal_agent = multi_modal_agent_factory(model_backend, task_id)@@ -463,7 +465,7 @@ slides should be very comprehensive and professional.finally:await edgeone_pages_mcp_toolkit.disconnect()- await google_drive_mcp_toolkit.disconnect()+ # await google_drive_mcp_toolkit.disconnect()if __name__ == "__main__":diff --git a/test/models/test_model_manager.py b/test/models/test_model_manager.pyindex 0027e4d4d..36033833d 100644--- a/test/models/test_model_manager.py+++ b/test/models/test_model_manager.py@@ -72,7 +72,7 @@ def test_model_manager(assert model.run.call_count == times_each_model_calledif strategy == "always_first":assert model_manager.scheduling_strategy.__name__ == "always_first"- assert models[0].run.call_count == times_each_model_called+ assert models[0].run.call_count == times_each_model_called # type: ignore[attr-defined]if strategy == "random_model":assert model_manager.scheduling_strategy.__name__ == "random_model"diff --git a/test/tasks/test_task.py b/test/tasks/test_task.pyindex 53bdc6cb2..4eb1c01bc 100644--- a/test/tasks/test_task.py+++ b/test/tasks/test_task.py@@ -11,6 +11,12 @@# See the License for the specific language governing permissions and# limitations under the License.# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========+import os+import tempfile++import pytest+from PIL import Image+from camel.tasks import Task, TaskManager@@ -78,3 +84,138 @@ def test_task_management():"3","0",]+++def temp_image():+ # Create temporary image file and return PIL Image object+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:+ img = Image.new("RGB", (10, 10), color="blue")+ img.save(f, format="PNG")+ f.flush()+ # Load image into memory to avoid file dependency+ with Image.open(f.name) as loaded_img:+ image = loaded_img.copy()+ yield image+ os.remove(f.name)+++def temp_video_bytes():+ # Create temporary video file and read as bytes+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as f:+ video_data = b"fake video data"+ f.write(video_data)+ f.flush()+ yield video_data+ os.remove(f.name)+++def test_image_task_management(temp_image):+ """+ Task 0: Analyze image+ Task 1: Detect objects in image+ Task 2: Recognize text in image+ Task 2.1: Recognize title text+ Task 2.2: Recognize body text+ Task 3: Generate image description+ """+ root_task = Task(+ content="Analyze image",+ id="0",+ image_list=[temp_image],+ image_detail="high",+ )+ sub_task_1 = Task(content="Detect objects in image", id="1")+ sub_task_2 = Task(content="Recognize text in image", id="2")+ sub_task_3 = Task(content="Generate image description", id="3")+ sub_task_2_1 = Task(content="Recognize title text", id="2.1")+ sub_task_2_2 = Task(content="Recognize body text", id="2.2")++ root_task.add_subtask(sub_task_1)+ root_task.add_subtask(sub_task_2)+ root_task.add_subtask(sub_task_3)+ sub_task_2.add_subtask(sub_task_2_1)+ sub_task_2.add_subtask(sub_task_2_2)++ print("\n===\n" + root_task.to_string() + "\n===\n")++ manager = TaskManager(root_task)+ new_tasks = [+ sub_task_1,+ sub_task_2,+ sub_task_2_1,+ sub_task_2_2,+ sub_task_3,+ ]++ sorted_tasks = manager.topological_sort(new_tasks)+ sorted_tasks_ids = [task.id for task in sorted_tasks]+ print(sorted_tasks_ids)+ assert sorted_tasks_ids == ["1", "2.1", "2.2", "2", "3"]++ manager.add_tasks(new_tasks)+ print([task.id for task in manager.tasks])+ assert [task.id for task in manager.tasks] == [+ "1",+ "2.1",+ "2.2",+ "2",+ "3",+ "0",+ ]+++def test_video_task_management(temp_video_bytes):+ """+ Task 0: Analyze video+ Task 1: Detect people in video+ Task 2: Recognize speech in video+ Task 2.1: Recognize opening dialogue+ Task 2.2: Recognize ending dialogue+ Task 3: Generate video summary+ """+ root_task = Task(+ content="Analyze video",+ id="0",+ video_bytes=temp_video_bytes,+ video_detail="high",+ )+ sub_task_1 = Task(content="Detect people in video", id="1")+ sub_task_2 = Task(content="Recognize speech in video", id="2")+ sub_task_3 = Task(content="Generate video summary", id="3")+ sub_task_2_1 = Task(content="Recognize opening dialogue", id="2.1")+ sub_task_2_2 = Task(content="Recognize ending dialogue", id="2.2")++ root_task.add_subtask(sub_task_1)+ root_task.add_subtask(sub_task_2)+ root_task.add_subtask(sub_task_3)+ sub_task_2.add_subtask(sub_task_2_1)+ sub_task_2.add_subtask(sub_task_2_2)++ print("\n===\n" + root_task.to_string() + "\n===\n")++ manager = TaskManager(root_task)+ new_tasks = [+ sub_task_1,+ sub_task_2,+ sub_task_2_1,+ sub_task_2_2,+ sub_task_3,+ ]++ sorted_tasks = manager.topological_sort(new_tasks)+ sorted_tasks_ids = [task.id for task in sorted_tasks]+ print(sorted_tasks_ids)+ assert sorted_tasks_ids == ["1", "2.1", "2.2", "2", "3"]++ manager.add_tasks(new_tasks)+ print([task.id for task in manager.tasks])+ assert [task.id for task in manager.tasks] == [+ "1",+ "2.1",+ "2.2",+ "2",+ "3",+ "0",+ ]