Building AI agents, atomically
feat(tool): add TavilySearchTool tests, README.md
2dogzb387ec3877bd
diff --git a/atomic-forge/tools/tavily_search/README.md b/atomic-forge/tools/tavily_search/README.mdnew file mode 100644index 0000000..1ae9cf3--- /dev/null+++ b/atomic-forge/tools/tavily_search/README.md@@ -0,0 +1,87 @@+# Tavily Search Tool++## Overview+The Tavily Search Tool is a powerful utility within the Atomic Agents ecosystem that allows you to perform searches using Tavily, a search engine built for AI Agents. This tool enables you to fetch search results from Tavily.++## Prerequisites and Dependencies+- Python 3.9 or later+- atomic-agents (See [here](/README.md) for installation instructions)+- pydantic+- requests++## Installation+You can install the tool using any of the following options:++1. Using the CLI tool that comes with Atomic Agents. Simply run `atomic` and select the tool from the list of available tools. After doing so you will be asked for a target directory to download the tool into.+2. Good old fashioned copy/paste: Just like any other tool inside the Atomic Forge, you can copy the code from this repo directly into your own project, provided you already have atomic-agents installed according to the instructions in the main [README](/README.md).++## Configuration++### Parameters++- `api_url` (str): The api key of the Tavily user.+- `max_results` (int, optional): The maximum number of search results to return. Defaults to `10`.++### Example++```python+config = TavilySearchToolConfig(+ api_key="my-api-key",+ max_results=5+)+```++## Input & Output Structure++### Input Schema+- `queries` (List[str]): List of search queries.++### Output Schema+- `results` (List[TavilySearchResultItemSchema]): List of search result items.++Each `TavilySearchResultItemSchema` contains:+- `title` (str): The title of the search result.+- `url` (str): The URL of the search result.+- `content` (Optional[str]): The content snippet of the search result.+- `score` (float): The score of the search result.+- `raw_content` (Optional[str]): The raw content of the search result.+- `query` (str): The query used to obtain this search result.+- `answer` (Optional[str]): The answer to the query provided by Tavily.++## Usage++Here's an example of how to use the Tavily Search Tool:+++```python+import os+from tool.tavily_search import TavilyTool, TavilySearchToolConfig++# Initialize the tool with your Tavily instance URL+config = TavilySearchToolConfig(api_key=os.getenv("TAVILY_API_KEY"), max_results=5)+search_tool = TavilyTool(config=config)++# Define input data+input_data = TavilyTool.input_schema(+ queries=["Python programming", "Machine learning"],+)++# Perform the search+result = search_tool.run(input_data)+print(result)+```++## Contributing++Contributions are welcome! To contribute:++1. Fork the repository.+2. Create a new feature branch.+3. Commit your changes with clear messages.+4. Open a pull request detailing your changes.++Please ensure you follow the project's coding standards and include tests for any new features or bug fixes.++## License++This project is licensed under the same license as the main Atomic Agents project. See the [LICENSE](/LICENSE) file in the repository root for more details.diff --git a/atomic-forge/tools/tavily_search/tests/test_tavily_seach.py b/atomic-forge/tools/tavily_search/tests/test_tavily_seach.pynew file mode 100644index 0000000..c76f8f1--- /dev/null+++ b/atomic-forge/tools/tavily_search/tests/test_tavily_seach.py@@ -0,0 +1,178 @@+import os+import sys+import pytest+from unittest.mock import patch, AsyncMock, MagicMock+from aiohttp import ClientSession++sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))++from tool.tavily_search import ( # noqa: E402+ TavilySearchTool,+ TavilySearchToolInputSchema,+ TavilySearchToolConfig,+)+++def mock_aiohttp_session():+ # Patch the ClientSession in the module where it's used+ with patch("aiohttp.ClientSession") as mock_session_class:+ mock_session = MagicMock(spec=ClientSession)+ # Mock the async context manager __aenter__ to return the mock session+ mock_session_class.return_value.__aenter__ = AsyncMock(return_value=mock_session)+ yield mock_session+++async def test_searxng_search_tool_missing_fields(mock_aiohttp_session):+ mock_api_key = "KEY"+ mock_query = "query with missing fields"+ mock_response_data = {+ "results": [+ {"title": "Result Missing Content", "url": "https://example.com/1", "query": mock_query},+ {"content": "Result Missing Title", "url": "https://example.com/2", "query": mock_query},+ {"title": "Result Missing URL", "content": "Some content", "query": mock_query},+ {"title": "Result Missing Query", "url": "https://example.com/4", "content": "Some content"},+ {"title": "Valid Result", "url": "https://example.com/5", "content": "Valid content", "query": mock_query},+ ]+ }++ # Create a mock response object+ mock_response = AsyncMock()+ mock_response.status = 200+ mock_response.json.return_value = mock_response_data++ # Configure the mock+ mock_aiohttp_session.get.return_value.__aenter__.return_value = mock_response++ # Initialize the tool+ tavily_tool = TavilySearchTool(TavilySearchToolConfig(api_key=mock_api_key))+ input_schema = TavilySearchToolInputSchema(queries=[mock_query])++ # Run the tool+ result = await tavily_tool.run_async(input_schema)++ # The last two results should be included+ assert len(result.results) == 2+ assert result.results[0].title == "Result Missing Query"+ assert result.results[1].title == "Valid Result"+++def test_searxng_search_tool_sync_run_method(mock_aiohttp_session):+ mock_api_key = "KEY"+ mock_query = "sync query"+ mock_response_data = {+ "results": [+ {+ "title": "Sync Test Result",+ "url": "https://example.com/sync",+ "content": "Sync content",+ "query": mock_query,+ }+ ]+ }++ # Create a mock response object+ mock_response = AsyncMock()+ mock_response.status = 200+ mock_response.json.return_value = mock_response_data++ # Configure the mock+ mock_aiohttp_session.get.return_value.__aenter__.return_value = mock_response++ # Initialize the tool+ tavily_tool = TavilySearchTool(TavilySearchToolConfig(api_key=mock_api_key))+ input_schema = TavilySearchToolInputSchema(queries=[mock_query])++ # Run the tool synchronously+ result = tavily_tool.run(input_schema)++ # Assertions+ assert len(result.results) == 1+ assert result.results[0].title == "Sync Test Result"+++async def test_searxng_search_tool_with_max_results(mock_aiohttp_session):+ mock_api_key = "KEY"+ mock_query = "test query with max results"+ mock_response_data = {+ "results": [+ {"title": f"Result {i}", "url": f"https://example.com/{i}", "content": f"Content {i}", "query": mock_query}+ for i in range(10)+ ]+ }++ # Create a mock response object+ mock_response = AsyncMock()+ mock_response.status = 200+ mock_response.json.return_value = mock_response_data++ # Configure the mock+ mock_aiohttp_session.get.return_value.__aenter__.return_value = mock_response++ # Initialize the tool+ tavily_tool = TavilySearchTool(TavilySearchToolConfig(api_key=mock_api_key, max_results=10))+ input_schema = TavilySearchToolInputSchema(queries=[mock_query])++ # Run the tool with max_results=5+ result = await tavily_tool.run_async(input_schema, max_results=5)++ # Assertions+ assert len(result.results) == 5+++async def test_searxng_search_tool_no_results(mock_aiohttp_session):+ # Existing test case remains the same+ mock_api_key = "KEY"+ mock_query = "no results query"+ mock_response_data = {"results": []}++ # Create a mock response object+ mock_response = AsyncMock()+ mock_response.status = 200+ mock_response.json.return_value = mock_response_data++ # Configure the mock+ mock_aiohttp_session.get.return_value.__aenter__.return_value = mock_response++ # Initialize the tool+ tavily_tool = TavilySearchTool(TavilySearchToolConfig(api_key=mock_api_key))+ input_schema = TavilySearchToolInputSchema(queries=[mock_query])++ # Run the tool+ result = await tavily_tool.run_async(input_schema)++ # Assertions+ assert len(result.results) == 0+++async def test_searxng_search_tool_error(mock_aiohttp_session):+ # Existing test case remains the same+ mock_api_key = "KEY"+ mock_query = "error query"++ # Create a mock response object with a 500 status+ mock_response = AsyncMock()+ mock_response.status = 500+ mock_response.reason = "Internal Server Error"++ # Configure the mock+ mock_aiohttp_session.get.return_value.__aenter__.return_value = mock_response++ # Initialize the tool+ tavily_tool = TavilySearchTool(TavilySearchToolConfig(api_key=mock_api_key))+ input_schema = TavilySearchToolInputSchema(queries=[mock_query])++ # Run the tool and expect an exception+ with pytest.raises(Exception) as excinfo:+ await tavily_tool.run_async(input_schema)++ # Assertion on the exception message+ assert "Failed to fetch search results" in str(excinfo.value)+++if __name__ == "__main__":+ pytest.main([__file__])