← All posts

RAG Made Practical: Building a Retrieval-augmented LLM with Pinecone

Learn how to avoid the dreaded dimension mismatch and build a production-ready RAG pipeline with Pinecone, LangChain, and OpenAI embeddings.

LLMs are powerful, but they often hallucinate or pull in outdated facts. Retrieval‑augmented generation (RAG) lets you tether an LLM to a curated knowledge base, giving you fresh, trustworthy answers without retraining the model.
When you try to build a RAG system you’ll quickly run into a silent but fatal error: the embedding dimension of your query vector doesn’t match the index. This article walks through that pitfall, shows how to set up a Pinecone‑backed RAG pipeline with LangChain, and gives you production‑ready tips.

TL;DR

  • Dimension mismatch happens when the embedding model used during indexing differs from the one used at query time.
  • Keep the same model (e.g., text-embedding-ada-002) for both ingestion and retrieval, and create the Pinecone index with that dimension.
  • A minimal end‑to‑end RAG stack: ingest → embed → store → query → retrieve → generate.
  • Optimize cost by batching embeddings, tuning top_k, and caching frequent queries.

Why RAG Matters for Real‑World Applications

  • Hallucination control – By grounding the LLM in your own documents, you reduce fabricated facts.
  • Compliance – You can restrict the model to only see data you’re allowed to share (e.g., internal policy manuals, regulated medical guidelines).
  • Up‑to‑date knowledge – Add new documents without retraining the model; the index simply grows.
  • Domain specificity – For niche fields like aviation safety or legal discovery, the retrieved snippets give the LLM the jargon it needs to answer accurately.

The Pinecone Dimension Mismatch: A Common Error

“The query embedding dimension does not match the index dimension.”

This error shows up when:

  • The embedding model used to create the index differs from the one used at query time (e.g., you indexed with text-embedding-ada-002 but query with text-embedding-3-large).
  • The index was created with an incorrect dimension parameter (e.g., dimension=128 instead of 1536).
  • You accidentally switch to a local model that outputs a different vector size.

Symptoms include:

  • All queries return empty results or throw the mismatch error.
  • Logs show the error repeatedly.
  • No documents are retrieved even though the index contains data.

Quick fix

  1. Verify the embedding model’s vector size (model.get_sentence_embedding_dimension() or check the API docs).
  2. Re‑create the Pinecone index with the correct dimension.
  3. Re‑index your data using the same model.
  4. Use the same model for both ingestion and query.

Choosing Embeddings and Index Configuration

Model Dimensionality Typical Use
text-embedding-ada-002 (OpenAI) 1536 Cost‑effective, general‑purpose
text-embedding-3-large (OpenAI) 3072 Higher semantic quality, higher cost
sentence-transformers/all-MiniLM-L6-v2 384 Local, GPU‑accelerated, lower cost

When you create a Pinecone index you must pass the exact dimension:

pinecone.Index.create(
    name="rag-index",
    dimension=1536,  # match the embedding model
    metric="cosine"
)

If you later decide to switch to a higher‑dimensional model, you’ll need a new index; Pinecone does not allow altering the dimension of an existing index.

Building the RAG Pipeline End‑to‑End

Below is a minimal, production‑ready skeleton. It uses LangChain to orchestrate ingestion, retrieval, and generation, OpenAI’s embedding API for vectors, and Pinecone as the vector store.

# rag_pipeline.py
import os
import pinecone
from langchain.document_loaders import DirectoryLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.vectorstores import Pinecone
from langchain.llms import OpenAI
from langchain.chains import RetrievalQA
from langchain.prompts import PromptTemplate

# 1. Initialise clients
pinecone.init(api_key=os.getenv("PINECONE_API_KEY"), environment="us-east1-gcp")
embeddings = OpenAIEmbeddings(model="text-embedding-ada-002")

# 2. Ingestion
loader = DirectoryLoader("docs/", glob="**/*.txt")
docs = loader.load()

text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
chunks = text_splitter.split_documents(docs)

# 3. Embed and upsert in batches
vectorstore = Pinecone.from_existing_index(
    index_name="rag-index",
    embedding=embeddings,
    text_key="text"
)

# If the index is empty, create it and upsert
if vectorstore.index.describe_index_stats()["total_vector_count"] == 0:
    vectorstore.add_documents(chunks)

# 4. Retrieval + Generation
prompt_template = PromptTemplate(
    input_variables=["context", "question"],
    template=(
        "You are a helpful assistant. Use the following context to answer the question.\n"
        "Context: {context}\n"
        "Question: {question}\n"
        "Answer:"
    ),
)

