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
115 changes: 115 additions & 0 deletions docs/adapters/perplexity.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
---
title: Perplexity
id: perplexity-adapter
order: 10
description: "Use the Perplexity Search API and OpenAI-compatible chat completions with TanStack AI via @tanstack/ai-perplexity."
keywords:
- tanstack ai
- perplexity
- search api
- web search
- adapter
---

`@tanstack/ai-perplexity` integrates [Perplexity](https://www.perplexity.ai) with TanStack AI:

- A **Search API tool** that grounds your agent on the live web (`POST https://api.perplexity.ai/search`).
- An **OpenAI-compatible chat client** that points the `openai` SDK at Perplexity's chat-completions endpoint, so existing OpenAI code can target Perplexity by swapping the base URL.

## Installation

```bash
npm install @tanstack/ai-perplexity
```

Set your API key (get one at <https://www.perplexity.ai/account/api/keys>):

```bash
export PERPLEXITY_API_KEY=...
# PPLX_API_KEY is also accepted
```

## Search tool

Wrap the Search API as a TanStack AI tool and pass it to a chat agent so the model can fetch up-to-date web results:

```ts
import { chat } from '@tanstack/ai'
import { perplexitySearchTool } from '@tanstack/ai-perplexity'

const search = perplexitySearchTool({
// optional: applied when the model omits max_results
defaultMaxResults: 5,
})

const stream = chat({
// ... your text adapter ...
tools: [search],
messages: [
{ role: 'user', content: 'What were the top AI papers this week?' },
],
})
```

The tool input schema accepts:

| Field | Type | Notes |
| --------------------------- | ------------------------------------------------- | ------------------------------------------------------------------ |
| `query` | `string` (required) | The search query. |
| `max_results` | `integer` (1–20) | Defaults to API default (10), or `defaultMaxResults` if configured.|
| `search_domain_filter` | `string[]` | Allowlist (`"nytimes.com"`) **or** denylist (`"-pinterest.com"`) — never both. |
| `search_recency_filter` | `"hour" \| "day" \| "week" \| "month" \| "year"` | Recency window. |
| `search_after_date_filter` | `string` | `m/d/yyyy` — only results on/after this date. |
| `search_before_date_filter` | `string` | `m/d/yyyy` — only results on/before this date. |

Each result is `{ title, url, snippet, date? }`.

### Direct client

If you want to call the Search API outside an agent loop:

```ts
import { PerplexitySearchClient } from '@tanstack/ai-perplexity'

const client = new PerplexitySearchClient()
const { results } = await client.search({
query: 'mars sample return mission',
max_results: 5,
search_recency_filter: 'month',
})
```

## Chat (OpenAI-compatible)

Perplexity exposes `POST /v1/chat/completions` with the standard OpenAI Chat Completions shape. `createPerplexityChatClient` returns an `openai` SDK instance pointed at `https://api.perplexity.ai`:

```ts
import { createPerplexityChatClient } from '@tanstack/ai-perplexity/chat'

const client = createPerplexityChatClient()
const completion = await client.chat.completions.create({
model: 'sonar',
messages: [
{ role: 'user', content: 'What is the latest on the Mars rover?' },
],
})
```

## Configuration

```ts
import { PerplexitySearchClient } from '@tanstack/ai-perplexity'

const client = new PerplexitySearchClient({
apiKey: process.env.PERPLEXITY_API_KEY, // explicit key (optional)
baseURL: 'https://api.perplexity.ai', // override (optional)
fetch: globalThis.fetch, // custom fetch (optional)
})
```

## References

- Search quickstart: <https://docs.perplexity.ai/docs/search/quickstart>
- Search API reference: <https://docs.perplexity.ai/api-reference/search-post>
- Domain filters: <https://docs.perplexity.ai/docs/search/filters/domain-filter>
- Date / recency filters: <https://docs.perplexity.ai/docs/search/filters/date-time-filters>
4 changes: 4 additions & 0 deletions docs/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,10 @@
{
"label": "OpenRouter Adapter",
"to": "adapters/openrouter"
},
{
"label": "Perplexity",
"to": "adapters/perplexity"
}
]
},
Expand Down
91 changes: 91 additions & 0 deletions packages/typescript/ai-perplexity/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# @tanstack/ai-perplexity

