diff --git a/README.md b/README.md index 59d92e6..72a2bc0 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ In-depth tutorials for advanced implementations: - Migrating from Sonar to the Agent API - Memory management patterns - OpenAI agents integration +- **[AG2 integration](docs/articles/ag2-integration/)** - Perplexity search tools for AG2 (AutoGen) agents - Multi-modal implementations ## Quick Start diff --git a/docs/articles/ag2-integration/README.md b/docs/articles/ag2-integration/README.md new file mode 100644 index 0000000..e97e898 --- /dev/null +++ b/docs/articles/ag2-integration/README.md @@ -0,0 +1,216 @@ +--- +title: AG2 Integration +description: Give AG2 agents real-time web search and grounded answers with Perplexity's Search API and Sonar +sidebar_position: 1 +keywords: [ag2, autogen, agents, integration, sonar, search api, multi-agent, tool calling] +--- + +# Giving AG2 Agents Real-Time Web Access with Perplexity + +This guide shows how to give [AG2](https://github.com/ag2ai/ag2) agents live web access using Perplexity's Search API and Sonar models. AG2 >= 1.0.0 ships first-party Perplexity support, so there is no adapter package to write or maintain. + +## ๐ŸŽฏ What You'll Build + +By the end of this guide, you'll have: +- โœ… An [AG2](https://github.com/ag2ai/ag2) agent with two Perplexity-backed tools +- โœ… Raw web search results via the **Search API** (no LLM hop, no extra token cost) +- โœ… Grounded answers with citations via **Sonar** +- โœ… Per-tool filtering (domains, recency, date ranges, search mode) + +## ๐Ÿ—๏ธ Architecture Overview + +```mermaid +graph TD + A[Your Application] --> B[AG2 Agent] + B --> C[PerplexitySearchToolkit] + C --> D[perplexity_search โ†’ Search API] + C --> E[perplexity_answer โ†’ Sonar Chat Completions] + D --> F[Real-time web index] + E --> F +``` + +AG2 ships first-party Perplexity support, so there is no adapter package to write or maintain. The +toolkit exposes both endpoints as tools sharing a single HTTP client, and AG2 drives the tool-calling +loop with whichever model provider the agent is configured with. + +## ๐Ÿ“‹ Prerequisites + +- **Python 3.10+** +- **AG2 >= 1.0.0** +- **Perplexity API key** โ€” [get one here](https://docs.perplexity.ai/home) +- An API key for the agent's own model provider (Anthropic, OpenAI, Gemini, โ€ฆ) + +:::info +The Perplexity tools are provider-agnostic: they run as local function tools, so they work with +**every** model provider AG2 supports โ€” not just OpenAI-compatible ones. +::: + +## ๐Ÿš€ Installation + +```bash +pip install "ag2[perplexity]>=1.0.0" +``` + +The `perplexity` extra pulls in the official `perplexityai` SDK. Add your agent's model provider +extra as well, for example: + +```bash +pip install "ag2[perplexity,anthropic]>=1.0.0" +``` + +## โš™๏ธ Environment Setup + +```bash +export PERPLEXITY_API_KEY="your-perplexity-api-key" +export ANTHROPIC_API_KEY="your-anthropic-api-key" +``` + +If `api_key` is omitted on the toolkit, the Perplexity SDK reads `PERPLEXITY_API_KEY` from the +environment automatically. + +## ๐Ÿงฐ The Tools + +| Tool | Endpoint | What it returns | +|------|----------|-----------------| +| `perplexity_search` | [Search API](https://docs.perplexity.ai/docs/search/quickstart) | Ranked title / URL / snippet / date results โ€” no LLM hop | +| `perplexity_answer` | [Sonar Chat Completions](https://docs.perplexity.ai/docs/sonar/openai-compatibility) | LLM answer with citations, plus search results and optional images | + +## ๐Ÿ Quick Start + +Passing the whole toolkit registers both tools: + +```python +import asyncio +import os + +from ag2 import Agent +from ag2.config import AnthropicConfig +from ag2.tools import PerplexitySearchToolkit + +agent = Agent( + "researcher", + prompt=( + "You research topics on the live web. " + "Use perplexity_search to gather sources and perplexity_answer for grounded summaries." + ), + config=AnthropicConfig(model="claude-sonnet-4-6"), + tools=[PerplexitySearchToolkit(api_key=os.environ["PERPLEXITY_API_KEY"])], +) + + +async def main() -> None: + reply = await agent.ask("What shipped in the latest Sonar model release? Cite your sources.") + print(reply.body) + + +asyncio.run(main()) +``` + +## ๐ŸŽš๏ธ Picking a Subset of Tools + +Each tool is exposed as a factory method on the toolkit. Call the method to get a ready-to-use tool, +then pass only the ones you need: + +```python +toolkit = PerplexitySearchToolkit() + +agent = Agent( + "searcher", + config=AnthropicConfig(model="claude-sonnet-4-6"), + tools=[toolkit.search()], # Search API only โ€” no Sonar calls +) +``` + +This is the cheap path when the agent only needs sources and will do its own synthesis. + +## ๐Ÿ”ง Per-Tool Configuration + +Per-call parameters live on the factory methods, not on the toolkit: + +```python +toolkit = PerplexitySearchToolkit() + +search_tool = toolkit.search( + max_results=10, + max_tokens_per_page=512, + search_domain_filter=["arxiv.org", "-medium.com"], # prefix '-' to exclude + search_recency_filter="week", # hour | day | week | month | year + search_after_date_filter="1/1/2025", # MM/DD/YYYY + search_before_date_filter="12/31/2025", +) + +answer_tool = toolkit.answer( + model="sonar-pro", # sonar | sonar-pro | sonar-reasoning | sonar-reasoning-pro | sonar-deep-research + max_tokens=2000, + search_context_size="high", # low | medium | high + search_mode="academic", # web | academic | sec + search_recency_filter="month", + return_images=True, + return_related_questions=True, +) + +agent = Agent("researcher", config=config, tools=[search_tool, answer_tool]) +``` + +## ๐Ÿงช Two Specialists, Two Configurations + +Because parameters are bound per tool, you can give different agents differently-scoped access to the +same API โ€” an academic researcher and a news monitor, for instance: + +```python +toolkit = PerplexitySearchToolkit() + +academic = Agent( + "academic", + prompt="You only cite peer-reviewed and preprint sources.", + config=AnthropicConfig(model="claude-sonnet-4-6"), + tools=[toolkit.answer(model="sonar-reasoning", search_mode="academic")], +) + +news = Agent( + "news", + prompt="You report only on developments from the last week.", + config=AnthropicConfig(model="claude-sonnet-4-6"), + tools=[toolkit.search(search_recency_filter="week", max_results=10)], +) +``` + +## ๐Ÿ” Runtime Values with `Variable` + +Every runtime parameter accepts an AG2 `Variable`, resolved from the run context at execution time +rather than fixed when the tool is built: + +```python +from ag2.annotations import Variable + +toolkit = PerplexitySearchToolkit() +search_tool = toolkit.search(search_recency_filter=Variable("freshness")) +``` + +## ๐ŸŒ Networking Options + +The toolkit forwards transport settings to the shared HTTP client, and any extra keyword arguments to +the `AsyncPerplexity` SDK constructor: + +```python +toolkit = PerplexitySearchToolkit( + api_key=os.environ["PERPLEXITY_API_KEY"], + proxy="http://proxy.internal:8080", + verify=True, + timeout=30.0, +) +``` + +Requests made through AG2 are tagged with integration headers, so Perplexity-side usage is +attributable to AG2 automatically. + +## ๐Ÿ“Ž Full Example + +A runnable version of this guide lives in [`ag2_perplexity.py`](./ag2_perplexity.py). + +## ๐Ÿ“š Resources + +- [AG2 repository](https://github.com/ag2ai/ag2) +- [AG2 `PerplexitySearchToolkit` documentation](https://docs.ag2.ai/docs/user-guide/tools/common_toolkits/#perplexitysearchtoolkit) +- [Perplexity Search API](https://docs.perplexity.ai/docs/search/quickstart) +- [Sonar models](https://docs.perplexity.ai/docs/sonar/openai-compatibility) diff --git a/docs/articles/ag2-integration/README.mdx b/docs/articles/ag2-integration/README.mdx new file mode 100644 index 0000000..cce20c4 --- /dev/null +++ b/docs/articles/ag2-integration/README.mdx @@ -0,0 +1,212 @@ +--- +title: AG2 Integration +description: Give AG2 agents real-time web search and grounded answers with Perplexity's Search API and Sonar +sidebar_position: 1 +keywords: [ag2, autogen, agents, integration, sonar, search api, multi-agent, tool calling] +--- + +## ๐ŸŽฏ What You'll Build + +By the end of this guide, you'll have: +- โœ… An [AG2](https://github.com/ag2ai/ag2) agent with two Perplexity-backed tools +- โœ… Raw web search results via the **Search API** (no LLM hop, no extra token cost) +- โœ… Grounded answers with citations via **Sonar** +- โœ… Per-tool filtering (domains, recency, date ranges, search mode) + +## ๐Ÿ—๏ธ Architecture Overview + +```mermaid +graph TD + A[Your Application] --> B[AG2 Agent] + B --> C[PerplexitySearchToolkit] + C --> D[perplexity_search โ†’ Search API] + C --> E[perplexity_answer โ†’ Sonar Chat Completions] + D --> F[Real-time web index] + E --> F +``` + +AG2 ships first-party Perplexity support, so there is no adapter package to write or maintain. The +toolkit exposes both endpoints as tools sharing a single HTTP client, and AG2 drives the tool-calling +loop with whichever model provider the agent is configured with. + +## ๐Ÿ“‹ Prerequisites + +- **Python 3.10+** +- **AG2 >= 1.0.0** +- **Perplexity API key** โ€” [get one here](https://docs.perplexity.ai/home) +- An API key for the agent's own model provider (Anthropic, OpenAI, Gemini, โ€ฆ) + +:::info +The Perplexity tools are provider-agnostic: they run as local function tools, so they work with +**every** model provider AG2 supports โ€” not just OpenAI-compatible ones. +::: + +## ๐Ÿš€ Installation + +```bash +pip install "ag2[perplexity]>=1.0.0" +``` + +The `perplexity` extra pulls in the official `perplexityai` SDK. Add your agent's model provider +extra as well, for example: + +```bash +pip install "ag2[perplexity,anthropic]>=1.0.0" +``` + +## โš™๏ธ Environment Setup + +```bash +export PERPLEXITY_API_KEY="your-perplexity-api-key" +export ANTHROPIC_API_KEY="your-anthropic-api-key" +``` + +If `api_key` is omitted on the toolkit, the Perplexity SDK reads `PERPLEXITY_API_KEY` from the +environment automatically. + +## ๐Ÿงฐ The Tools + +| Tool | Endpoint | What it returns | +|------|----------|-----------------| +| `perplexity_search` | [Search API](https://docs.perplexity.ai/docs/search/quickstart) | Ranked title / URL / snippet / date results โ€” no LLM hop | +| `perplexity_answer` | [Sonar Chat Completions](https://docs.perplexity.ai/docs/sonar/openai-compatibility) | LLM answer with citations, plus search results and optional images | + +## ๐Ÿ Quick Start + +Passing the whole toolkit registers both tools: + +```python +import asyncio +import os + +from ag2 import Agent +from ag2.config import AnthropicConfig +from ag2.tools import PerplexitySearchToolkit + +agent = Agent( + "researcher", + prompt=( + "You research topics on the live web. " + "Use perplexity_search to gather sources and perplexity_answer for grounded summaries." + ), + config=AnthropicConfig(model="claude-sonnet-4-6"), + tools=[PerplexitySearchToolkit(api_key=os.environ["PERPLEXITY_API_KEY"])], +) + + +async def main() -> None: + reply = await agent.ask("What shipped in the latest Sonar model release? Cite your sources.") + print(reply.body) + + +asyncio.run(main()) +``` + +## ๐ŸŽš๏ธ Picking a Subset of Tools + +Each tool is exposed as a factory method on the toolkit. Call the method to get a ready-to-use tool, +then pass only the ones you need: + +```python +toolkit = PerplexitySearchToolkit() + +agent = Agent( + "searcher", + config=AnthropicConfig(model="claude-sonnet-4-6"), + tools=[toolkit.search()], # Search API only โ€” no Sonar calls +) +``` + +This is the cheap path when the agent only needs sources and will do its own synthesis. + +## ๐Ÿ”ง Per-Tool Configuration + +Per-call parameters live on the factory methods, not on the toolkit: + +```python +toolkit = PerplexitySearchToolkit() + +search_tool = toolkit.search( + max_results=10, + max_tokens_per_page=512, + search_domain_filter=["arxiv.org", "-medium.com"], # prefix '-' to exclude + search_recency_filter="week", # hour | day | week | month | year + search_after_date_filter="1/1/2025", # MM/DD/YYYY + search_before_date_filter="12/31/2025", +) + +answer_tool = toolkit.answer( + model="sonar-pro", # sonar | sonar-pro | sonar-reasoning | sonar-reasoning-pro | sonar-deep-research + max_tokens=2000, + search_context_size="high", # low | medium | high + search_mode="academic", # web | academic | sec + search_recency_filter="month", + return_images=True, + return_related_questions=True, +) + +agent = Agent("researcher", config=config, tools=[search_tool, answer_tool]) +``` + +## ๐Ÿงช Two Specialists, Two Configurations + +Because parameters are bound per tool, you can give different agents differently-scoped access to the +same API โ€” an academic researcher and a news monitor, for instance: + +```python +toolkit = PerplexitySearchToolkit() + +academic = Agent( + "academic", + prompt="You only cite peer-reviewed and preprint sources.", + config=AnthropicConfig(model="claude-sonnet-4-6"), + tools=[toolkit.answer(model="sonar-reasoning", search_mode="academic")], +) + +news = Agent( + "news", + prompt="You report only on developments from the last week.", + config=AnthropicConfig(model="claude-sonnet-4-6"), + tools=[toolkit.search(search_recency_filter="week", max_results=10)], +) +``` + +## ๐Ÿ” Runtime Values with `Variable` + +Every runtime parameter accepts an AG2 `Variable`, resolved from the run context at execution time +rather than fixed when the tool is built: + +```python +from ag2.annotations import Variable + +toolkit = PerplexitySearchToolkit() +search_tool = toolkit.search(search_recency_filter=Variable("freshness")) +``` + +## ๐ŸŒ Networking Options + +The toolkit forwards transport settings to the shared HTTP client, and any extra keyword arguments to +the `AsyncPerplexity` SDK constructor: + +```python +toolkit = PerplexitySearchToolkit( + api_key=os.environ["PERPLEXITY_API_KEY"], + proxy="http://proxy.internal:8080", + verify=True, + timeout=30.0, +) +``` + +Requests made through AG2 are tagged with integration headers, so Perplexity-side usage is +attributable to AG2 automatically. + +## ๐Ÿ“Ž Full Example + +A runnable version of this guide lives in [`ag2_perplexity.py`](./ag2_perplexity.py). + +## ๐Ÿ“š Resources + +- [AG2 repository](https://github.com/ag2ai/ag2) +- [AG2 `PerplexitySearchToolkit` documentation](https://docs.ag2.ai/docs/user-guide/tools/common_toolkits/#perplexitysearchtoolkit) +- [Perplexity Search API](https://docs.perplexity.ai/docs/search/quickstart) +- [Sonar models](https://docs.perplexity.ai/docs/sonar/openai-compatibility) diff --git a/docs/articles/ag2-integration/ag2_perplexity.py b/docs/articles/ag2-integration/ag2_perplexity.py new file mode 100644 index 0000000..9bef2ab --- /dev/null +++ b/docs/articles/ag2-integration/ag2_perplexity.py @@ -0,0 +1,55 @@ +"""Perplexity + AG2: a research agent with web search and grounded answers. + +Requires AG2 >= 1.0.0: + + pip install "ag2[perplexity,anthropic]>=1.0.0" + + export PERPLEXITY_API_KEY="..." + export ANTHROPIC_API_KEY="..." + +Run: + + python ag2_perplexity.py +""" + +import asyncio + +from ag2 import Agent +from ag2.config import AnthropicConfig +from ag2.tools import PerplexitySearchToolkit + +# api_key is omitted, so the Perplexity SDK reads PERPLEXITY_API_KEY from the environment. +toolkit = PerplexitySearchToolkit() + +# Raw Search API results โ€” ranked sources, no LLM hop. +search_tool = toolkit.search( + max_results=10, + search_recency_filter="month", +) + +# Sonar answer with citations. +answer_tool = toolkit.answer( + model="sonar-pro", + search_context_size="high", + return_related_questions=True, +) + +agent = Agent( + "researcher", + prompt=( + "You research topics on the live web.\n" + "Use perplexity_search to gather candidate sources, then perplexity_answer " + "for a grounded summary. Always cite the URLs you relied on." + ), + config=AnthropicConfig(model="claude-sonnet-4-6"), + tools=[search_tool, answer_tool], +) + + +async def main() -> None: + reply = await agent.ask("What shipped in the latest Sonar model release?") + print(reply.body) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/docs/index.mdx b/docs/index.mdx index cb1a9ce..67fead3 100644 --- a/docs/index.mdx +++ b/docs/index.mdx @@ -25,7 +25,9 @@ Ready-to-run projects that demonstrate specific use cases and implementation pat Community-built applications that demonstrate real-world implementations of the API Platform. ### [Integration Guides](/cookbook/articles/memory-management/chat-summary-memory-buffer/README) -In-depth tutorials for advanced implementations and integrations with other tools. +In-depth tutorials for advanced implementations and integrations with other tools, including +[AG2 (AutoGen)](/cookbook/articles/ag2-integration/README) and +[OpenAI Agents](/cookbook/articles/openai-agents-integration/README). > **Note**: All complete code examples, scripts, and project files can be found in our [GitHub repository](https://github.com/perplexityai/api-cookbook). The documentation here provides guides and explanations, while the repository contains the full runnable implementations.