chain = RetrievalQA.from_chain_type(
    llm=OpenAI(model="gpt-3.5-turbo"),
    chain_type="stuff",
    retriever=vectorstore.as_retriever(search_kwargs={"k": 5}),
    prompt=prompt_template
)

# 5. Query
def answer_question(question: str) -> str:
    return chain.run(question)

if __name__ == "__main__":
    q = input("Ask a question: ")
    print(answer_question(q))

Explanation

  1. Clients – We initialise Pinecone and the OpenAI embedding client.
  2. Ingestion – All .txt files in the docs/ directory are loaded, split into 1000‑character chunks with 200‑character overlap to preserve context.
  3. Embedding & upsert – Chunks are embedded using the same model that will be used at query time, then uploaded to Pinecone in batches.
  4. Retrieval + Generation – A LangChain RetrievalQA chain stitches a prompt template, the vector store retriever, and the LLM. The retriever fetches the top‑5 relevant chunks.
  5. Query – The answer_question helper runs the chain, returning a grounded answer.

The code is intentionally concise; in production you’d add error handling, rate‑limiting, and logging.

Optimizing Performance and Cost

Technique Benefit Trade‑off
Batch embeddings Fewer API calls, lower latency Slightly more complex ingestion logic
Adjust k (top_k) Lower k → faster retrieval, higher k → more context Too low k may miss relevant docs
Cache frequent queries Reduce Pinecone load, lower latency Requires extra infrastructure (Redis, in‑memory cache)
Monitor token usage Prevent runaway costs Needs integration with OpenAI usage API

A practical rule of thumb: start with k=5, observe latency, and adjust. If you’re serving a high‑traffic API, consider a read‑only replica of the index to distribute load.

Deploying and Monitoring Your RAG Service

  1. Containerize
    FROM python:3.12-slim
    WORKDIR /app
    COPY requirements.txt .
    RUN pip install -r requirements.txt
    COPY . .
    CMD ["uvicorn", "api:app", "--host", "0.0.0.0", "--port", "8000"]
    
  2. FastAPI endpoint – Expose a single /ask route that calls answer_question.
  3. Health checks – Use Pinecone’s /health endpoint and expose a /metrics route for Prometheus.
  4. Logging – Log query latency, retrieval accuracy (e.g., top‑k hit rate), and error rates.
  5. Retry logic – Wrap Pinecone calls in a retry decorator with exponential backoff to handle transient network glitches.

Example FastAPI snippet:

# api.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI()

class QARequest(BaseModel):
    question: str

@app.post("/ask")
async def ask(req: QARequest):
    try:
        answer = answer_question(req.question)
        return {"answer": answer}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

Common Mistakes and Trade‑offs

Mistake Why it hurts Fix
Embedding drift – Using a newer OpenAI model for queries after indexing with an older one Dimension mismatch, inconsistent relevance Re‑index with the new model or keep the old one for queries
Over‑chunking – Splitting documents into too small pieces Retrieval noise, higher storage cost Aim for 500–1000 character chunks with overlap
Context overflow – Feeding too many chunks to the LLM Exceeds token limits, reduces performance Truncate to the first 2000 tokens or use a summarization step
Tiny k – Setting top_k to 1 or 2 Misses relevant documents Increase until retrieval quality plateaus
Ignoring cost – Using high‑dim embeddings without monitoring Unexpected bill Track token and API usage, set budget alerts

Balancing quality and cost often comes down to selecting the right embedding model. If your domain is highly technical, a higher‑dim model may pay off by reducing the number of queries needed to get a correct answer. For general knowledge, the cheaper ada model is usually sufficient.

Key takeaways

  • Consistency is critical: the embedding dimension used at ingestion must match the one used at query time.
  • Pinecone indices are immutable in dimension; create a new index if you change the embedding model.
  • LangChain simplifies orchestration but still requires careful chunking and prompt design.
  • Batch embeddings, tune k, and cache to keep latency low and costs predictable.
  • Deploy with FastAPI, Docker, and monitoring to make the RAG service production‑ready.
  • Watch out for common pitfalls like embedding drift, over‑chunking, and context overflow to maintain a reliable system.

FAQ

What causes the 'query embedding dimension does not match the index dimension' error?

It occurs when the embedding model used during indexing differs from the one used at query time, or the Pinecone index was created with an incorrect dimension parameter.

How do I verify the correct embedding dimension for a model?

Use model.get_sentence_embedding_dimension() or consult the API docs to confirm the vector size before creating the index.

Can I change the dimension of an existing Pinecone index?

No, Pinecone does not allow altering the dimension of an existing index; you must create a new index with the desired dimension.