Python Environment Setup for RAG

Create a virtual environment, manage API keys safely and install the libraries used in this tutorial.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 0 · Lesson 3 of 9 · Beginner

Python Environment Setup for RAG

Create a virtual environment, manage API keys safely and install the libraries used in this tutorial.

This lesson sets up the Python environment used in every lesson of the tutorial. It takes about ten minutes and you only need to do it once.

1. Install Python

You need Python 3.10 or later. Check your version:

python --version

On Windows, if python is not found, try py --version, or install Python from python.org and tick "Add python.exe to PATH" during setup.

2. Create a project folder and virtual environment

A virtual environment keeps this tutorial's libraries separate from other Python projects on your computer.

mkdir rag-tutorial
cd rag-tutorial
python -m venv .venv

Activate it. On Windows (PowerShell):

.venv\Scripts\Activate.ps1

On macOS or Linux:

source .venv/bin/activate

Your prompt now starts with (.venv). Activate the environment again every time you open a new terminal.

3. Install the libraries

Download requirements.txt into your project folder and install everything with one command:

pip install -r requirements.txt

The main libraries are:

LibraryUsed for
anthropicCalling Claude, the LLM used for generation
sentence-transformersRunning embedding and reranking models locally
numpyVector maths
chromadb, faiss-cpuVector stores
rank-bm25Keyword search
pypdf, python-docx, beautifulsoup4Loading documents
pydantic, fastapi, uvicornStructured output and serving APIs

Later lessons install a few extra libraries when they need them, and say so.

4. Get an API key and keep it safe

Create an API key in the Claude Console (platform.claude.com). Treat it like a password: anyone with the key can spend money on your account.

Never paste the key into your code. Store it in an environment variable instead. The simplest way for a project is a .env file:

.env
ANTHROPIC_API_KEY=your-key-here

Then make sure the file is never committed to Git:

.gitignore
.env
.venv/

Load the file at the start of your scripts with python-dotenv:

from dotenv import load_dotenv
load_dotenv()  # copies the values from .env into the environment

import anthropic
client = anthropic.Anthropic()  # finds ANTHROPIC_API_KEY automatically
Security

If a key is ever committed to a repository or shared in a chat, delete it in the Console and create a new one. Removing it from the file later does not help, because it stays in the Git history.

5. Add the shared helper module

Many lessons need the same two operations: ask the LLM a question and turn text into embeddings. Instead of repeating that code, download rag_helpers.py into your project folder. Here is the core of it:

rag_helpers.py (excerpt)
import anthropic
import numpy as np

MODEL = "claude-opus-5-5"
EMBED_MODEL = "BAAI/bge-small-en-v1.5"
QUERY_PREFIX = "Represent this sentence for searching relevant passages: "

client = anthropic.Anthropic()
_embedder = None

def get_embedder():
    global _embedder
    if _embedder is None:
        from sentence_transformers import SentenceTransformer
        _embedder = SentenceTransformer(EMBED_MODEL)
    return _embedder

def embed(texts, query=False):
    """Return L2-normalised embeddings, shape (n, 384)."""
    if isinstance(texts, str):
        texts = [texts]
    if query:
        texts = [QUERY_PREFIX + t for t in texts]
    return get_embedder().encode(texts, normalize_embeddings=True, convert_to_numpy=True)

def ask(prompt, system=None, max_tokens=4000, effort="low"):
    """Send one prompt to Claude and return the reply text."""
    params = {
        "model": MODEL,
        "max_tokens": max_tokens,
        "messages": [{"role": "user", "content": prompt}],
        "output_config": {"effort": effort},
        "betas": ["server-side-fallback-2026-07-01"],
        "fallbacks": "default",
    }
    if system:
        params["system"] = system
    response = client.beta.messages.create(**params)
    if response.stop_reason == "refusal":
        raise RuntimeError("The model declined this request.")
    return "".join(b.text for b in response.content if b.type == "text")

A few details worth knowing:

  • The embedding model BAAI/bge-small-en-v1.5 is free, runs on a normal laptop CPU and is downloaded automatically (about 130 MB) the first time you use it.
  • The query prefix is recommended by the BGE model authors: queries get a short instruction, documents do not.
  • Server-side fallback. If the main model declines a request, the API retries it on a fallback model inside the same call. If every model declines, the helper raises an error instead of returning an empty answer.
  • Effort defaults to low, which keeps RAG answers fast and cheap. Pass effort="medium" or "high" for harder questions.

6. Check that everything works

check_setup.py
from dotenv import load_dotenv
load_dotenv()

from rag_helpers import ask, embed

vectors = embed(["Hello world", "Hi there"])
print("Embedding shape:", vectors.shape)          # (2, 384)
print("Similarity:", float(vectors[0] @ vectors[1]))
print(ask("Reply with the single word: ready"))
Embedding shape: (2, 384)
Similarity: 0.83
ready

Your similarity number may differ slightly. If you see an authentication error, check that the .env file is in the folder you run the script from.

Key takeaways

  • Use a virtual environment per project and install from requirements.txt.
  • Keep the API key in an environment variable or a git-ignored .env file, never in code.
  • The rag_helpers.py module gives you ask() and embed(), used throughout the tutorial.