🐫 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 response api (#1824)
Rishabh88270e3f3803
diff --git a/camel/toolkits/__init__.py b/camel/toolkits/__init__.pyindex d29626f3f..e802e6825 100644--- a/camel/toolkits/__init__.py+++ b/camel/toolkits/__init__.py@@ -61,6 +61,7 @@ from .file_write_toolkit import FileWriteToolkitfrom .terminal_toolkit import TerminalToolkitfrom .pubmed_toolkit import PubMedToolkitfrom .thinking_toolkit import ThinkingToolkit+from .openai_agent_toolkit import OpenAIAgentToolkitfrom .searxng_toolkit import SearxNGToolkit@@ -112,5 +113,6 @@ __all__ = ['TerminalToolkit','PubMedToolkit','ThinkingToolkit',+ 'OpenAIAgentToolkit','SearxNGToolkit',]diff --git a/camel/toolkits/openai_agent_toolkit.py b/camel/toolkits/openai_agent_toolkit.pynew file mode 100644index 000000000..382e498d2--- /dev/null+++ b/camel/toolkits/openai_agent_toolkit.py@@ -0,0 +1,131 @@+# ========= 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 os+from typing import List, Optional++from openai import OpenAI++from camel.logger import get_logger+from camel.models import BaseModelBackend, ModelFactory+from camel.toolkits.base import BaseToolkit+from camel.toolkits.function_tool import FunctionTool+from camel.types import ModelPlatformType, ModelType+from camel.utils import api_keys_required++logger = get_logger(__name__)+++class OpenAIAgentToolkit(BaseToolkit):+ r"""Toolkit for accessing OpenAI's agent tools including web search and+ file search.++ Provides access to OpenAI's web search and file search capabilities+ through the Responses API, allowing agents to retrieve information from+ the web and search through uploaded files.+ """++ @api_keys_required(+ [+ (None, "OPENAI_API_KEY"),+ ]+ )+ def __init__(+ self,+ model: Optional[BaseModelBackend] = None,+ api_key: Optional[str] = None,+ ) -> None:+ r"""Initialize the OpenAI agent toolkit.++ Args:+ model (BaseModelBackend): The OpenAI model to use for responses.+ If None, defaults to gpt-4o-mini. (default: :obj:`None`)+ api_key (str): OpenAI API key. If not provided, will attempt to+ use OPENAI_API_KEY environment variable. (default: :obj:`None`)+ """+ super().__init__()+ self.api_key = api_key or os.getenv("OPENAI_API_KEY")+ self.client = OpenAI(api_key=self.api_key)+ self.model = model or ModelFactory.create(+ model_platform=ModelPlatformType.OPENAI,+ model_type=ModelType.GPT_4O_MINI,+ )++ def web_search(self, query: str) -> str:+ r"""Perform a web search using OpenAI's web search tool.++ Args:+ query (str): The search query.++ Returns:+ str: The search result or error message.+ """+ try:+ response = self.client.responses.create(+ model=str(self.model.model_type),+ tools=[{"type": "web_search_preview"}],+ input=query,+ )+ return response.output_text++ except Exception as e:+ logger.error(f"Web search failed: {e!s}")+ return f"Web search failed: {e!s}"++ def file_search(+ self,+ query: str,+ vector_store_id: str,+ ) -> str:+ r"""Search through files using OpenAI's file search tool.++ Args:+ query (str): The search query.+ vector_store_id (str): The vector store ID to search in.++ Returns:+ str: The search result or error message.+ """+ if not vector_store_id.strip():+ logger.error("Empty vector store ID provided.")+ return "Empty vector store ID provided, it cannot be empty."++ try:+ response = self.client.responses.create(+ model=str(self.model.model_type),+ tools=[+ {+ "type": "file_search",+ "vector_store_ids": [vector_store_id],+ }+ ],+ input=query,+ )+ return response.output_text++ except Exception as e:+ logger.error(f"File search failed: {e!s}")+ return f"File search failed: {e!s}"++ def get_tools(self) -> List[FunctionTool]:+ r"""Retrieve available toolkit functions as FunctionTool objects.++ Returns:+ List[FunctionTool]: Collection of FunctionTool objects representing+ the available search functions in this toolkit.+ """+ return [+ FunctionTool(self.web_search),+ FunctionTool(self.file_search),+ ]diff --git a/examples/toolkits/openai_agent_toolkit_example.py b/examples/toolkits/openai_agent_toolkit_example.pynew file mode 100644index 000000000..d50ab44dc--- /dev/null+++ b/examples/toolkits/openai_agent_toolkit_example.py@@ -0,0 +1,275 @@+# ========= 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 os++from camel.agents import ChatAgent+from camel.configs import ChatGPTConfig+from camel.models import ModelFactory+from camel.toolkits import OpenAIAgentToolkit+from camel.types import ModelPlatformType, ModelType++# Define system message+sys_msg = """You are a helpful AI assistant that can use OpenAI's agent tools+including web search and file search."""++# Set model config+model_config_dict = ChatGPTConfig(+ temperature=0.0,+).as_dict()++model = ModelFactory.create(+ model_platform=ModelPlatformType.OPENAI,+ model_type=ModelType.GPT_4O_MINI,+ model_config_dict=model_config_dict,+)++# Initialize toolkit and get tools+toolkit = OpenAIAgentToolkit(model=model)+tools = toolkit.get_tools()++# Set agent+agent = ChatAgent(+ system_message=sys_msg,+ model=model,+ tools=tools,+)++# Example 1: Web Search+print("\n=== Using Web Search with Agent ===")+response = agent.step(+ "What was a positive news story from today? Use web search to find out."+)+print("Web Search Response:", response.msg.content)++# Example 2: Direct Web Search+print("\n=== Direct Web Search Usage ===")+web_result = toolkit.web_search(+ "What are the latest developments in renewable energy?"+)+print("Direct Web Search Result:", web_result)++# Example 3: File Search (if configured)+vector_store_id = os.getenv("OPENAI_VECTOR_STORE_ID")++if vector_store_id:+ print("\n=== Using File Search with Agent ===")+ response = agent.step(+ f"Search through my documents for information about climate change. "+ f"Use file search with vector store ID: {vector_store_id}"+ )+ print("File Search Response:", response.msg.content)++ print("\n=== Direct File Search Usage ===")+ file_result = toolkit.file_search(+ query="What are the key points about climate change?",+ vector_store_id=vector_store_id,+ )+ print("Direct File Search Result:", file_result)+else:+ print("\n=== File Search Examples Skipped ===")+ print("Set OPENAI_VECTOR_STORE_ID env var to run file search examples")+++"""+=== Using Web Search with Agent ===+Web Search Response: Here are some uplifting news stories from today:++1. **Historic Marriage Milestone**: A Brazilian couple has set a new Guinness+World Record for the longest marriage of a living couple, celebrating 84+years and 85 days together.++2. **Lottery Jackpot Win**: A Michigan man who consistently played the same+lottery numbers for four years has won a $1.3 million jackpot in the state's+Lotto 47 game.++3. **Miraculous Recovery**: A 23-year-old British woman, initially given only+a 5% chance of survival after a life-threatening skiing accident, shared her+inspiring story of recovery.++4. **Marathon for a Cause**: A Wisconsin doctor, who previously battled+testicular cancer, ran seven marathons on seven continents—from+Antarctica to North America—to raise awareness for the disease.++5. **Kindness in the Skies**: An airline passenger shared a story about+a fellow flyer who offered $100 to switch their window seat for an aisle+seat, highlighting unexpected acts of kindness.++6. **Community Support**: A North Carolina mother is honoring the victims of+an American Airlines flight that collided with an Army helicopter by+supporting the skating community, demonstrating resilience and unity.++7. **Positive Outlook During Pandemic**: A study from Oregon State University+confirms that individuals with positive and playful attitudes navigated the+COVID-19 pandemic more effectively, underscoring the power of optimism.++8. **Random Act of Kindness**: An emergency room doctor and father of three in+Fort Worth, Texas, was touched when a stranger left a heartfelt note and paid+his family's breakfast bill at a local café.++9. **Mountain Rescue**: Two experienced hikers were rescued from the tallest+mountain in the Northeast after a whiteout snowstorm stranded them at about+5,000 feet, showcasing the dedication of rescue teams.++10. **Pilot's Reassurance**: An American Airlines pilot went viral after+assuring passengers that he has "no higher calling" than "carefully"+transporting them to their destination, following a recent tragic+crash in D.C.++These stories highlight the resilience, kindness, and positive spirit+present in our communities.++=== Direct Web Search Usage ===+Direct Web Search Result: Recent developments in renewable energy have marked+significant progress across various sectors:++**Record Growth in Renewable Energy Capacity**++In 2023, the global renewable energy sector experienced unprecedented growth,+adding 473 gigawatts (GW) new capacity—a 54% increase from the previous year.+This surge was predominantly driven by solar photovoltaic and onshore wind+installations, which together accounted for over 95% of the new capacity.+Notably, solar PV alone contributed 346 GW, reflecting a 73% year-on-year+increase. China played a pivotal role in this expansion, leading in solar PV,+onshore wind, offshore wind, and hydropower installations. This dominance has+contributed to a decline in the global weighted average cost of electricity+(LCOE) for these technologies, making renewable power generation increasingly+competitive. ([greenearth.news](https://greenearth.news/record-growth-in-+renewable-energy-473-gw-added-in-2023-marks-a-turning-point-in-global-power-+transition-report/?utm_source=openai))++**Advancements in Energy Storage Technologies**++The integration of renewable energy sources has been bolstered by significant+advancements in energy storage solutions. In 2023, battery storage capacity+expanded dramatically, with 95.9 GWh added, up from just 0.1 GWh in 2010. This+growth has been accompanied by substantial reduction in costs, with price of+battery storage projects decreasing by 89% between 2010 and 2023. These+developments enhance reliability and scalability of renewable energy systems,+addressing the intermittent nature of sources like wind and solar.+([greenearth.news](https://greenearth.news/record-growth-in-renewable-energy-+473-gw-added-in-2023-marks-a-turning-point-in-global-power-transition-report/?+utm_source=openai))++**Innovations in Renewable Energy Technologies**++The renewable energy sector has witnessed several technological breakthroughs:++- **Solar Power**: The introduction of high-efficiency solar panels utilizing+materials such as perovskite and gallium arsenide has significantly increased+energy conversion rates. Additionally, building-integrated photovoltaics+are enabling the seamless integration of solar technology into architectural+designs, transforming buildings into self-sustaining power generators.+([toxigon.com](https://toxigon.com/renewable-energy-technologies-2023?+utm_source=openai))++- **Wind Energy**: Advancements in wind turbine technology, including the+deployment of larger and more efficient turbines, have enhanced energy capture+Offshore wind farms, particularly those utilizing floating wind turbines, are+expanding the potential for wind power generation in deeper waters previously+inaccessible to traditional fixed-bottom turbines. ([toxigon.com]+(https://toxigon.com/renewable-energy-technologies-2023?utm_source=openai))++- **Energy Storage**: Innovations in battery technology, such as development+of advanced lithium-ion, solid-state batteries, have improved energy density,+charging times, and safety features. These advancements facilitate the+integration of renewable energy into the power grid and support transition to+a low-carbon economy. ([toxigon.com](https://toxigon.com/renewable-energy-+technologies-2023?utm_source=openai))++**Global Investment and Policy Support**++The clean energy transition is gaining momentum, with substantial investments+and policy support driving the shift towards renewable energy:++- The International Energy Agency (IEA) projects that $2 trillion will be+allocated to clean energy in 2024, with 85% of new power plants being+renewable.+([time.com](https://time.com/7022326/climate-leadership-forum-green-economy-+clean-energy-transition/?utm_source=openai))++- China's dominance in green technology manufacturing, including turbines,+solar panels, electric vehicles, and lithium-ion batteries, positions it as a+leader in the global renewable energy market. This leadership is expected to+continue, with China projected to install 60% of world's renewable capacity+between now and 2030. ([ft.com](https://www.ft.com/content/d3650b44-0313-44c9-+a7aa-495549b158b5?utm_source=openai))++These developments underscore the rapid advancements in renewable energy,+driven by technological innovation, substantial investments, and supportive+policies, collectively contributing to a more sustainable and resilient+global energy landscape.+++## Recent Developments in Renewable Energy:+- [Record renewables growth fuels cost competitiveness -IRENA report shows]+(https://www.reuters.com/business/energy/record-renewables-growth-fuels-cost-+competitiveness-irena-report-shows-2024-09-24/?utm_source=openai)+- [Cheap Solar Panels Are Changing the World](https://www.theatlantic.com/science/+archive/2024/10/solar-power-energy-revolution-global-south/680351/?+utm_source=openai)+- [China is winning the race for green supremacy](https://www.ft.com/content/+d3650b44-0313-44c9-a7aa-495549b158b5?utm_source=openai)++=== Using File Search with Agent ===+File Search Response: It appears that there are no mentions of "climate+change" in the documents you've uploaded. If you need info or insights on+that topic, please let me know how I can assist you further!++=== Direct File Search Usage ===+Direct File Search Result: It looks like there were no relevant results in the+uploaded files regarding climate change. However, I can provide summary of key+points about climate change:++1. **Definition**: Climate change refers to significant changes in global+temperatures and weather patterns over time.++2. **Causes**:+- **Greenhouse Gas Emissions**: Increased levels of carbon dioxide (CO2),+methane (CH4), and nitrous oxide (N2O) from human activities (e.g., burning+fossil fuels, deforestation).+- **Natural Factors**: Volcanic eruptions, solar radiation variations, and+natural greenhouse gas emissions.++3. **Impacts**:+- **Temperature Increases**: Global average temperatures have risen, leading+to heatwaves and extreme weather.+- **Sea Level Rise**: Melting ice caps and glaciers contribute to rising sea+levels, which can lead to coastal flooding.+- **Ecosystem Disruption**: Affects biodiversity, leading to habitat loss,+changes in species distribution, and increased extinction rates.++4. **Social and Economic Consequences**:+- **Food and Water Security**: Impact on agricultural productivity and water+availability.+- **Health Risks**: Increased prevalence of heat-related illnesses and spread+of diseases.+- **Economic Costs**: Damage to infrastructure, increased disaster recovery+costs, and shifts in market dynamics.++5. **Mitigation Strategies**:+- **Renewable Energy Sources**: Transition to solar, wind, and other renewable+energy resources.+- **Energy Efficiency**: Improving energy use in buildings, transportation,+and industry.+- **Conservation Practices**: Protecting forests, wetlands, and other+ecosystems that sequester carbon.++6. **International Agreements**: Efforts like the Paris Agreement aim to unite+countries to limit global warming to well below 2 degrees Celsius above pre-+industrial levels.++If you need more specific information or details from the files,+feel free to ask!+"""diff --git a/pyproject.toml b/pyproject.tomlindex c63f6bb01..1ec3b349d 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -22,7 +22,7 @@ keywords = []dependencies = ["numpy~=1.26",- "openai>=1.59.7,<2",+ "openai>=1.68.0,<2","tiktoken>=0.7.0,<0.8","colorama>=0.4.6,<0.5","jsonschema>=4,<5",diff --git a/test/toolkits/test_openai_agent_toolkit.py b/test/toolkits/test_openai_agent_toolkit.pynew file mode 100644index 000000000..a65a5e096--- /dev/null+++ b/test/toolkits/test_openai_agent_toolkit.py@@ -0,0 +1,256 @@+# ========= 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 os+from unittest.mock import MagicMock, patch++import pytest++from camel.models import BaseModelBackend+from camel.toolkits.openai_agent_toolkit import OpenAIAgentToolkit+from camel.types import ModelPlatformType, ModelType+++class TestOpenAIAgentToolkitInitialization:+ r"""Test cases for OpenAIAgentToolkit initialization."""++ @patch.dict(os.environ, {"OPENAI_API_KEY": "test_api_key"})+ def test_init_with_env_api_key(self):+ r"""Test initialization with API key from environment variable."""+ toolkit = OpenAIAgentToolkit()+ assert toolkit.api_key == "test_api_key"+ assert toolkit.client.api_key == "test_api_key"++ def test_init_with_provided_api_key(self):+ r"""Test initialization with explicitly provided API key."""+ toolkit = OpenAIAgentToolkit(api_key="provided_api_key")+ assert toolkit.api_key == "provided_api_key"+ assert toolkit.client.api_key == "provided_api_key"++ @patch.dict(os.environ, {"OPENAI_API_KEY": "test_api_key"})+ def test_init_with_default_model(self):+ r"""Test initialization with default model."""+ toolkit = OpenAIAgentToolkit()+ assert toolkit.model is not None+ assert toolkit.model.model_type == ModelType.GPT_4O_MINI++ def test_init_with_custom_model(self):+ r"""Test initialization with custom model."""+ mock_model = MagicMock(spec=BaseModelBackend)+ mock_model.model_type = ModelType.GPT_4+ mock_model.model_platform = ModelPlatformType.OPENAI++ toolkit = OpenAIAgentToolkit(model=mock_model, api_key="test_api_key")+ assert toolkit.model == mock_model+++class TestOpenAIAgentToolkitWebSearch:+ r"""Test cases for OpenAIAgentToolkit web search functionality."""++ @pytest.fixture+ def toolkit_fixture(self):+ r"""Fixture to create a toolkit instance with mocked dependencies."""+ with patch.object(OpenAIAgentToolkit, '__init__', return_value=None):+ toolkit = OpenAIAgentToolkit()+ toolkit.api_key = "test_api_key"+ toolkit.client = MagicMock()+ toolkit.model = MagicMock()+ toolkit.model.model_type = "gpt-4o-mini"+ return toolkit++ def test_web_search_success(self, toolkit_fixture):+ r"""Test successful web search."""+ # Setup+ toolkit = toolkit_fixture+ mock_response = MagicMock()+ mock_response.output_text = "Web search results"+ toolkit.client.responses.create.return_value = mock_response++ # Execute+ result = toolkit.web_search("test query")++ # Verify+ toolkit.client.responses.create.assert_called_once_with(+ model=str(toolkit.model.model_type),+ tools=[{"type": "web_search_preview"}],+ input="test query",+ )+ assert result == "Web search results"+++class TestOpenAIAgentToolkitFileSearch:+ r"""Test cases for OpenAIAgentToolkit file search functionality."""++ @pytest.fixture+ def toolkit_fixture(self):+ r"""Fixture to create a toolkit instance with mocked dependencies."""+ with patch.object(OpenAIAgentToolkit, '__init__', return_value=None):+ toolkit = OpenAIAgentToolkit()+ toolkit.api_key = "test_api_key"+ toolkit.client = MagicMock()+ toolkit.model = MagicMock()+ toolkit.model.model_type = "gpt-4o-mini"+ return toolkit++ def test_file_search_success(self, toolkit_fixture):+ r"""Test successful file search."""+ # Setup+ toolkit = toolkit_fixture+ mock_response = MagicMock()+ mock_response.output_text = "File search results"+ toolkit.client.responses.create.return_value = mock_response++ # Execute+ result = toolkit.file_search("test query", "vector_store_id_123")++ # Verify+ toolkit.client.responses.create.assert_called_once_with(+ model=str(toolkit.model.model_type),+ tools=[+ {+ "type": "file_search",+ "vector_store_ids": ["vector_store_id_123"],+ }+ ],+ input="test query",+ )+ assert result == "File search results"++ def test_file_search_empty_vector_store_id(self, toolkit_fixture):+ r"""Test file search with empty vector store ID."""+ # Setup+ toolkit = toolkit_fixture++ # Execute+ result = toolkit.file_search("test query", " ")++ # Verify+ toolkit.client.responses.create.assert_not_called()+ assert "Empty vector store ID provided" in result++ def test_file_search_exception(self, toolkit_fixture):+ r"""Test file search with exception."""+ # Setup+ toolkit = toolkit_fixture+ toolkit.client.responses.create.side_effect = Exception("API error")++ # Execute+ result = toolkit.file_search("test query", "vector_store_id_123")++ # Verify+ assert "File search failed: API error" in result+++class TestOpenAIAgentToolkitTools:+ r"""Test cases for OpenAIAgentToolkit tools functionality."""++ @pytest.fixture+ def toolkit_fixture(self):+ r"""Fixture to create a toolkit instance with mocked dependencies."""+ with patch.object(OpenAIAgentToolkit, '__init__', return_value=None):+ toolkit = OpenAIAgentToolkit()+ # Add these attributes to the mock+ toolkit.web_search = MagicMock()+ toolkit.web_search.__name__ = "web_search"+ toolkit.file_search = MagicMock()+ toolkit.file_search.__name__ = "file_search"+ return toolkit++ def test_get_tools(self, toolkit_fixture):+ r"""Test get_tools method returns correct FunctionTool objects."""+ # Setup+ toolkit = toolkit_fixture++ # Use a more comprehensive mock for FunctionTool+ with patch(+ 'camel.toolkits.openai_agent_toolkit.FunctionTool'+ ) as mock_function_tool:+ # Create mock tools to return+ mock_web_tool = MagicMock()+ mock_file_tool = MagicMock()+ # Make the mock return different values on each call+ mock_function_tool.side_effect = [mock_web_tool, mock_file_tool]++ # Execute+ tools = toolkit.get_tools()++ # Verify+ assert len(tools) == 2+ assert mock_function_tool.call_count == 2+ # Check that the functions were passed to FunctionTool constructor+ mock_function_tool.assert_any_call(toolkit.web_search)+ mock_function_tool.assert_any_call(toolkit.file_search)+++class TestOpenAIAgentToolkitIntegration:+ r"""Integration test cases for OpenAIAgentToolkit."""++ @patch.dict(os.environ, {"OPENAI_API_KEY": "test_api_key"})+ @patch('openai.OpenAI')+ @patch('camel.models.ModelFactory.create')+ def test_toolkit_integration(self, mock_model_factory, mock_openai):+ """Test the integration of all components in the toolkit."""+ # Setup+ mock_model = MagicMock(spec=BaseModelBackend)+ # Use string for model_type to avoid recursion issues+ mock_model.model_type = "gpt-4o-mini"+ mock_model_factory.return_value = mock_model++ # Mock the client and its methods+ mock_client = MagicMock()+ mock_openai.return_value = mock_client++ mock_response = MagicMock()+ mock_response.output_text = "Search results"+ mock_client.responses.create.return_value = mock_response++ # Mock FunctionTool to avoid schema generation issues+ with patch(+ 'camel.toolkits.openai_agent_toolkit.FunctionTool'+ ) as mock_function_tool:+ mock_web_tool = MagicMock()+ mock_file_tool = MagicMock()+ mock_function_tool.side_effect = [mock_web_tool, mock_file_tool]++ # Create a properly mocked toolkit+ with patch.object(+ OpenAIAgentToolkit, '__init__', return_value=None+ ):+ toolkit = OpenAIAgentToolkit()+ # Set up the toolkit with our mocks+ toolkit.api_key = "test_api_key"+ toolkit.client = mock_client+ toolkit.model = mock_model++ toolkit.web_search = lambda query: "Search results"+ toolkit.file_search = (+ lambda query, vector_store_id: "Search results"+ )++ # Execute the get_tools method+ tools = toolkit.get_tools()++ # Verify+ assert len(tools) == 2+ assert mock_function_tool.call_count == 2++ # Test that the web_search and file_search methods work+ web_result = toolkit.web_search("web query")+ file_result = toolkit.file_search(+ "file query", "vector_store_id_123"+ )++ # Verify results+ assert web_result == "Search results"+ assert file_result == "Search results"diff --git a/uv.lock b/uv.lockindex 00a5e51b6..65a6d5a29 100644--- a/uv.lock+++ b/uv.lock@@ -910,7 +910,7 @@ requires-dist = [{ name = "notion-client", marker = "extra == 'all'", specifier = ">=2.2.1,<3" },{ name = "notion-client", marker = "extra == 'communication-tools'", specifier = ">=2.2.1,<3" },{ name = "numpy", specifier = "~=1.26" },- { name = "openai", specifier = ">=1.59.7,<2" },+ { name = "openai", specifier = ">=1.68.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 = "opencv-python", marker = "extra == 'all'", specifier = ">=4,<5" },@@ -3827,7 +3827,7 @@ wheels = [[[package]]name = "openai"-version = "1.66.3"+version = "1.68.2"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "anyio" },@@ -3839,9 +3839,9 @@ dependencies = [{ name = "tqdm" },{ name = "typing-extensions" },]-sdist = { url = "https://files.pythonhosted.org/packages/a3/77/5172104ca1df35ed2ed8fb26dbc787f721c39498fc51d666c4db07756a0c/openai-1.66.3.tar.gz", hash = "sha256:8dde3aebe2d081258d4159c4cb27bdc13b5bb3f7ea2201d9bd940b9a89faf0c9", size = 397244 }+sdist = { url = "https://files.pythonhosted.org/packages/3f/6b/6b002d5d38794645437ae3ddb42083059d556558493408d39a0fcea608bc/openai-1.68.2.tar.gz", hash = "sha256:b720f0a95a1dbe1429c0d9bb62096a0d98057bcda82516f6e8af10284bdd5b19", size = 413429 }wheels = [- { url = "https://files.pythonhosted.org/packages/78/5a/e20182f7b6171642d759c548daa0ba20a1d3ac10d2bd0a13fd75704a9ac3/openai-1.66.3-py3-none-any.whl", hash = "sha256:a427c920f727711877ab17c11b95f1230b27767ba7a01e5b66102945141ceca9", size = 567400 },+ { url = "https://files.pythonhosted.org/packages/fd/34/cebce15f64eb4a3d609a83ac3568d43005cc9a1cba9d7fde5590fd415423/openai-1.68.2-py3-none-any.whl", hash = "sha256:24484cb5c9a33b58576fdc5acf0e5f92603024a4e39d0b99793dfa1eb14c2b36", size = 606073 },][[package]]