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 module as it is compatible with the OpenAI API. You can install it with

pnpm
npm
yarn
pnpm add @ai-sdk/openai

Provider Instance

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

import { createOpenAI } from '@ai-sdk/openai';
const perplexity = createOpenAI({
name: 'perplexity',
apiKey: 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-sonar-large-32k-online.

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

Example

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

import { createOpenAI } from '@ai-sdk/openai';
import { generateText } from 'ai';
const perplexity = createOpenAI({
name: 'perplexity',
apiKey: process.env.PERPLEXITY_API_KEY ?? '',
baseURL: 'https://api.perplexity.ai/',
});
const { text } = await generateText({
model: perplexity('llama-3-sonar-large-32k-online'),
prompt: 'Write a vegetarian lasagna recipe for 4 people.',
});

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