🐫 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: add openai image generation model (#2472)
JINO ROHITf8ef43a77225
diff --git a/camel/toolkits/__init__.py b/camel/toolkits/__init__.pyindex f4f797123..0ea860286 100644--- a/camel/toolkits/__init__.py+++ b/camel/toolkits/__init__.py@@ -23,7 +23,7 @@ from .open_api_specs.security_config import openapi_security_configfrom .math_toolkit import MathToolkitfrom .search_toolkit import SearchToolkitfrom .weather_toolkit import WeatherToolkit-from .dalle_toolkit import DalleToolkit+from .openai_image_toolkit import OpenAIImageToolkitfrom .ask_news_toolkit import AskNewsToolkit, AsyncAskNewsToolkitfrom .linkedin_toolkit import LinkedInToolkitfrom .reddit_toolkit import RedditToolkit@@ -145,6 +145,7 @@ __all__ = ['PlaywrightMCPToolkit','WolframAlphaToolkit','BohriumToolkit',+ 'OpenAIImageToolkit','TaskPlanningToolkit','HybridBrowserToolkit','EdgeOnePagesMCPToolkit',diff --git a/camel/toolkits/dalle_toolkit.py b/camel/toolkits/dalle_toolkit.pydeleted file mode 100644index b8352fbf0..000000000--- a/camel/toolkits/dalle_toolkit.py+++ /dev/null@@ -1,175 +0,0 @@-# ========= 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. =========--# Enables postponed evaluation of annotations (for string-based type hints)-from __future__ import annotations--import base64-import os-import uuid-from io import BytesIO-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):- r"""A class representing a toolkit for image generation using OpenAI's- DALL-E model.- """-- def __init__(- self,- timeout: Optional[float] = None,- ):- r"""Initializes a new instance of the DalleToolkit class.-- Args:- timeout (Optional[float]): The timeout value for API requests- in seconds. If None, no timeout is applied.- (default: :obj:`None`)- """- super().__init__(timeout=timeout)-- def base64_to_image(self, base64_string: str) -> Optional[Image.Image]:- r"""Converts a base64 encoded string into a PIL Image object.-- Args:- base64_string (str): The base64 encoded string of the image.-- Returns:- Optional[Image.Image]: The PIL Image object or None if conversion- fails.- """- try:- # Decode the base64 string to get the image data- image_data = base64.b64decode(base64_string)- # Create a memory buffer for the image data- image_buffer = BytesIO(image_data)- # Open the image using the PIL library- image = Image.open(image_buffer)- return image- except Exception as 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:- r"""Converts the file path of an image to a Base64 encoded string.-- Args:- image_path (str): The path to the image file.-- Returns:- str: A Base64 encoded string representing the content of the image- file.- """- try:- with open(image_path, "rb") as image_file:- return base64.b64encode(image_file.read()).decode('utf-8')- except Exception as e:- error_msg = (- f"An error occurred while converting image path to base64: {e}"- )- 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.-- This function takes an image object as input, encodes the image into a- PNG format base64 string, and returns it.- If the encoding process encounters an error, it prints the error- message and returns None.-- Args:- image: The image object to be encoded, supports any image format- that can be saved in PNG format.-- Returns:- str: A base64-encoded string of the image.- """- try:- with BytesIO() as buffered_image:- image.save(buffered_image, format="PNG")- buffered_image.seek(0)- image_bytes = buffered_image.read()- base64_str = base64.b64encode(image_bytes).decode('utf-8')- return base64_str- except Exception as e:- 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.- The generated image is saved to the specified directory.-- Args:- prompt (str): The text prompt based on which the image is- generated.- image_dir (str): The directory to save the generated image.- Defaults to 'img'.-- Returns:- str: The path to the saved image.- """-- dalle_client = OpenAI()- response = dalle_client.images.generate(- model="dall-e-3",- prompt=prompt,- size="1024x1792",- quality="standard",- 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:- 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")- image.save(image_path)-- return image_path-- def get_tools(self) -> List[FunctionTool]:- r"""Returns a list of FunctionTool objects representing the- functions in the toolkit.-- Returns:- List[FunctionTool]: A list of FunctionTool objects- representing the functions in the toolkit.- """- return [FunctionTool(self.get_dalle_img)]diff --git a/camel/toolkits/openai_image_toolkit.py b/camel/toolkits/openai_image_toolkit.pynew file mode 100644index 000000000..91b058151--- /dev/null+++ b/camel/toolkits/openai_image_toolkit.py@@ -0,0 +1,268 @@+# ========= 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 base64+import os+import uuid+from io import BytesIO+from typing import List, Literal, 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, api_keys_required++logger = get_logger(__name__)+++@MCPServer()+class OpenAIImageToolkit(BaseToolkit):+ r"""A class toolkit for image generation using OpenAI's+ Image Generation API.+ """++ @api_keys_required(+ [+ ("api_key", "OPENAI_API_KEY"),+ ]+ )+ def __init__(+ self,+ model: Optional[+ Literal["gpt-image-1", "dall-e-3", "dall-e-2"]+ ] = "gpt-image-1",+ timeout: Optional[float] = None,+ api_key: Optional[str] = None,+ url: Optional[str] = None,+ size: Optional[+ Literal[+ "256x256",+ "512x512",+ "1024x1024",+ "1536x1024",+ "1024x1536",+ "1792x1024",+ "1024x1792",+ "auto",+ ]+ ] = "1024x1024",+ quality: Optional[+ Literal["auto", "low", "medium", "high", "standard", "hd"]+ ] = "standard",+ response_format: Optional[Literal["url", "b64_json"]] = "b64_json",+ n: Optional[int] = 1,+ background: Optional[+ Literal["transparent", "opaque", "auto"]+ ] = "auto",+ style: Optional[Literal["vivid", "natural"]] = None,+ image_save_path: Optional[str] = "image_save",+ ):+ r"""Initializes a new instance of the OpenAIImageToolkit class.++ Args:+ api_key (Optional[str]): The API key for authenticating+ with the OpenAI service. (default: :obj:`None`)+ url (Optional[str]): The url to the OpenAI service.+ (default: :obj:`None`)+ model (Optional[str]): The model to use.+ (default: :obj:`"dall-e-3"`)+ timeout (Optional[float]): The timeout value for API requests+ in seconds. If None, no timeout is applied.+ (default: :obj:`None`)+ size (Optional[Literal["256x256", "512x512", "1024x1024",+ "1536x1024", "1024x1536", "1792x1024", "1024x1792",+ "auto"]]):+ The size of the image to generate.+ (default: :obj:`"1024x1024"`)+ quality (Optional[Literal["auto", "low", "medium", "high",+ "standard", "hd"]]):The quality of the image to+ generate. Different models support different values.+ (default: :obj:`"standard"`)+ response_format (Optional[Literal["url", "b64_json"]]):+ The format of the response.(default: :obj:`"b64_json"`)+ n (Optional[int]): The number of images to generate.+ (default: :obj:`1`)+ background (Optional[Literal["transparent", "opaque", "auto"]]):+ The background of the image.(default: :obj:`"auto"`)+ style (Optional[Literal["vivid", "natural"]]): The style of the+ image.(default: :obj:`None`)+ image_save_path (Optional[str]): The path to save the generated+ image.(default: :obj:`"image_save"`)+ """+ super().__init__(timeout=timeout)+ api_key = api_key or os.environ.get("OPENAI_API_KEY")+ url = url or os.environ.get("OPENAI_API_BASE_URL")+ self.client = OpenAI(api_key=api_key, base_url=url)+ self.model = model+ self.size = size+ self.quality = quality+ self.response_format = response_format+ self.n = n+ self.background = background+ self.style = style+ self.image_save_path: str = image_save_path or "image_save"++ def base64_to_image(self, base64_string: str) -> Optional[Image.Image]:+ r"""Converts a base64 encoded string into a PIL Image object.++ Args:+ base64_string (str): The base64 encoded string of the image.++ Returns:+ Optional[Image.Image]: The PIL Image object or None if conversion+ fails.+ """+ try:+ # decode the base64 string to get the image data+ image_data = base64.b64decode(base64_string)+ # create a memory buffer for the image data+ image_buffer = BytesIO(image_data)+ # open the image with PIL+ image = Image.open(image_buffer)+ return image+ except Exception as e:+ logger.error(+ f"An error occurred while converting base64 to image: {e}"+ )+ return None++ def _build_base_params(self, prompt: str) -> dict:+ r"""Build base parameters dict for OpenAI API calls.++ Args:+ prompt (str): The text prompt for the image operation.++ Returns:+ dict: Parameters dictionary with non-None values.+ """+ params = {"prompt": prompt, "model": self.model}++ # basic parameters supported by all models+ if self.n is not None:+ params["n"] = self.n+ if self.size is not None:+ params["size"] = self.size++ # Model-specific parameter filtering based on model+ if self.model == "dall-e-2":+ # dall-e-2 supports: prompt, model, n, size, response_format+ if self.response_format is not None:+ params["response_format"] = self.response_format++ elif self.model == "dall-e-3":+ # dall-e-3 supports: prompt, model, n,+ # size, quality, response_format, style+ if self.quality is not None:+ params["quality"] = self.quality+ if self.response_format is not None:+ params["response_format"] = self.response_format+ if self.style is not None:+ params["style"] = self.style++ elif self.model == "gpt-image-1":+ # gpt-image-1 supports: prompt, model, n, size, quality, background+ # Note: gpt-image-1 seems to default to b64_json response format+ if self.quality is not None:+ params["quality"] = self.quality+ if self.background is not None:+ params["background"] = self.background++ return params++ def _handle_api_response(+ self, response, image_name: str, operation: str+ ) -> str:+ r"""Handle API response from OpenAI image operations.++ Args:+ response: The response object from OpenAI API.+ image_name (str): Name for the saved image file.+ operation (str): Operation type for success message ("generated").++ Returns:+ str: Success message with image path/URL or error message.+ """+ if response.data is None or len(response.data) == 0:+ error_msg = "No image data returned from OpenAI API."+ logger.error(error_msg)+ return error_msg++ # check if response has URL or base64 data+ if hasattr(response.data[0], 'url') and response.data[0].url:+ image_url = response.data[0].url+ return f"Image {operation} successfully. Image URL: {image_url}"+ elif (+ hasattr(response.data[0], 'b64_json') and response.data[0].b64_json+ ):+ image_b64 = response.data[0].b64_json++ # Save the image from base64+ image_bytes = base64.b64decode(image_b64)+ os.makedirs(self.image_save_path, exist_ok=True)+ image_path = os.path.join(+ self.image_save_path,+ f"{image_name}_{uuid.uuid4().hex}.png",+ )++ with open(image_path, "wb") as f:+ f.write(image_bytes)++ return f"Image generated and saved to {image_path}"+ else:+ error_msg = "No valid image data (URL or base64) found in response"+ logger.error(error_msg)+ return error_msg++ def generate_image(+ self,+ prompt: str,+ image_name: str = "image",+ ) -> str:+ r"""Generate an image using OpenAI's Image Generation models.+ The generated image will be saved locally (for ``b64_json`` response+ formats) or an image URL will be returned (for ``url`` response+ formats).++ Args:+ prompt (str): The text prompt to generate the image.+ image_name (str): The name of the image to save.+ (default: :obj:`"image"`)++ Returns:+ str: the content of the model response or format of the response.+ """+ try:+ params = self._build_base_params(prompt)+ response = self.client.images.generate(**params)+ return self._handle_api_response(response, image_name, "generated")+ except Exception as e:+ error_msg = f"An error occurred while generating image: {e}"+ logger.error(error_msg)+ return error_msg++ def get_tools(self) -> List[FunctionTool]:+ r"""Returns a list of FunctionTool objects representing the+ functions in the toolkit.++ Returns:+ List[FunctionTool]: A list of FunctionTool objects+ representing the functions in the toolkit.+ """+ return [+ FunctionTool(self.generate_image),+ # could add edit_image function later+ ]diff --git a/examples/toolkits/openai_image_example.py b/examples/toolkits/openai_image_example.pynew file mode 100644index 000000000..5b6c4c1d3--- /dev/null+++ b/examples/toolkits/openai_image_example.py@@ -0,0 +1,51 @@+# ========= 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. =========+from camel.agents import ChatAgent+from camel.models import ModelFactory+from camel.toolkits import OpenAIImageToolkit+from camel.types import ModelPlatformType, ModelType++# Define system message+sys_msg = "You are a helpful assistant that can generate images."++# Create OpenAI Image Toolkit with DALL-E 3 model and base64 response format+tools = [+ *OpenAIImageToolkit(+ model="dall-e-3",+ response_format="b64_json",+ size="1024x1024",+ quality="standard",+ ).get_tools()+]++model = ModelFactory.create(+ model_platform=ModelPlatformType.DEFAULT,+ model_type=ModelType.DEFAULT,+)++# Set agent+camel_agent = ChatAgent(+ system_message=sys_msg,+ model=model,+ tools=tools,+)++# Define a user message+usr_msg = "Generate an image of a camel working out in a gym."++# Get response information+response = camel_agent.step(usr_msg)++print(f"Tool calls made: {len(response.info['tool_calls'])}")+print(f"\nAgent response: {response.msg}")diff --git a/pyproject.toml b/pyproject.tomlindex 8d1960225..5ba8ae95b 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -21,7 +21,6 @@ keywords = ["large-language-models",]dependencies = [- "openai>=1.68.0,<2","mcp>=1.3.0","tiktoken>=0.7.0,<0.8","colorama>=0.4.6,<0.5",@@ -31,6 +30,7 @@ dependencies = ["httpx>=0.28.0,<1.0.0dev","psutil>=5.9.8,<6","pillow>=10.1.0,<11.0.0",+ "openai>=1.86.0,<2",]diff --git a/test/toolkits/test_dalle_functions.py b/test/toolkits/test_dalle_functions.pydeleted file mode 100644index 729d3d17e..000000000--- a/test/toolkits/test_dalle_functions.py+++ /dev/null@@ -1,97 +0,0 @@-# ========= 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 base64-import os--import pytest-from PIL import Image--from camel.toolkits import DalleToolkit---def dalle_toolkit():- return DalleToolkit()---def test_image_path():- # Prepare the path for the test image- test_image_path = 'test_image.png'- # Create a test image file (or ensure it exists for the test)- with open(test_image_path, 'wb') as f:- f.write(b'This is a test image placeholder content.')-- # Provide the path to the temp file for the test to use- yield test_image_path-- # Teardown: Clean up the temporary file- try:- os.remove(test_image_path)- except OSError as e:- print(f"Error: {e.strerror}")---def test_base64_to_image_valid(dalle_toolkit):- valid_base64_string = "iVBORw0KGgoAAAANSUhEUgAAAAUA\- AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO\- 9TXL0Y4OHwAAAABJRU5ErkJggg=="- if valid_base64_string.startswith('data:image/png;base64,'):- valid_base64_string = valid_base64_string[22:]-- image = dalle_toolkit.base64_to_image(valid_base64_string)-- assert isinstance(- image, Image.Image- ), "The function should return a PIL Image object"---def test_base64_to_image_invalid(dalle_toolkit):- invalid_base64_string = "invalid_base64_string"-- image = dalle_toolkit.base64_to_image(invalid_base64_string)-- # Check response is None- assert (- image is None- ), "The function should return None for an invalid base64 string"---def test_image_path_to_base64(test_image_path, dalle_toolkit):- # Obtain the Base64 encoded string of the test image- base64_encoded_string = dalle_toolkit.image_path_to_base64(test_image_path)- # Decode the Base64 string back to binary data for validation- decoded_binary_data = base64.b64decode(base64_encoded_string)- # Verify if the decoded data matches the original binary content of- # the test image- with open(test_image_path, 'rb') as f:- original_binary_data = f.read()-- assert (- decoded_binary_data == original_binary_data- ), "The Base64 encoded string does not match the original image content."---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 an error message when an error occurs- # during encoding- result = dalle_toolkit.image_to_base64(invalid_input)-- # 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 resultdiff --git a/test/toolkits/test_openai_image.py b/test/toolkits/test_openai_image.pynew file mode 100644index 000000000..3629c32d6--- /dev/null+++ b/test/toolkits/test_openai_image.py@@ -0,0 +1,60 @@+# ========= 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 pytest+from PIL import Image++from camel.toolkits import OpenAIImageToolkit+++def image_toolkit():+ return OpenAIImageToolkit()+++def test_base64_to_image_valid(image_toolkit):+ valid_base64_string = "iVBORw0KGgoAAAANSUhEUgAAAAUA\+ AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO\+ 9TXL0Y4OHwAAAABJRU5ErkJggg=="+ if valid_base64_string.startswith('data:image/png;base64,'):+ valid_base64_string = valid_base64_string[22:]++ image = image_toolkit.base64_to_image(valid_base64_string)++ # test base64 converts to image+ assert isinstance(+ image, Image.Image+ ), "The function should return a PIL Image object"+++def test_base64_to_image_invalid(image_toolkit):+ invalid_base64_string = "invalid_base64_string"++ image = image_toolkit.base64_to_image(invalid_base64_string)++ # check response is None+ assert (+ image is None+ ), "The function should return None for an invalid base64 string"+++def test_toolkit_initialization_and_tools(image_toolkit):+ # test that toolkit initializes properly+ assert image_toolkit is not None++ # test that only generate_image tool is available+ tools = image_toolkit.get_tools()+ assert len(tools) == 1, "Should only have one tool available"+ assert (+ tools[0].func.__name__ == "generate_image"+ ), "Tool should be generate_image"diff --git a/uv.lock b/uv.lockindex 032daecc1..6585baa0c 100644--- a/uv.lock+++ b/uv.lock@@ -1158,7 +1158,7 @@ requires-dist = [{ name = "numpy", marker = "extra == 'document-tools'", specifier = ">=1.2,<=2.2" },{ name = "numpy", marker = "extra == 'owl'", specifier = ">=1.2,<=2.2" },{ name = "numpy", marker = "extra == 'rag'", specifier = ">=1.2,<=2.2" },- { name = "openai", specifier = ">=1.68.0,<2" },+ { name = "openai", specifier = ">=1.86.0,<2" },{ name = "openapi-spec-validator", marker = "extra == 'all'", specifier = ">=0.7.1,<0.8" },{ name = "openapi-spec-validator", marker = "extra == 'document-tools'", specifier = ">=0.7.1,<0.8" },{ name = "openapi-spec-validator", marker = "extra == 'owl'", specifier = ">=0.7.1,<0.8" },