[Perplexity](https://www.perplexity.ai) integration for [TanStack AI](https://tanstack.com/ai):

- **Search API tool** — call `POST https://api.perplexity.ai/search` from an LLM agent loop and get back ranked web results (`title`, `url`, `snippet`, `date?`) suitable for grounding/citation.
- **OpenAI-compatible chat client** — a thin factory that points the `openai` SDK at Perplexity's chat-completions endpoint so you can reuse existing OpenAI code paths.

## Install

```bash
pnpm add @tanstack/ai-perplexity
```

Set your API key (get one at <https://www.perplexity.ai/account/api/keys>):

```bash
export PERPLEXITY_API_KEY=...
# PPLX_API_KEY is also accepted
```

## Search tool

Wrap the Search API as a TanStack AI tool and pass it to a chat agent:

```ts
import { perplexitySearchTool } from '@tanstack/ai-perplexity'

const search = perplexitySearchTool({
// optional defaults
defaultMaxResults: 5,
})

// Use directly with chat()
chat({
tools: [search],
// ...
})
```

The tool input schema accepts:

| field | type | notes |
| --------------------------- | --------------------------------------------------- | ------------------------------------------------------------------ |
| `query` | `string` (required) | The search query. |
| `max_results` | `integer` (1–20) | Defaults to API default (10), or `defaultMaxResults` if configured.|
| `search_domain_filter` | `string[]` | Allowlist (`"nytimes.com"`) **or** denylist (`"-pinterest.com"`) — never both. |
| `search_recency_filter` | `"hour" \| "day" \| "week" \| "month" \| "year"` | Recency window. |
| `search_after_date_filter` | `string` | `m/d/yyyy` — only results on/after this date. |
| `search_before_date_filter` | `string` | `m/d/yyyy` — only results on/before this date. |

Output: `{ results: Array<{ title, url, snippet, date? }> }`.

### Direct client usage

If you don't need the tool wrapping, call the Search API directly:

```ts
import { PerplexitySearchClient } from '@tanstack/ai-perplexity'

const client = new PerplexitySearchClient()
const { results } = await client.search({
query: 'mars sample return mission',
max_results: 5,
search_recency_filter: 'month',
})
```

## Chat (OpenAI-compatible)

Perplexity's chat completions endpoint is OpenAI-compatible, so you can target it by swapping the `baseURL`:

```ts
import { createPerplexityChatClient } from '@tanstack/ai-perplexity/chat'

const client = createPerplexityChatClient()
const completion = await client.chat.completions.create({
model: 'sonar',
messages: [
{ role: 'user', content: 'What is the latest on the Mars rover?' },
],
})
```

Env vars: `PERPLEXITY_API_KEY` (preferred) or `PPLX_API_KEY`.

## Docs

- Search quickstart: <https://docs.perplexity.ai/docs/search/quickstart>
- Search API reference: <https://docs.perplexity.ai/api-reference/search-post>
- Domain filters: <https://docs.perplexity.ai/docs/search/filters/domain-filter>
- Date / recency filters: <https://docs.perplexity.ai/docs/search/filters/date-time-filters>
61 changes: 61 additions & 0 deletions packages/typescript/ai-perplexity/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
{
"name": "@tanstack/ai-perplexity",
"version": "0.1.0",
"description": "Perplexity adapter for TanStack AI — Search API and OpenAI-compatible chat",
"author": "",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/TanStack/ai.git",
"directory": "packages/typescript/ai-perplexity"
},
"type": "module",
"module": "./dist/esm/index.js",
"types": "./dist/esm/index.d.ts",
"exports": {
".": {
"types": "./dist/esm/index.d.ts",
"import": "./dist/esm/index.js"
},
"./search": {
"types": "./dist/esm/search/index.d.ts",
"import": "./dist/esm/search/index.js"
},
"./chat": {
"types": "./dist/esm/chat/index.d.ts",
"import": "./dist/esm/chat/index.js"
}
},
"files": [
"dist",
"src"
],
"scripts": {
"build": "vite build",
"clean": "premove ./build ./dist",
"lint:fix": "eslint ./src --fix",
"test:build": "publint --strict",
"test:eslint": "eslint ./src",
"test:lib": "vitest run",
"test:lib:dev": "pnpm test:lib --watch",
"test:types": "tsc"
},
"keywords": [
"ai",
"perplexity",
"search",
"tanstack",
"adapter"
],
"dependencies": {
"openai": "^6.9.1"
},
"devDependencies": {
"@tanstack/ai": "workspace:*",
"@vitest/coverage-v8": "4.0.14",
"vite": "^7.2.7"
},
"peerDependencies": {
"@tanstack/ai": "workspace:^"
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify internal workspace protocol usage in package manifests
rg -n --glob 'packages/**/package.json' '"@tanstack/ai"\s*:\s*"workspace:[^*"]+"'

Repository: TanStack/ai

Length of output: 1107


🏁 Script executed:

#!/bin/bash
# Check if workspace:* (without caret) is used anywhere in package.json files
rg -n --glob 'packages/**/package.json' '"@tanstack/ai"\s*:\s*"workspace:\*"'

Repository: TanStack/ai

Length of output: 2156


🏁 Script executed:

#!/bin/bash
# Also check the devDependencies in the file under review
cat -n packages/typescript/ai-perplexity/package.json | grep -A 10 '"devDependencies"'

Repository: TanStack/ai

Length of output: 303


🏁 Script executed:

#!/bin/bash
# Check what pattern is used in devDependencies for `@tanstack/ai` across all provider adapters
rg -n --glob 'packages/typescript/ai-*/package.json' '"@tanstack/ai"' -A 1 -B 1 | head -50

Repository: TanStack/ai

Length of output: 2974


Use workspace:* for the internal peer dependency at line 59.

The peerDependency uses workspace:^ which violates the repo guideline requiring workspace:* for internal package dependencies. This is a systematic issue across provider adapter packages (ai-react, ai-vue, ai-solid, ai-svelte, ai-preact, and others use the same pattern), but ai-openrouter correctly uses workspace:* in peerDependencies, confirming this pattern is achievable.

Suggested fix
   "peerDependencies": {
-    "@tanstack/ai": "workspace:^"
+    "@tanstack/ai": "workspace:*"
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"@tanstack/ai": "workspace:^"
"peerDependencies": {
"@tanstack/ai": "workspace:*"
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/typescript/ai-perplexity/package.json` at line 59, The
peerDependency entry for "@tanstack/ai" in the package.json uses "workspace:^"
which violates the repo guideline; change that value to "workspace:*" in the
peerDependencies block of the ai-perplexity package.json (update the
"@tanstack/ai" entry), and mirror the same replacement for any other provider
adapter packages that currently use "workspace:^" so all internal peer deps use
"workspace:*".

}
}
42 changes: 42 additions & 0 deletions packages/typescript/ai-perplexity/src/chat/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import OpenAI from 'openai'
import { getPerplexityApiKeyFromEnv } from '../utils/api-key'
import type { ClientOptions } from 'openai'

export interface PerplexityChatClientConfig extends ClientOptions {
/** Perplexity API key. Falls back to `PERPLEXITY_API_KEY` / `PPLX_API_KEY` env vars. */
apiKey?: string
/** Override the API base URL (defaults to https://api.perplexity.ai). */
baseURL?: string
}

const DEFAULT_BASE_URL = 'https://api.perplexity.ai'

/**
* Create an OpenAI SDK client pointed at Perplexity's OpenAI-compatible
* chat-completions endpoint.
*
* Perplexity exposes `POST /v1/chat/completions` with the standard OpenAI
* Chat Completions request/response shape, so any code that consumes the
* `openai` SDK can target Perplexity by swapping the `baseURL`.
*
* @example
* ```ts
* import { createPerplexityChatClient } from '@tanstack/ai-perplexity/chat'
*
* const client = createPerplexityChatClient()
* const completion = await client.chat.completions.create({
* model: 'sonar',
* messages: [{ role: 'user', content: 'What is the latest on the Mars rover?' }],
* })
* ```
*/
export function createPerplexityChatClient(
config: PerplexityChatClientConfig = {},
): OpenAI {
const { apiKey, baseURL, ...rest } = config
return new OpenAI({
...rest,
apiKey: apiKey ?? getPerplexityApiKeyFromEnv(),
baseURL: baseURL ?? DEFAULT_BASE_URL,
Comment on lines +36 to +40
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Normalize explicit apiKey input before constructing the client.

On Line 39, ?? treats '' as provided, so an empty key is sent instead of falling back or failing early.

Suggested fix
 export function createPerplexityChatClient(
   config: PerplexityChatClientConfig = {},
 ): OpenAI {
   const { apiKey, baseURL, ...rest } = config
+  const resolvedApiKey =
+    typeof apiKey === 'string' && apiKey.trim().length > 0
+      ? apiKey.trim()
+      : getPerplexityApiKeyFromEnv()
   return new OpenAI({
     ...rest,
-    apiKey: apiKey ?? getPerplexityApiKeyFromEnv(),
+    apiKey: resolvedApiKey,
     baseURL: baseURL ?? DEFAULT_BASE_URL,
   })
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const { apiKey, baseURL, ...rest } = config
return new OpenAI({
...rest,
apiKey: apiKey ?? getPerplexityApiKeyFromEnv(),
baseURL: baseURL ?? DEFAULT_BASE_URL,
export function createPerplexityChatClient(
config: PerplexityChatClientConfig = {},
): OpenAI {
const { apiKey, baseURL, ...rest } = config
const resolvedApiKey =
typeof apiKey === 'string' && apiKey.trim().length > 0
? apiKey.trim()
: getPerplexityApiKeyFromEnv()
return new OpenAI({
...rest,
apiKey: resolvedApiKey,
baseURL: baseURL ?? DEFAULT_BASE_URL,
})
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/typescript/ai-perplexity/src/chat/client.ts` around lines 36 - 40,
The config destructuring passes an empty string as apiKey into the OpenAI
constructor because the current `apiKey ?? getPerplexityApiKeyFromEnv()` treats
'' as provided; fix by normalizing `apiKey` first (e.g., compute an
`effectiveApiKey` using `apiKey` trimmed and treated as missing when empty,
falling back to `getPerplexityApiKeyFromEnv()`), validate that `effectiveApiKey`
is non-empty (throw or log/exit early if still missing), and then pass
`effectiveApiKey` into the `new OpenAI({...})` call instead of the raw `apiKey`.

})
}
4 changes: 4 additions & 0 deletions packages/typescript/ai-perplexity/src/chat/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export {
createPerplexityChatClient,
type PerplexityChatClientConfig,
} from './client'
18 changes: 18 additions & 0 deletions packages/typescript/ai-perplexity/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Search API
export {
PerplexitySearchClient,
perplexitySearchTool,
type PerplexitySearchClientConfig,
type PerplexitySearchRequest,
type PerplexitySearchResponse,
type PerplexitySearchResult,
} from './search'

// OpenAI-compatible chat client (Perplexity chat completions endpoint)
export {
createPerplexityChatClient,
type PerplexityChatClientConfig,
} from './chat'

// Utilities
export { getPerplexityApiKeyFromEnv } from './utils/api-key'
Loading