Open History to see the last commit
1---
2title: Perplexity Search
3id: perplexity-adapter
4order: 10
5description: "Give a TanStack AI agent live web results with the Perplexity Search API and @tanstack/ai-perplexity, or chat with Sonar."
6keywords:
7 - tanstack ai
8 - perplexity
9 - search api
10 - web search
11 - grounding
12---
13
14`@tanstack/ai-perplexity` exposes the Perplexity Search API as a tool. Pair it with a chat adapter that calls tools, such as `openaiText` or `anthropicText`.
15
16Want Sonar, the Perplexity chat model, instead? See [Chat with Sonar](#chat-with-sonar).
17
18## 1. Install
19
20This page uses OpenAI for the chat.
21
22<!-- ::start:tabs variant="package-manager" mode="install" -->
23
24react: @tanstack/ai @tanstack/ai-react @tanstack/ai-openai @tanstack/ai-perplexity
25vue: @tanstack/ai @tanstack/ai-vue @tanstack/ai-openai @tanstack/ai-perplexity
26solid: @tanstack/ai @tanstack/ai-solid @tanstack/ai-openai @tanstack/ai-perplexity
27svelte: @tanstack/ai @tanstack/ai-svelte @tanstack/ai-openai @tanstack/ai-perplexity
28preact: @tanstack/ai @tanstack/ai-preact @tanstack/ai-openai @tanstack/ai-perplexity
29angular: @tanstack/ai @tanstack/ai-angular @tanstack/ai-openai @tanstack/ai-perplexity
30vanilla: @tanstack/ai @tanstack/ai-client @tanstack/ai-openai @tanstack/ai-perplexity
31octane: @tanstack/ai @tanstack/ai-octane @tanstack/ai-openai @tanstack/ai-perplexity octane
32
33<!-- ::end:tabs -->
34
35## 2. Set the API key
36
37Get a key in the [Perplexity console](https://console.perplexity.ai/group/keys). Put it in the environment of your server, next to the key of your chat provider:
38
39```bash
40PERPLEXITY_API_KEY=pplx-...
41OPENAI_API_KEY=sk-...
42```
43
44The tool reads `PERPLEXITY_API_KEY` first, then `PPLX_API_KEY`.
45
46## 3. Stream a chat with web search from the server
47
48Add the search tool to `tools`. The model calls it when it needs fresh facts:
49
50```typescript
51import {
52 chat,
53 chatParamsFromRequest,
54 toServerSentEventsResponse,
55} from "@tanstack/ai";
56import { openaiText } from "@tanstack/ai-openai";
57import { perplexitySearchTool } from "@tanstack/ai-perplexity";
58
59const search = perplexitySearchTool({ defaultMaxResults: 5 });
60
61export async function POST(request: Request) {
62 const { messages, threadId, runId } = await chatParamsFromRequest(request);
63
64 const stream = chat({
65 adapter: openaiText("gpt-6.1-sol"),
66 tools: [search],
67 messages,
68 threadId,
69 runId,
70 });
71
72 return toServerSentEventsResponse(stream);
73}
74```
75
76To use Claude, swap `openaiText` for `anthropicText`. Any adapter that calls tools works the same way.
77
78## 4. Render the chat
79
80The client is the same for every provider. Point `useChat` at your route:
81
82```tsx
83import { useState } from "react";
84import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
85
86export function Chat() {
87 const [input, setInput] = useState("");
88 const { messages, sendMessage } = useChat({
89 connection: fetchServerSentEvents("/api/chat"),
90 threadId: "support-chat",
91 });
92
93 return (
94 <form
95 onSubmit={(event) => {
96 event.preventDefault();
97 sendMessage(input);
98 setInput("");
99 }}
100 >
101 {messages.map((message) => (
102 <p key={message.id}>
103 {message.parts
104 .map((part) => (part.type === "text" ? part.content : ""))
105 .join("")}
106 </p>
107 ))}
108 <input value={input} onChange={(event) => setInput(event.target.value)} />
109 </form>
110 );
111}
112```
113
114For Vue, Solid, Svelte, Angular, and the other frameworks, see [Quick Start](../getting-started/quick-start#3-render-the-chat).
115
116Ask "What were the top AI papers this week?" and the answer now uses live web results. For more on tools, see [Tools](../tools/tools).
117
118## Search without an agent
119
120To call the Search API in your own code, use `PerplexitySearchClient`:
121
122```ts
123import { PerplexitySearchClient } from "@tanstack/ai-perplexity";
124
125const client = new PerplexitySearchClient();
126const { results } = await client.search({
127 query: "mars sample return mission",
128 max_results: 5,
129 search_recency_filter: "month",
130});
131```
132
133The client also takes these, which the tool does not:
134
135- `max_tokens_per_page`: the most content tokens for each page.
136- `query` as an array of up to 5 queries.
137
138## Chat with Sonar
139
140Sonar is the Perplexity chat model. It searches the web by itself and does not take custom tools, so do not give it `perplexitySearchTool`. This package has no Sonar adapter. Use [`openaiCompatible`](./openai-compatible.md):
141
142```ts
143import { chat } from "@tanstack/ai";
144import { openaiCompatible } from "@tanstack/ai-openai/compatible";
145import { getPerplexityIntegrationHeaders } from "@tanstack/ai-perplexity";
146
147const perplexity = openaiCompatible({
148 name: "perplexity",
149 baseURL: "https://api.perplexity.ai",
150 apiKey: process.env.PERPLEXITY_API_KEY!,
151 models: ["sonar", "sonar-pro"],
152 defaultHeaders: getPerplexityIntegrationHeaders(),
153});
154
155const stream = chat({
156 adapter: perplexity("sonar"),
157 messages: [{ role: "user", content: "What is the latest on the Mars rover?" }],
158 threadId: "thread-1",
159});
160```
161
162The OpenAI SDK then calls `POST https://api.perplexity.ai/chat/completions`, the OpenAI-compatible path of Sonar.
163
164`getPerplexityIntegrationHeaders()` is optional. It adds the Perplexity attribution header `X-Pplx-Integration` (`tanstack/<package-version>`). The Search client sends this header by itself.
165
166## Models and options
167
168### Tool options
169
170`perplexitySearchTool(config?)` takes:
171
172- `defaultMaxResults`: the result count when the model does not send one. An integer from 1 to 20.
173- `name`: the tool name. The default is `perplexity_search`.
174- `description`: the tool description that the model sees.
175- `apiKey`, `baseURL`, `fetch`: the same as on `PerplexitySearchClient`. See [Configuration](#configuration).
176
177### Tool input
178
179The model fills these fields when it calls the tool:
180
181| Field | Type | Notes |
182| --- | --- | --- |
183| `query` | `string` (required) | The search query. |
184| `max_results` | `integer` (1 to 20) | The default is `defaultMaxResults` when set, else the API default (10). |
185| `search_domain_filter` | `string[]` | Max 20. An allowlist (`"nytimes.com"`) or a denylist (`"-pinterest.com"`), never both. Hostnames, optional paths, or TLDs. |
186| `search_recency_filter` | `"hour" \| "day" \| "week" \| "month" \| "year"` | The recency window. |
187| `search_after_date_filter` | `string` | `m/d/yyyy`. Only results on or after this date. |
188| `search_before_date_filter` | `string` | `m/d/yyyy`. Only results on or before this date. |
189
190### Tool output
191
192The tool returns `{ results: Array<{ title, url, snippet, date?, last_updated? }> }`.
193
194- `client.search()` also returns the optional response `id`.
195- Neither returns `server_time`.
196
197## Advanced
198
199### Configuration
200
201```ts
202import { PerplexitySearchClient } from "@tanstack/ai-perplexity";
203
204const client = new PerplexitySearchClient({
205 apiKey: process.env.PERPLEXITY_API_KEY, // optional, explicit key
206 baseURL: "https://api.perplexity.ai", // optional, override
207 fetch: globalThis.fetch, // optional, custom fetch
208});
209```
210
211The client calls `POST {baseURL}/search` with a bearer token.
212
213### Bring your own key
214
215`perplexityByok` from `@tanstack/ai-perplexity/byok` declares Perplexity for the BYOK store, with `PERPLEXITY_API_KEY` and `PPLX_API_KEY` as its env vars. See [Bring Your Own Key](../advanced/byok).
216
217### Perplexity references
218
219- [Search quickstart](https://docs.perplexity.ai/docs/search/quickstart)
220- [Search API reference](https://docs.perplexity.ai/api-reference/search-post)
221- [Domain filters](https://docs.perplexity.ai/docs/search/filters/domain-filter)
222- [Date and recency filters](https://docs.perplexity.ai/docs/search/filters/date-time-filters)