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 todocument_qa.py and run:
Full Code
Example Output
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-4bmodel 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.