Skip to main content

Document Q&A with Embeddings

A self-contained retrieval-augmented generation (RAG) system that ingests documents, generates contextualized embeddings for semantic search, and produces grounded answers using the Agent API.

Features

  • Ingest plain-text documents and automatically split them into chunks
  • Generate document-aware embeddings using pplx-embed-context-v1-4b
  • In-memory vector store with numpy cosine similarity search
  • Answer generation via the Agent API with anthropic/claude-sonnet-4-6
  • Full working pipeline: load, chunk, embed, query, answer

Architecture

Indexing: Load documents, split into overlapping chunks, embed with contextualized embeddings, store in memory. Query: Embed the user question, compute cosine similarity, retrieve top-k chunks, generate an answer with the Agent API.
Contextualized embeddings produce higher-quality representations than standard embeddings for document chunks because the model understands that chunks belong to the same document.

Installation

Usage

Save the full code below to document_qa.py and run:
For interactive mode:

Full Code

Example Output

For production workloads, replace the in-memory numpy index with a dedicated vector database such as Pinecone, Weaviate, or Qdrant. The embedding and retrieval logic remains the same.
Contextualized embeddings require that chunks within each document are sent in their original sequential order. Shuffling chunks will degrade embedding quality.

Limitations

  • The in-memory store is suitable for prototyping but will not scale to large collections. Use a vector database for production.
  • Chunk size and overlap may need tuning for your documents. Shorter chunks improve precision; longer chunks preserve context.
  • The pplx-embed-context-v1-4b model has a 32K token context window per document.
  • Answer quality depends on retrieval quality. If the wrong chunks are retrieved, the answer will reflect that.