Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions python/docs/src/user-guide/agentchat-user-guide/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ tutorial/teams
tutorial/human-in-the-loop
tutorial/termination
tutorial/state
tutorial/perplexity

```

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,4 +77,11 @@ Create your own agents

Save and load agents and teams for persistent sessions
:::

:::{grid-item-card} {fas}`magnifying-glass;pst-color-primary` Perplexity
:link: ./perplexity.html
:link-alt: Perplexity: Use the Perplexity model client and Search API tool

Use the Perplexity model client and Search API tool
:::
::::
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# Perplexity (experimental)

[Perplexity](https://docs.perplexity.ai) provides LLM chat completions and a
real-time web search API. AutoGen ships two components for it in
`autogen_ext`:

- {py:class}`~autogen_ext.models.perplexity.PerplexityChatCompletionClient` —
a chat-completion client (Perplexity's `/v1/chat/completions` endpoint is
OpenAI-compatible, so this client is a thin wrapper around
{py:class}`~autogen_ext.models.openai.OpenAIChatCompletionClient`).
- {py:class}`~autogen_ext.tools.perplexity.PerplexitySearchTool` — a `BaseTool`
that calls the
[Perplexity Search API](https://docs.perplexity.ai/docs/search/quickstart)
for ranked web results.

Install the extra:

```bash
pip install -U "autogen-ext[perplexity]"
```

Both components read the API key from the `api_key` argument, falling back
to the `PERPLEXITY_API_KEY` environment variable (or the `PPLX_API_KEY`
alias). Get a key from <https://www.perplexity.ai/account/api/keys>.

## Chat completion client

```python
import asyncio
from autogen_core.models import UserMessage
from autogen_ext.models.perplexity import PerplexityChatCompletionClient


async def main() -> None:
client = PerplexityChatCompletionClient(model="sonar")
result = await client.create(
[UserMessage(content="What changed in Python 3.13?", source="user")]
)
print(result.content)
await client.close()


asyncio.run(main())
```

See the [Perplexity Agent API quickstart](https://docs.perplexity.ai/docs/agent/quickstart)
for the list of available models.

## Search tool

```python
import asyncio
from autogen_agentchat.agents import AssistantAgent
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_ext.tools.perplexity import PerplexitySearchTool


async def main() -> None:
model_client = OpenAIChatCompletionClient(model="gpt-4o-mini")
search = PerplexitySearchTool()
agent = AssistantAgent("researcher", model_client=model_client, tools=[search])
result = await agent.run(task="Summarize today's top AI news with sources.")
print(result.messages[-1].content)


asyncio.run(main())
```

The tool accepts `query`, `max_results`, `search_domain_filter`
(allow- or deny-list — prefix a domain with `-` to exclude; do **not** mix
allow and deny in the same call), and `search_recency_filter`
(`hour` / `day` / `week` / `month` / `year`). See
[domain filters](https://docs.perplexity.ai/docs/search/filters/domain-filter)
and [date/recency filters](https://docs.perplexity.ai/docs/search/filters/date-time-filters)
for details.
6 changes: 6 additions & 0 deletions python/packages/autogen-ext/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ azure = [
docker = ["docker~=7.0", "asyncio_atexit>=1.0.1"]
ollama = ["ollama>=0.4.7", "tiktoken>=0.8.0"]
openai = ["openai>=1.93", "tiktoken>=0.8.0", "aiofiles"]
perplexity = [
"openai>=1.93",
"tiktoken>=0.8.0",
"aiofiles",
"httpx>=0.27.0",
]
file-surfer = [
"autogen-agentchat==0.7.5",
"magika>=0.6.1rc2",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from ._perplexity_client import PERPLEXITY_BASE_URL, PerplexityChatCompletionClient

__all__ = [
"PERPLEXITY_BASE_URL",
"PerplexityChatCompletionClient",
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
"""Perplexity chat completion client for AutoGen.

Perplexity's chat completions endpoint is OpenAI-compatible, so this client
wraps :class:`~autogen_ext.models.openai.OpenAIChatCompletionClient` with the
Perplexity base URL and a sensible default ``model_info`` block, while reading
``PERPLEXITY_API_KEY`` (or ``PPLX_API_KEY``) from the environment.

See https://docs.perplexity.ai/docs/agent/quickstart for endpoint details.
"""

from __future__ import annotations

import os
from typing import Any

from autogen_core.models import ModelFamily, ModelInfo

from ..openai import OpenAIChatCompletionClient

PERPLEXITY_BASE_URL = "https://api.perplexity.ai"

_DEFAULT_MODEL_INFO: ModelInfo = {
"vision": False,
"function_calling": True,
"json_output": True,
"family": ModelFamily.UNKNOWN,
"structured_output": True,
}


class PerplexityChatCompletionClient(OpenAIChatCompletionClient):
"""Chat completion client for Perplexity.

Wraps :class:`~autogen_ext.models.openai.OpenAIChatCompletionClient` with
Perplexity's OpenAI-compatible endpoint at ``https://api.perplexity.ai``.

The API key is taken from the ``api_key`` argument, falling back to the
``PERPLEXITY_API_KEY`` env var, then ``PPLX_API_KEY``. ``base_url`` defaults
to :data:`PERPLEXITY_BASE_URL` and can be overridden if you need to point
at an alternative gateway.

To use this client, install the ``perplexity`` extra::

pip install -U "autogen-ext[perplexity]"

Args:
model: The Perplexity model identifier (e.g. one of the chat-completion
models documented at https://docs.perplexity.ai/docs/agent/models).
api_key: API key. Defaults to ``PERPLEXITY_API_KEY`` or ``PPLX_API_KEY``.
base_url: API base URL. Defaults to ``https://api.perplexity.ai``.
model_info: Optional :class:`ModelInfo`. A reasonable default is supplied.
**kwargs: Forwarded to :class:`OpenAIChatCompletionClient`.

Example:
.. code-block:: python

import asyncio
from autogen_core.models import UserMessage
from autogen_ext.models.perplexity import PerplexityChatCompletionClient


async def main() -> None:
client = PerplexityChatCompletionClient(model="sonar")
result = await client.create([UserMessage(content="What is RAG?", source="user")])
print(result.content)
await client.close()


asyncio.run(main())
"""

component_provider_override = "autogen_ext.models.perplexity.PerplexityChatCompletionClient"

def __init__(
self,
model: str,
*,
api_key: str | None = None,
base_url: str | None = None,
model_info: ModelInfo | None = None,
**kwargs: Any,
) -> None:
resolved_api_key = api_key or os.environ.get("PERPLEXITY_API_KEY") or os.environ.get("PPLX_API_KEY")
if not resolved_api_key:
raise ValueError(
"Perplexity API key not provided. Pass api_key=... or set the "
"PERPLEXITY_API_KEY (or PPLX_API_KEY) environment variable."
)

super().__init__(
model=model,
api_key=resolved_api_key,
base_url=base_url or PERPLEXITY_BASE_URL,
model_info=model_info or _DEFAULT_MODEL_INFO,
**kwargs,
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from ._perplexity_search_tool import (
PerplexitySearchResponse,
PerplexitySearchResult,
PerplexitySearchTool,
PerplexitySearchToolArgs,
PerplexitySearchToolConfig,
)

__all__ = [
"PerplexitySearchTool",
"PerplexitySearchToolArgs",
"PerplexitySearchToolConfig",
"PerplexitySearchResult",
"PerplexitySearchResponse",
]
Loading