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

feat(toolkits): add Perplexity search toolkit (#4060)

James Liounis85fe9ed3dc70
diff --git a/camel/toolkits/search_toolkit.py b/camel/toolkits/search_toolkit.py
index 738ec2396..77ff977c6 100644
--- a/camel/toolkits/search_toolkit.py
+++ b/camel/toolkits/search_toolkit.py
@@ -34,7 +34,8 @@ class SearchToolkit(BaseToolkit):
r"""A class representing a toolkit for web search.
This class provides methods for searching information on the web using
- search engines like Google, DuckDuckGo, Wikipedia and Wolfram Alpha, Brave.
+ search engines like Google, DuckDuckGo, Wikipedia and Wolfram Alpha, Brave,
+ Perplexity.
"""
def __init__(
@@ -1665,6 +1666,105 @@ class SearchToolkit(BaseToolkit):
except Exception as e:
return {"error": f"Unexpected error during Querit search: {e!s}"}
+ @api_keys_required([(None, 'PERPLEXITY_API_KEY')])
+ def search_perplexity(
+ self,
+ query: Union[str, List[str]],
+ max_results: int = 10,
+ max_tokens: Optional[int] = None,
+ max_tokens_per_page: Optional[int] = None,
+ country: Optional[str] = None,
+ search_recency_filter: Optional[
+ Literal["hour", "day", "week", "month", "year"]
+ ] = None,
+ search_domain_filter: Optional[List[str]] = None,
+ search_language_filter: Optional[List[str]] = None,
+ extra_params: Optional[Dict[str, Any]] = None,
+ ) -> Dict[str, Any]:
+ r"""Use Perplexity Search API to retrieve web search results.
+
+ See https://docs.perplexity.ai/api-reference/search-post for details.
+
+ Args:
+ query (Union[str, List[str]]): The search query string, or a list
+ of search query strings.
+ max_results (int): Maximum number of results to return. Must be
+ between 1 and 20. (default: :obj:`10`)
+ max_tokens (Optional[int]): Maximum tokens for context (between 1
+ and 1,000,000). (default: :obj:`None`)
+ max_tokens_per_page (Optional[int]): Maximum number of tokens to
+ include from each result page (between 1 and 1,000,000).
+ (default: :obj:`None`)
+ country (Optional[str]): ISO 3166-1 alpha-2 country code used to
+ bias results to a specific country. (default: :obj:`None`)
+ search_recency_filter (Optional[Literal["hour", "day", "week", "month", "year"]]):
+ Filter results by recency. (default: :obj:`None`)
+ search_domain_filter (Optional[List[str]]): Up to 20 domains to
+ restrict the search to. (default: :obj:`None`)
+ search_language_filter (Optional[List[str]]): ISO 639-1 language
+ codes to restrict the search to. (default: :obj:`None`)
+ extra_params (Optional[Dict[str, Any]]): Additional request body
+ parameters supported by the Perplexity Search API. Explicit
+ arguments take precedence when keys overlap.
+ (default: :obj:`None`)
+
+ Returns:
+ Dict[str, Any]: The Perplexity Search API response. On success,
+ contains a ``results`` list (each entry includes ``title``,
+ ``url``, ``snippet``, and may include ``date`` and
+ ``last_updated``) along with ``id`` and ``server_time`` fields.
+ On failure, returns a dictionary with an ``error`` key.
+ """
+ from camel import __version__ as camel_version
+
+ PERPLEXITY_API_KEY = os.getenv("PERPLEXITY_API_KEY")
+
+ url = "https://api.perplexity.ai/search"
+ headers = {
+ "Authorization": f"Bearer {PERPLEXITY_API_KEY}",
+ "Content-Type": "application/json",
+ "X-Pplx-Integration": f"camel-ai/{camel_version}",
+ }
+
+ payload: Dict[str, Any] = {
+ "query": query,
+ "max_results": max_results,
+ }
+ optional_params: Dict[str, Any] = {
+ "max_tokens": max_tokens,
+ "max_tokens_per_page": max_tokens_per_page,
+ "country": country,
+ "search_recency_filter": search_recency_filter,
+ "search_domain_filter": search_domain_filter,
+ "search_language_filter": search_language_filter,
+ }
+ for key, value in optional_params.items():
+ if value is not None:
+ payload[key] = value
+ if extra_params:
+ for key, value in extra_params.items():
+ if value is not None and key not in payload:
+ payload[key] = value
+
+ try:
+ response = requests.post(
+ url, headers=headers, json=payload, timeout=self.timeout
+ )
+ if response.status_code != 200:
+ return {
+ "error": (
+ f"Perplexity API failed with status "
+ f"{response.status_code}: {response.text}"
+ )
+ }
+ return response.json()
+ except requests.exceptions.RequestException as e:
+ return {"error": f"Perplexity search request failed: {e!s}"}
+ except Exception as e:
+ return {
+ "error": f"Unexpected error during Perplexity search: {e!s}"
+ }
+
def get_tools(self) -> List[FunctionTool]:
r"""Returns a list of FunctionTool objects representing the
functions in the toolkit.
@@ -1689,6 +1789,7 @@ class SearchToolkit(BaseToolkit):
FunctionTool(self.search_metaso),
FunctionTool(self.search_serpapi),
FunctionTool(self.search_querit),
+ FunctionTool(self.search_perplexity),
]
# Deprecated method alias for backward compatibility
diff --git a/camel/utils/commons.py b/camel/utils/commons.py
index 39ca1661a..17c5031ae 100644
--- a/camel/utils/commons.py
+++ b/camel/utils/commons.py
@@ -342,6 +342,7 @@ def api_keys_required(
'AVIAN_API_KEY': "https://avian.io",
'ORCAROUTER_API_KEY': "https://www.orcarouter.ai/",
'QUERIT_API_KEY': "https://www.querit.ai/en/dashboard/home",
+ 'PERPLEXITY_API_KEY': "https://www.perplexity.ai/account/api",
}
key_way = env_key_urls.get(
missing_keys[0], "the official website"
diff --git a/docs/mintlify/reference/camel.toolkits.search_toolkit.mdx b/docs/mintlify/reference/camel.toolkits.search_toolkit.mdx
index 72ddbd4b4..ead85c93a 100644
--- a/docs/mintlify/reference/camel.toolkits.search_toolkit.mdx
+++ b/docs/mintlify/reference/camel.toolkits.search_toolkit.mdx
@@ -11,7 +11,8 @@ class SearchToolkit(BaseToolkit):
A class representing a toolkit for web search.
This class provides methods for searching information on the web using
-search engines like Google, DuckDuckGo, Wikipedia and Wolfram Alpha, Brave.
+search engines like Google, DuckDuckGo, Wikipedia and Wolfram Alpha, Brave,
+Perplexity.
<a id="camel.toolkits.search_toolkit.SearchToolkit.__init__"></a>
@@ -600,6 +601,45 @@ such as site names, favicons, and page ages.
- 'took': The server-side response time.
- or 'error': An error message if something went wrong.
+<a id="camel.toolkits.search_toolkit.SearchToolkit.search_perplexity"></a>
+
+### search_perplexity
+
+```python
+def search_perplexity(
+ self,
+ query: Union[str, List[str]],
+ max_results: int = 10,
+ max_tokens: Optional[int] = None,
+ max_tokens_per_page: Optional[int] = None,
+ country: Optional[str] = None,
+ search_recency_filter: Optional[Literal['hour', 'day', 'week', 'month', 'year']] = None,
+ search_domain_filter: Optional[List[str]] = None,
+ search_language_filter: Optional[List[str]] = None,
+ extra_params: Optional[Dict[str, Any]] = None,
+) -> Dict[str, Any]:
+```
+
+Use Perplexity Search API to retrieve web search results.
+
+See https://docs.perplexity.ai/api-reference/search-post for details.
+
+**Parameters:**
+
+- **query** (Union[str, List[str]]): The search query string, or a list of search query strings.
+- **max_results** (int): Maximum number of results to return. Must be between 1 and 20. (default: :obj:`10`)
+- **max_tokens** (Optional[int]): Maximum tokens for context (between 1 and 1,000,000). (default: :obj:`None`)
+- **max_tokens_per_page** (Optional[int]): Maximum number of tokens to include from each result page (between 1 and 1,000,000). (default: :obj:`None`)
+- **country** (Optional[str]): ISO 3166-1 alpha-2 country code used to bias results to a specific country. (default: :obj:`None`)
+- **search_recency_filter** (Optional[Literal['hour', 'day', 'week', 'month', 'year']]): Filter results by recency. (default: :obj:`None`)
+- **search_domain_filter** (Optional[List[str]]): Up to 20 domains to restrict the search to. (default: :obj:`None`)
+- **search_language_filter** (Optional[List[str]]): ISO 639-1 language codes to restrict the search to. (default: :obj:`None`)
+- **extra_params** (Optional[Dict[str, Any]]): Additional request body parameters supported by the Perplexity Search API. Explicit arguments take precedence when keys overlap. (default: :obj:`None`)
+
+**Returns:**
+
+ Dict[str, Any]: The Perplexity Search API response. On success, contains a `results` list (each entry includes `title`, `url`, `snippet`, and may include `date` and `last_updated`) along with `id` and `server_time` fields. On failure, returns a dictionary with an `error` key.
+
<a id="camel.toolkits.search_toolkit.SearchToolkit.get_tools"></a>
### get_tools
diff --git a/docs/reference/camel.toolkits.search_toolkit.md b/docs/reference/camel.toolkits.search_toolkit.md
index 6d4582fcd..de2cc2352 100644
--- a/docs/reference/camel.toolkits.search_toolkit.md
+++ b/docs/reference/camel.toolkits.search_toolkit.md
@@ -12,7 +12,7 @@ A class representing a toolkit for web search.
This class provides methods for searching information on the web using
search engines like Google, DuckDuckGo, Wikipedia and Wolfram Alpha, Brave,
-Querit.
+Querit, Perplexity.
<a id="camel.toolkits.search_toolkit.SearchToolkit.__init__"></a>
@@ -598,6 +598,45 @@ such as site names, favicons, and page ages.
- 'took' (str): The server-side response time.
- or 'error' (str): An error message if something went wrong.
+<a id="camel.toolkits.search_toolkit.SearchToolkit.search_perplexity"></a>
+
+### search_perplexity
+
+```python
+def search_perplexity(
+ self,
+ query: Union[str, List[str]],
+ max_results: int = 10,
+ max_tokens: Optional[int] = None,
+ max_tokens_per_page: Optional[int] = None,
+ country: Optional[str] = None,
+ search_recency_filter: Optional[Literal['hour', 'day', 'week', 'month', 'year']] = None,
+ search_domain_filter: Optional[List[str]] = None,
+ search_language_filter: Optional[List[str]] = None,
+ extra_params: Optional[Dict[str, Any]] = None,
+) -> Dict[str, Any]:
+```
+
+Use Perplexity Search API to retrieve web search results.
+
+See https://docs.perplexity.ai/api-reference/search-post for details.
+
+**Parameters:**
+
+- **query** (Union[str, List[str]]): The search query string, or a list of search query strings.
+- **max_results** (int): Maximum number of results to return. Must be between 1 and 20. (default: :obj:`10`)
+- **max_tokens** (Optional[int]): Maximum tokens for context (between 1 and 1,000,000). (default: :obj:`None`)
+- **max_tokens_per_page** (Optional[int]): Maximum number of tokens to include from each result page (between 1 and 1,000,000). (default: :obj:`None`)
+- **country** (Optional[str]): ISO 3166-1 alpha-2 country code used to bias results to a specific country. (default: :obj:`None`)
+- **search_recency_filter** (Optional[Literal['hour', 'day', 'week', 'month', 'year']]): Filter results by recency. (default: :obj:`None`)
+- **search_domain_filter** (Optional[List[str]]): Up to 20 domains to restrict the search to. (default: :obj:`None`)
+- **search_language_filter** (Optional[List[str]]): ISO 639-1 language codes to restrict the search to. (default: :obj:`None`)
+- **extra_params** (Optional[Dict[str, Any]]): Additional request body parameters supported by the Perplexity Search API. Explicit arguments take precedence when keys overlap. (default: :obj:`None`)
+
+**Returns:**
+
+ Dict[str, Any]: The Perplexity Search API response. On success, contains a `results` list (each entry includes `title`, `url`, `snippet`, and may include `date` and `last_updated`) along with `id` and `server_time` fields. On failure, returns a dictionary with an `error` key.
+
<a id="camel.toolkits.search_toolkit.SearchToolkit.get_tools"></a>
### get_tools
diff --git a/examples/toolkits/search_toolkit.py b/examples/toolkits/search_toolkit.py
index 75fa81b12..f40f8f205 100644
--- a/examples/toolkits/search_toolkit.py
+++ b/examples/toolkits/search_toolkit.py
@@ -184,7 +184,7 @@ search_bocha_response = SearchToolkit().search_bocha(
query="阿里巴巴2024年的esg报告",
freshness="noLimit",
summary=False,
- count=10,
+ number_of_result_pages=10,
)
print(search_bocha_response)
@@ -284,7 +284,7 @@ print(response.msgs[0].content)
exa_response = SearchToolkit().search_exa(
query="What is CAMEL-AI?",
category="github",
- num_results=1,
+ number_of_result_pages=1,
text=True,
)
@@ -555,3 +555,14 @@ querit_agent = ChatAgent(
usr_msg = "What are the latest developments in multi-agent AI systems?"
response = querit_agent.step(input_message=usr_msg, response_format=None)
print(response.msgs[0].content)
+
+# Example with ChatAgent using Perplexity search
+perplexity_agent = ChatAgent(
+ system_message="""You are a helpful assistant that can use Perplexity
+ search engine to answer questions.""",
+ tools=[FunctionTool(SearchToolkit().search_perplexity)],
+)
+
+usr_msg = "What are the latest developments in multi-agent AI systems?"
+response = perplexity_agent.step(input_message=usr_msg, response_format=None)
+print(response.msgs[0].content)
diff --git a/test/toolkits/test_search_functions.py b/test/toolkits/test_search_functions.py
index 8caa019ff..9d944eee0 100644
--- a/test/toolkits/test_search_functions.py
+++ b/test/toolkits/test_search_functions.py
@@ -1212,3 +1212,173 @@ def test_search_querit_empty_results(mock_post, search_toolkit):
assert "results" in result
assert len(result["results"]) == 0
assert result["search_id"] == 12348
+
+
+# ==================== Perplexity Search Tests ====================
+
+
+@patch('requests.post')
+def test_search_perplexity_success(mock_post, search_toolkit):
+ """Test successful Perplexity search."""
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {
+ "id": "abc123",
+ "server_time": "2026-04-30T00:00:00Z",
+ "results": [
+ {
+ "title": "CAMEL-AI",
+ "url": "https://www.camel-ai.org/",
+ "snippet": "CAMEL-AI is an open-source framework...",
+ "date": "2025-01-15",
+ "last_updated": "2025-03-01",
+ },
+ {
+ "title": "camel-ai/camel",
+ "url": "https://github.com/camel-ai/camel",
+ "snippet": "Multi-agent framework...",
+ "date": "2024-11-10",
+ "last_updated": "2025-04-01",
+ },
+ ],
+ }
+ mock_post.return_value = mock_response
+
+ with patch.dict(os.environ, {'PERPLEXITY_API_KEY': 'fake_api_key'}):
+ result = search_toolkit.search_perplexity(query="CAMEL-AI")
+
+ assert "results" in result
+ assert len(result["results"]) == 2
+ assert result["id"] == "abc123"
+ assert result["results"][0]["url"] == "https://www.camel-ai.org/"
+
+ mock_post.assert_called_once()
+ args, kwargs = mock_post.call_args
+ assert args[0] == "https://api.perplexity.ai/search"
+ assert kwargs['headers']['Authorization'] == 'Bearer fake_api_key'
+ assert kwargs['headers']['Content-Type'] == 'application/json'
+ # Attribution header must be present and use the camel-ai slug.
+ assert 'X-Pplx-Integration' in kwargs['headers']
+ assert kwargs['headers']['X-Pplx-Integration'].startswith('camel-ai/')
+ assert kwargs['json']['query'] == "CAMEL-AI"
+ assert kwargs['json']['max_results'] == 10
+ assert 'timeout' in kwargs
+
+
+@patch('requests.post')
+def test_search_perplexity_with_filters(mock_post, search_toolkit):
+ """Test Perplexity search with explicit filters and extra params."""
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {
+ "id": "def456",
+ "server_time": "2026-04-30T00:00:00Z",
+ "results": [],
+ }
+ mock_post.return_value = mock_response
+
+ with patch.dict(os.environ, {'PERPLEXITY_API_KEY': 'fake_api_key'}):
+ search_toolkit.search_perplexity(
+ query="AI agents",
+ max_results=5,
+ max_tokens=10000,
+ max_tokens_per_page=2048,
+ country="US",
+ search_recency_filter="month",
+ search_domain_filter=["github.com"],
+ search_language_filter=["en"],
+ extra_params={
+ "search_after_date_filter": "01/01/2024",
+ "max_results": 20,
+ },
+ )
+
+ assert mock_post.call_args[1]['json'] == {
+ "query": "AI agents",
+ "max_results": 5,
+ "max_tokens": 10000,
+ "max_tokens_per_page": 2048,
+ "country": "US",
+ "search_recency_filter": "month",
+ "search_domain_filter": ["github.com"],
+ "search_language_filter": ["en"],
+ "search_after_date_filter": "01/01/2024",
+ }
+
+
+@patch('requests.post')
+def test_search_perplexity_omits_unset_optional_params(
+ mock_post, search_toolkit
+):
+ """Test Perplexity search omits optional params when not set."""
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {
+ "id": "ghi789",
+ "server_time": "2026-04-30T00:00:00Z",
+ "results": [],
+ }
+ mock_post.return_value = mock_response
+
+ with patch.dict(os.environ, {'PERPLEXITY_API_KEY': 'fake_api_key'}):
+ search_toolkit.search_perplexity(query="test")
+
+ payload = mock_post.call_args[1]['json']
+ assert payload == {"query": "test", "max_results": 10}
+
+
+@patch('requests.post')
+def test_search_perplexity_with_multiple_queries(mock_post, search_toolkit):
+ """Test Perplexity search accepts multiple queries."""
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {
+ "id": "jkl012",
+ "server_time": "2026-04-30T00:00:00Z",
+ "results": [],
+ }
+ mock_post.return_value = mock_response
+
+ queries = ["CAMEL-AI", "multi-agent systems"]
+ with patch.dict(os.environ, {'PERPLEXITY_API_KEY': 'fake_api_key'}):
+ search_toolkit.search_perplexity(query=queries)
+
+ payload = mock_post.call_args[1]['json']
+ assert payload == {"query": queries, "max_results": 10}
+
+
+@patch('requests.post')
+def test_search_perplexity_http_error(mock_post, search_toolkit):
+ """Test HTTP error handling in Perplexity search."""
+ mock_response = MagicMock()
+ mock_response.status_code = 401
+ mock_response.text = '{"error": "Unauthorized"}'
+ mock_post.return_value = mock_response
+
+ with patch.dict(os.environ, {'PERPLEXITY_API_KEY': 'invalid_key'}):
+ result = search_toolkit.search_perplexity(query="test")
+
+ assert "error" in result
+ assert "401" in result["error"]
+
+
+@patch('requests.post')
+def test_search_perplexity_request_exception(mock_post, search_toolkit):
+ """Test request exception handling in Perplexity search."""
+ mock_post.side_effect = requests.exceptions.Timeout("Connection timed out")
+
+ with patch.dict(os.environ, {'PERPLEXITY_API_KEY': 'fake_key'}):
+ result = search_toolkit.search_perplexity(query="test")
+
+ assert "error" in result
+ assert "Perplexity search request failed" in result["error"]
+
+
+def test_search_perplexity_missing_api_key(search_toolkit):
+ """Test that missing PERPLEXITY_API_KEY raises a clear error."""
+ with patch.dict(os.environ, {}, clear=True):
+ with pytest.raises(ValueError) as exc_info:
+ search_toolkit.search_perplexity(query="test")
+
+ assert "PERPLEXITY_API_KEY" in str(exc_info.value)
+ assert "https://www.perplexity.ai/account/api" in str(exc_info.value)