Perplexity Provider

Perplexity is a search engine that uses LLMs to answer questions. It offers an OpenAI compatible API that you can use with the AI SDK.

Setup

The Perplexity provider is available via the @ai-sdk/openai-compatible module as it is compatible with the OpenAI API. You can install it with

pnpm
npm
yarn
pnpm add @ai-sdk/openai-compatible

Provider Instance

To use Perplexity, you can create a custom provider instance with the createOpenAI function from @ai-sdk/openai:

import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
const perplexity = createOpenAICompatible({
name: 'perplexity',
headers: {
Authorization: `Bearer ${process.env.PERPLEXITY_API_KEY}`,
},
baseURL: 'https://api.perplexity.ai/',
});

Language Models

You can create Perplexity models using a provider instance. The first argument is the model id, e.g. llama-3.1-sonar-large-32k-online.

const model = perplexity('llama-3.1-sonar-large-32k-online');

Example

You can use Perplexity language models to generate text with the generateText function:

import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
import { generateText } from 'ai';
const perplexity = createOpenAICompatible({
name: 'perplexity',
headers: {
Authorization: `Bearer ${process.env.PERPLEXITY_API_KEY}`,
},
baseURL: 'https://api.perplexity.ai/',
});
const { text } = await generateText({
model: perplexity('llama-3.1-sonar-large-32k-online'),
prompt: 'Write a vegetarian lasagna recipe for 4 people.',
});

Perplexity language models can also be used in the streamText function.