Sample code for the Real Python tutorial LangChain Tutorial: Build Your First Chains and Agents.
This is the langchain_intro project you build throughout the tutorial: a chat model, reusable prompt templates, an LCEL chain, a ChromaDB-backed review retriever (RAG), and a tool-calling agent that answers questions about patient reviews and hospital wait times.
langchain-tutorial/
│
├── data/
│ └── reviews.csv
│
├── langchain_intro/
│ ├── chatbot.py # final chat model + prompt templates + RAG chain + agent
│ ├── create_retriever.py # builds the ChromaDB vector database from reviews.csv
│ └── tools.py # get_current_wait_time() tool
│
├── .env.example
├── requirements.txt
└── README.md
-
Create and activate a virtual environment (Python 3.10 or later), then install the dependencies:
(venv) $ python -m pip install -r requirements.txt -
Copy
.env.exampleto.envand add your OpenAI API key:(venv) $ cp .env.example .envOPENAI_API_KEY=<YOUR_OPENAI_API_KEY>
-
Build the ChromaDB vector database from the reviews. Run this from the project root; it creates a
chroma_data/directory with the embedded reviews:(venv) $ python langchain_intro/create_retriever.py
Start a Python REPL from the project root so the langchain_intro package is importable and dotenv finds your .env:
>>> from langchain_intro.chatbot import review_chain
>>> review_chain.invoke("Has anyone complained about communication with the hospital staff?")
>>> from langchain_intro.chatbot import hospital_agent_executor
>>> response = hospital_agent_executor.invoke(
... {
... "messages": [
... {"role": "user", "content": "What is the current wait time at hospital C?"}
... ]
... }
... )
>>> response["messages"][-1].text