Skip to main content
This guide walks through building a complete retrieval-augmented generation (RAG) pipeline using Perplexity’s Embeddings API and Agent API. It covers document chunking, embedding with both standard and contextualized models, building an in-memory vector index, querying for relevant context, and generating grounded answers.
This guide focuses on the end-to-end pipeline. For API reference details on individual embedding types, see Standard Embeddings and Contextualized Embeddings.

Pipeline Overview

A RAG pipeline retrieves relevant information from your own documents before generating an answer, grounding model responses in your data rather than relying solely on parametric knowledge. RAG Pipeline Diagram The steps are:
  1. Chunk your source documents into manageable pieces with overlap.
  2. Embed each chunk using a Perplexity embedding model.
  3. Index the embeddings for similarity search.
  4. Query by embedding the user question with the same model.
  5. Retrieve the top-k most similar chunks.
  6. Generate an answer by passing the retrieved context to the Agent API.

Prerequisites

Install the Perplexity SDK:
If you don’t have an API key yet:

Get your Perplexity API Key

Navigate to the API Keys tab in the API Portal and generate a new key.
Then export your API key as an environment variable:

Document Chunking

Split your documents into chunks small enough for the model’s context window while preserving semantic coherence. Overlapping chunks ensure that information at chunk boundaries is not lost.
A chunk size of 300-500 characters with 50-100 characters of overlap works well for most use cases. For structured documents (markdown, HTML), consider splitting on headings or paragraph boundaries instead of raw character counts.

Embedding with the Standard Model

Standard embeddings treat each text independently. Use them when chunks are self-contained and don’t rely on surrounding context.

Embedding with the Contextualized Model

Contextualized embeddings understand that chunks belong to the same document. The model uses cross-chunk attention so that each chunk’s embedding incorporates information from its neighbors. The key API difference is the nested array structure: each inner array contains chunks from a single document.
Chunk ordering matters. Chunks within each document must be passed in their original sequential order. The contextualized model uses positional context to relate neighboring chunks, so shuffling them will degrade embedding quality.

Querying a Contextualized Index

When using contextualized embeddings, wrap each query as a single-element inner list (e.g., [[query]]) so the API treats it as a single-chunk document:

Building a Vector Index

This example uses numpy for cosine similarity with a simple in-memory index. For production systems with millions of vectors, use a dedicated vector database (Pinecone, Weaviate, Qdrant, etc.).

Query Pipeline

The full query pipeline embeds the user question, retrieves the top-k most similar chunks, and passes them as context to the Agent API for answer generation.
Start with top_k=3 and min_score=0.3 for most use cases. Raise top_k to 5–7 for broad questions or short chunks. Raise min_score to 0.5–0.7 if retrieved chunks contain irrelevant information. Lower it toward 0.2 for diverse or ambiguous queries.

Standard vs Contextualized Comparison

When to Use Standard Embeddings

  • Chunks are self-contained and do not rely on surrounding context.
  • Your content consists of FAQ pairs, product descriptions, or short independent entries.
  • You need the lowest cost per token.

When to Use Contextualized Embeddings

  • Chunks come from longer documents where meaning depends on neighboring text.
  • A chunk like “This approach improves performance by 20%” only makes sense with its surrounding context.
  • You are embedding paragraphs from articles, reports, or technical documentation.
  • You want higher retrieval accuracy at a modest cost increase.

Matryoshka Dimensions

Perplexity embedding models support Matryoshka Representation Learning (MRL), which concentrates the most important information in the first N dimensions. You can request reduced dimensions directly via the API for faster search and smaller storage.
Dimension reduction tradeoffs for the pplx-embed-v1-4b model:
Use the dimensions parameter in the API call rather than manually truncating vectors. The API applies proper normalization for the requested dimension count. Start with full dimensions and reduce only when storage or latency becomes a bottleneck.

Batch Processing

When embedding large document collections, process them in batches to stay within API rate limits. The standard API accepts up to 512 texts per request with a combined limit of 120,000 tokens.
For contextualized embeddings, batch at the document level using client.contextualized_embeddings.create(input=batch_of_doc_arrays) with the same pattern. The contextualized API accepts up to 512 documents with 16,000 total chunks per request.
Rate limits: Keep batch sizes well within the API limits (512 texts / 120,000 tokens for standard; 512 documents / 16,000 chunks for contextualized) and add small delays between requests to avoid throttling.

Complete Example

A self-contained pipeline that indexes two documents with contextualized embeddings and answers questions against the indexed content.

Next Steps

Standard Embeddings

API reference for standard embedding parameters and response format.

Contextualized Embeddings

API reference for contextualized embedding parameters and response format.

Best Practices

Encoding formats, similarity metrics, normalization, and error handling.

Agent API

Learn more about the Responses API used for answer generation.