11. RAG & Tool Calling Environment Setup#
A fast, conceptual revision guide for 11-rag-setup. Focused on why the RAG and tool-calling environment is structured the way it is — virtual environment isolation, secret management, the four-layer dependency stack, local vs. cloud model roles, and fail-fast pre-flight verification — without boilerplate setup commands.
Environment Isolation & Secret Management#
Revision Notes#
Reference files: Setup_Guide_for_Learners.html, .env.example, env_template.txt
Concept#
AI engineering projects depend on fast-moving, heavy libraries (such as PyTorch, LangChain, and ChromaDB) alongside paid cloud API keys. Rather than installing packages globally or pasting credentials into source code, this module establishes two foundational boundaries: a project-scoped virtual environment (.venv) and a shared, untracked .env file at the root workspace (00-basics).
Key Mental Models#
- Virtual environment as a private dependency box: Creating
.venvinside the main00-basicsfolder isolates the exact package versions needed by the RAG modules (12-rag-...through15-rag-...) so they never collide with other Python projects on the machine. - Upward
.envdiscovery viaload_dotenv(): Placing a single.envfile in the parent00-basicsfolder allows any script inside11-rag-setupor downstream RAG folders to loadOPENAI_API_KEYautomatically, becausepython-dotenvsearches the current directory and walks upward through parent folders. - Templates vs. live secrets:
.env.exampleandenv_template.txtare safe-to-share blueprints documenting required variables (OPENAI_API_KEY), while the real.envfile stays local and is never pasted into code, screenshots, chat, or version control. - Interpreter alignment across runtimes: Activating
.venvin a terminal only affects that terminal session. Interactive notebooks (.ipynb) maintain their own Python kernel selection and must explicitly point to the same.venvinterpreter.
Trade-Offs & Pitfalls#
- Forgotten activation on new terminals: Opening a fresh shell resets
PATHto the system Python; running scripts without reactivating.venvtriggers false import errors. - Notebook vs. CLI mismatch: A common trap is passing
check_setup.pyin the terminal but hittingModuleNotFoundErrorin VS Code Jupyter notebooks because the notebook kernel is still bound to a global Python instead of.venv. - File naming mistakes: Saving the secret file as
.env.txt(common on Windows when extensions are hidden) or placing it outside the directory hierarchy preventsload_dotenv()from findingOPENAI_API_KEY.
Code Reference#
import importlib
import os
import sys
def ok(msg):
print(f" [OK] {msg}")
def fail(msg):
print(f" [FAIL] {msg}")
# Fail fast on unsupported Python versions because LangChain, ChromaDB, and typing syntax
# (e.g. `dict | None` union types) require Python 3.10+.
print(f"Python {sys.version.split()[0]}")
if sys.version_info < (3, 10):
fail("Python 3.10 or newer is needed (3.11 - 3.13 recommended)")
sys.exit(1)
# 1) Libraries --------------------------------------------------------------
# Dynamically import every package used across Modules 11-15 so missing installs
# are caught upfront rather than mid-workshop.
print("\n1) Libraries")
missing = []
for name in ["openai", "langchain_core", "langchain_openai", "langchain_text_splitters", "langchain_experimental",
"langchain_chroma", "langchain_huggingface", "chromadb", "sentence_transformers", "gensim",
"rank_bm25", "gradio", "sklearn", "pandas", "dotenv"]:
try:
importlib.import_module(name)
ok(name)
except Exception as e:
fail(f"{name}: {e}")
missing.append(name)
if missing:
print("\nInstall the missing libraries with: pip install -r 11-rag-setup/requirements.txt")
sys.exit(1)
# 2) Free local models -----------------------------------------------------
# Pre-warm HuggingFace and Gensim caches before class so downloads (~160 MB total)
# do not stall live demos or fail on restricted Wi-Fi.
print("\n2) Free local models (the first time this takes a few minutes)")
from sentence_transformers import CrossEncoder, SentenceTransformer # noqa: E402
# Bi-encoder (384-dim) for fast dense retrieval across candidate documents
SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
ok("all-MiniLM-L6-v2 (sentence embeddings)")
# Cross-encoder for high-precision pairwise reranking of top-K candidates
CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")
ok("ms-marco-MiniLM-L6-v2 (reranker)")
import gensim.downloader as api # noqa: E402
# Static 50-dim GloVe word vectors used to demonstrate vector arithmetic analogies
api.load("glove-wiki-gigaword-50")
# -> KeyedVectors(vector_size=50, count=400000) cached in ~/gensim-data/
ok("glove-wiki-gigaword-50 (word vectors)")
# 3) OpenAI ------------------------------------------------------------------
# Walk up parent directories to locate a shared .env file and verify API credentials
# before making a lightweight connectivity check to OpenAI.
print("\n3) OpenAI API key")
from dotenv import load_dotenv # noqa: E402
load_dotenv() # looks for a .env file in this folder and in the folders above it
# -> True if a .env file was found and loaded into os.environ, else False
if not os.getenv("OPENAI_API_KEY"):
fail("OPENAI_API_KEY not found. Create the .env file in the main folder (see the setup guide).")
sys.exit(1)
from openai import OpenAI # noqa: E402
# ... (see full file: check_setup.py)
$ python 11-rag-setup/check_setup.py
Python 3.12.4
1) Libraries
[OK] openai
[OK] langchain_core
[OK] langchain_openai
[OK] langchain_text_splitters
[OK] langchain_experimental
[OK] langchain_chroma
[OK] langchain_huggingface
[OK] chromadb
[OK] sentence_transformers
[OK] gensim
[OK] rank_bm25
[OK] gradio
[OK] sklearn
[OK] pandas
[OK] dotenv
2) Free local models (the first time this takes a few minutes)
[OK] all-MiniLM-L6-v2 (sentence embeddings)
[OK] ms-marco-MiniLM-L6-v2 (reranker)
[OK] glove-wiki-gigaword-50 (word vectors)
3) OpenAI API key
[OK] OPENAI_API_KEY loaded and API reachable
All checks passed! You are ready for the RAG & Agent modules.
The RAG & Tool Calling Tech Stack#
Revision Notes#
Reference file: requirements.txt
Concept#
requirements.txt is not an arbitrary list of packages — it is a blueprint of a complete modern RAG and tool-calling architecture. Each dependency group corresponds to a distinct stage in turning raw documents into grounded, interactive LLM answers.
How the Four Stack Layers Map to RAG Capabilities#
- Cloud LLM & Orchestration Layer (
openai,langchain-core,langchain-openai):- Connects to hosted chat and embedding models via the OpenAI SDK.
- Provides LangChain's core abstractions for prompts, messages, runnables, and tool calling.
- Chunking, Vector Storage & Local Neural Models (
langchain-text-splitters,langchain-experimental,langchain-chroma,langchain-huggingface,chromadb,sentence-transformers):- Splits long documents into retrievable chunks (including structural and semantic splitting).
- Stores and queries dense vector embeddings locally in
chromadb. - Runs local neural encoders and rerankers via
sentence-transformers(which pulls in PyTorch under the hood — the main reason installation takes 5–15 minutes).
- Word Vectors, Lexical Search & Math Foundations (
gensim,rank_bm25,numpy,pandas,scikit-learn):gensimloads classic static word vectors to build intuition for vector similarity.rank_bm25provides sparse keyword/BM25 retrieval, enabling hybrid search (combining exact lexical matches with dense semantic vectors).numpy,pandas, andscikit-learnhandle vector math, similarity metrics, and tabular inspection.
- Interfaces, Notebooks & Configuration (
gradio,jupyter,python-dotenv):jupytersupports step-by-step interactive experimentation in.ipynbfiles.gradioturns Python RAG pipelines into local browser web apps (http://127.0.0.1:7860).python-dotenvinjects.envsecrets cleanly intoos.environ.
Key Mental Models#
- Why both dense and sparse tools are installed: Pure vector search excels at semantic meaning but can miss exact IDs, acronyms, or rare terms;
rank_bm25+chromadbtogether prepare the environment for hybrid retrieval. - Python version window: The stack enforces Python
>= 3.10(with3.11–3.13recommended) to balance modern typing/SDK requirements against pre-built binary wheel availability for native extensions like PyTorch andgensim.
Local Models vs. Cloud APIs in the RAG Pipeline#
Revision Notes#
Reference file: check_setup.py
Concept#
Production and learning RAG systems rarely use one model for everything. check_setup.py deliberately exercises three free local models alongside two cloud OpenAI endpoints, reflecting the division of labor between fast local retrieval/reranking and high-capability cloud generation.
How Each Model Fits the Pipeline#
The RAG workbench pairs cached, zero-cost local CPU models for vector intuition, dense retrieval, and cross-encoder reranking with OpenAI cloud endpoints for 1536-d embeddings and grounded tool-calling synthesis.
Key Mental Models#
- Bi-encoder vs. Cross-encoder:
sentence-transformers/all-MiniLM-L6-v2is a bi-encoder — it encodes queries and chunks independently into vectors so thousands of documents can be indexed once and searched quickly.cross-encoder/ms-marco-MiniLM-L6-v2is a cross-encoder reranker — it reads the query and a candidate chunk together for much higher relevance accuracy, making it ideal as a second-stage filter over the top retrieved candidates.
- Pre-warming model caches: Calling
SentenceTransformer(...),CrossEncoder(...), andgensim.downloader.load(...)during setup downloads model weights once to local disk cache so live sessions never stall waiting on multi-hundred-megabyte downloads. - Low-latency smoke testing:
check_setup.pyvalidates the chat model (gpt-6-luna) withreasoning_effort="none"and a tiny prompt, plus a single"hello"call totext-embedding-3-small(verifying a 1536-number vector), confirming both key validity and billing readiness at negligible cost.
Trade-Offs & Pitfalls#
- Local models: Zero per-call API cost and offline capability once cached, but require initial download bandwidth and local CPU/RAM.
- Cloud models: No local weight downloads and stronger reasoning/embedding capacity, but require network access, valid credentials, and funded API quota.
Three-Stage Pre-Flight Verification & Troubleshooting#
Revision Notes#
Reference files: check_setup.py, Setup_Guide_for_Learners.html
Concept#
Debugging an environment error in the middle of a RAG experiment wastes time because it is hard to tell whether a failure comes from your pipeline logic or a broken setup. check_setup.py acts as a fail-fast diagnostic gate that validates dependencies from cheapest/local to external/paid, exiting immediately at the first failing layer.
How the Verification Flow Works#
check_setup.py validates layers from free local runtime checks to external paid API calls, exiting immediately on the first broken requirement so workshop errors are caught before coding begins.
Common Failure Modes & Diagnostic Signals#
- Shell & OS environment issues:
'python' is not recognized— Python was installed without adding it toPATH(or requirespy/python3).- PowerShell script execution disabled — Windows blocks
.venvactivation scripts until the user execution policy allows local scripts (or Command Prompt is used instead).
- API key & billing failures:
OPENAI_API_KEY not found— Missing, misnamed (.env.txt), or misplaced.envfile.401 Incorrect API keyorinsufficient_quota— Invalid key string or an OpenAI account with zero credit/billing enabled.
- Network & firewall blocks:
- Corporate or campus Wi-Fi networks often block model weight downloads from Hugging Face or Gensim mirrors. Downloading once over an unrestricted network (such as a mobile hotspot) caches the weights locally so subsequent runs work anywhere.
- Running the three exercise formats:
- Notebooks (
.ipynb): Must select the.venvkernel before running cells. - Scripts (
.py): Run from inside their specific module folder so relative data paths resolve correctly. - Gradio apps (
.py): Served locally onhttp://127.0.0.1:7860; stop the running server (Ctrl+C) before launching the next app to avoid port conflicts.
- Notebooks (
How All Building Blocks Connect#
Revision Notes#
Every file in 11-rag-setup plays a specific role in preparing the shared foundation for the subsequent RAG modules (12-rag-... through 15-rag-...):
Setup_Guide_for_Learners.html: Defines the workspace layout (00-basicsas the root containing.venv,.env,11-rag-setup, and modules12–15), execution habits for notebooks/scripts/Gradio apps, and troubleshooting fixes.requirements.txt: Installs the full four-layer stack — cloud LLM/embeddings, chunking & ChromaDB vector storage, local neural & lexical retrieval tools, and notebook/Gradio UIs..env.example&env_template.txt: Provide the secret-management contract soOPENAI_API_KEYlives once in the root.envfile instead of being duplicated or exposed in code.check_setup.py: Acts as the automated gatekeeper — verifying Python version, all 15 libraries, local model weight caches (bi-encoder, cross-encoder, word vectors), and live OpenAI chat + embedding connectivity before any hands-on coding begins.
Quick Self-Check Questions#
Self-Check Questions#
Why should .env be placed in the main 00-basics folder rather than duplicated inside every RAG subfolder?
python-dotenv's load_dotenv() walks upward from the current working directory into parent folders, so a single .env in 00-basics serves 11-rag-setup and all 12-rag-... to 15-rag-... modules without duplicating secrets.
Why can check_setup.py pass in the terminal while a Jupyter notebook still raises ModuleNotFoundError?
Terminal activation of .venv does not automatically change a notebook's kernel; the notebook is still executing against a different Python interpreter until you explicitly select the .venv kernel.
Why does requirements.txt include both chromadb (with sentence-transformers) and rank_bm25?
chromadb and embedding models power dense semantic search, while rank_bm25 powers sparse keyword search — together they support hybrid retrieval.
What is the conceptual difference between the two MiniLM models downloaded by check_setup.py?
all-MiniLM-L6-v2 is a bi-encoder that turns text into standalone embedding vectors for fast retrieval, whereas ms-marco-MiniLM-L6-v2 is a cross-encoder reranker that scores (query, candidate) pairs jointly for higher relevance precision.
Why does check_setup.py download local models and make two tiny OpenAI calls in a specific order?
It follows a fail-fast sequence (Python version → imports → local model cache warm-up → live API test) so local issues are caught before hitting paid APIs, and large model weights are cached ahead of time.
What does a successful text-embedding-3-small check return, and why does the chat check pass reasoning_effort="none"?
text-embedding-3-small returns a 1536-dimensional embedding vector, and reasoning_effort="none" keeps the gpt-6-luna connectivity smoke test fast and minimal-cost.