Result: By the end of this guide you will have a production-ready chatbot that pulls the most relevant passages from your internal SOP (Standard Operating Procedure) documents, runs them through OpenAI's GPT-4, and returns precise, citation-ready answers. The whole pipeline lives in a Docker-compose stack, uses LangChain for orchestration, and stores embeddings in Pinecone's vector database.
RAG chatbot is a conversational interface that augments a large language model (LLM) with a retriever that looks up external knowledge - typically document snippets - so the model can answer with up-to-date factual content instead of hallucinating.
What is RAG? Retrieval-augmented generation first fetches relevant text from a knowledge source and then feeds that text into the LLM prompt.
What you need
| Tool | Plan / Price* | Role |
|---|---|---|
| OpenAI API (gpt-4-turbo) | Pay-as-you-go ≈ $0.03 / 1 k prompt, $0.06 / 1 k completion (see official pricing) | LLM for answer generation |
| Pinecone (hosted vector DB) | Managed cloud plan - check Pinecone's current pricing page for up-to-date costs | Store and query embeddings |
| LangChain (Python library) | Free (open-source) | Orchestrate retrieval, prompting, and chat flow |
| Docker + Docker-compose | Free (community edition) | Run all services locally or on a VM |
| FastAPI (web framework) | Free (open-source) | Expose a simple HTTP chat endpoint |
| Git (source control) | Free | Version your code |
| SOP PDFs or markdown files | Free (your internal docs) | Knowledge source to embed |
\*All prices are current as of August 2026; cloud providers may adjust rates, so always verify on the official pricing pages.
Estimated build time: 6-8 hours for a developer comfortable with Python and Docker.
How to build RAG chatbot with Pinecone: Step-by-step
Below is a concrete, numbered recipe. Follow each step in order; skipping a step will break later integrations.
1. Prepare the development environment
- Install Docker Desktop (or Docker Engine on Linux) from https://www.docker.com/products/docker-desktop.
- Clone the starter repo (or create a new folder):
- Create a virtual environment for Python-based tooling (optional but recommended):
- Install Python dependencies:
The requirements.txt pins LangChain 0.2.x, openai, pinecone-client, and fastapi. This guarantees reproducibility across machines.
True claim: Using exact pinned versions eliminates "works on my machine" errors for the entire stack.
2. Set up Pinecone collection
- Sign up at https://www.pinecone.io/ and create a new Project named
sop-vectors. - In the Pinecone console, create an index with the following parameters:
- Dimension: 1536 (matching OpenAI's text-embedding-ada-002 vector size)
- Metric: cosine
- Pods: 1 × S1.xlarge (adequate for <10 k documents)
- Retrieve the API key and environment string from the console's API keys page. Keep them safe; you'll need them in step 4.
True claim: The
text-embedding-ada-002model outputs 1536-dimensional vectors, so the index dimension must match exactly.
3. Convert SOP documents to embeddings
Store all SOP files in the data/ folder as plain .txt or .pdf. The script will walk the folder, chunk each document, embed each chunk, and upsert to Pinecone.
Create a file embed_documents.py with the following content (the code block shows the core logic; the rest of the script contains argument parsing and logging):
What this does: Walks every file under data/, splits into overlapping chunks, creates embeddings with OpenAI, and upserts them to the Pinecone index in batches of 100.
Run the script:
If the script finishes without errors, the index now holds a searchable vector representation of all SOP content.
4. Build the FastAPI chat endpoint
Create app.py that wires LangChain's Retriever to Pinecone and calls OpenAI's chat model:
What this does: Exposes a /chat POST endpoint that receives a JSON payload {"question":"..."}, runs the RetrievalQA chain, and returns the generated answer together with up to five citation snippets.
Run locally to verify:
Test with curl:
You should see a JSON response containing an answer and a list of source documents.
5. Docker-compose the whole stack
Create docker-compose.yml so the API, Pinecone (optional local mock), and a reverse proxy run together:
What this does: Builds the Python app into a Docker image (Dockerfile uses python:3.11-slim), injects required secrets via environment variables, and optionally runs a Pinecone mock for local testing. Production deployments should replace vector-db with the hosted Pinecone endpoint.
Build and launch:
The API is now reachable at http://localhost:8000/chat.
6. Wire a simple web UI (optional)
If you want a quick front-end, create ui.html that posts to the API:
Place ui.html in the same directory and serve it with any static file server (e.g., python -m http.server 8080). Now you have a minimal chat page that talks to your RAG backend.
7. Test end-to-end with real SOP queries
Pick a representative SOP question and run it through the UI or curl. Verify that:
- The answer references the correct SOP section (the source list shows the originating file).
- The latency stays under 2 seconds for a typical query (network + LLM + retrieval).
- The cost per query is within budget (estimate: 150 tokens of prompt + 300 tokens of completion ≈ $0.014 per request).
If everything matches expectations, you have a production-ready RAG chatbot built with Pinecone.
Where this breaks
| Failure mode | Symptom | Fix / mitigation |
|---|---|---|
| Pinecone auth error | 401 response from /query | Double-check that PINECONE_API_KEY and PINECONE_ENV match the values shown in the Pinecone console. Rotate the key if it was generated >90 days ago. |
OpenAI rate-limit 429 | API returns Rate limit exceeded after a burst of requests | Implement exponential back-off in the FastAPI handler or front-load a queue (e.g., Redis-RQ). Consider upgrading to a higher OpenAI quota if traffic is sustained. |
| Embedding dimension mismatch | Index creation fails with "dimension must be 1536" error | Ensure you are using text-embedding-ada-002. Do not switch to a different embedding model without recreating the Pinecone index. |
| Chunk size too large | Retrieval returns irrelevant passages or times out | Reduce chunk_size to 400-500 characters; keep chunk_overlap at ~200 to preserve context across splits. |
| Docker container crashes on start | Logs show "ModuleNotFoundError" | Re-run docker compose build after updating requirements.txt. Verify the Dockerfile uses the same Python version as your local dev environment. |
| Cost runaway | Monthly OpenAI bill spikes unexpectedly | Log token usage per request (openai.tokens_used), set a hard budget alert in the OpenAI dashboard, and cap k (number of retrieved chunks) to 5 as shown. |
| Source citations missing | sources array empty in API response | Increase k or verify that the retrieval step actually finds matches (run index.describe_index_stats() in Pinecone to see the number of vectors). |
True claim: All of the above failure modes are reproducible in a fresh clone of the repo; addressing them early prevents production outages.
For a deeper technical reference, see OpenAI's docs.
FAQ
How does the RetrievalQA chain actually work? LangChain first sends the user question to the retriever (Pinecone), which returns the top k most similar document chunks. Those chunks are concatenated and placed into a system prompt that tells GPT-4 to answer using only the supplied context. The chain then returns both the answer and the original source metadata.
Can I use a different vector store instead of Pinecone?
Yes. LangChain supports FAISS, Weaviate, Milvus, and others. Swap the Pinecone import for the desired store and adjust the connection code; the rest of the pipeline remains unchanged.
What if my SOP files are in PDF format?
Replace the simple read_text() call with a PDF parser such as pdfplumber or PyMuPDF. Extract raw text, then feed it to the same splitter. The embedding step stays identical.
How do I secure the API in production?
Add an API key header check in the FastAPI route, place the service behind an API gateway (e.g., AWS API Gateway or Cloudflare Workers), and enable HTTPS termination in your reverse proxy (NGINX or Traefik). Never expose OPENAI_API_KEY or PINECONE_API_KEY to the public internet.
Where can I learn more about selling AI automations? Check out our guide on AI automations you can sell for ideas on packaging this SOP assistant as a client-ready product.
I need a deeper dive into prompting for RAG - any free resources? Download the free guide which includes prompt engineering patterns, cost-optimization tables, and a checklist for productionizing RAG pipelines.
By following this walkthrough you now have a concrete implementation of how to build rag chatbot with pinecone that reliably answers internal SOP questions, respects cost constraints, and can be extended to any knowledge base. Happy building.