LangChain is a framework for Python and JavaScript that lets you build applications powered by large language models (LLMs). Sending a single prompt to a model takes only a couple of lines of code. However, real apps also need reusable instructions, access to your own data, and a way for the model to call your Python code. In this tutorial, you’ll explore how LangChain’s Python library handles each of these.
Say a group of hospitals just handed you a spreadsheet full of patient reviews, together with a short request: Find out what patients are saying about us. You could read through every row yourself, but by the time you’re done, the next batch of reviews will probably have arrived. Instead, you’ll teach an LLM to do the reading for you.
Along the way, you’ll cover chat models, prompt templates, chains, retrieval, and agents. Step by step, you’ll build up to a RAG app that answers questions about what patients said and an agent that picks the right tool to look up exact facts.
By the end of this tutorial, you’ll understand that:
- LangChain offers a modular interface to LLM providers like OpenAI, so switching models doesn’t mean rewriting your app.
- A
SystemMessagesets a chat model’s behavior, aHumanMessagecarries the user’s input, and anAIMessageholds the model’s reply. - Prompt templates turn prompts into reusable recipes, and the pipe (
|) operator in LCEL chains them with models, parsers, retrievers, and any other runnable. - In retrieval-augmented generation (RAG), a retriever uses semantic search to pull the most relevant reviews and ground the model’s answers in real context.
- An agent lets the language model choose which tools to call instead of following steps you define in code.
To get the most out of this tutorial, you should be comfortable with Python functions, dictionaries, and comprehensions and have some familiarity with decorators and type hints. You don’t need any prior experience with LLMs, but a basic understanding of embeddings and vector databases will help in the RAG section. If you don’t have all of this background knowledge yet, that’s okay! You might learn more by going ahead and getting started.
Each section covers one feature. You’ll run most examples in the Python REPL and a few as scripts from the command line. You’ll start by preparing your environment and installing LangChain.
Get Your Code: Click here to download the free sample code you’ll use to build a RAG app and a tool-calling agent that answer questions about patient reviews with LangChain.
Take the Quiz: Test your knowledge with our interactive “LangChain Tutorial: From Prompts to RAG and AI Agents” quiz. You’ll receive a score upon completion to help you track your learning progress:
Interactive Quiz
LangChain Tutorial: From Prompts to RAG and AI AgentsCheck your grasp of LangChain in Python, from chat messages and prompt templates to LCEL chains, RAG retrieval, and tool-calling agents.
AI Agent From Scratch Live Course: Want to see what frameworks like LangChain do under the hood? In Real Python’s Build an AI Agent From Scratch in Python live course, you write the agent loop by hand, then recognize every piece of it in the tools you already use. Join the waitlist to hear about the next dates.
Set Up a LangChain Environment
To get started, create a folder for this tutorial’s Python files. Set up a virtual environment to install the required tools and libraries. Make sure you have Python 3.10 or later.
Activate your virtual environment and install the following libraries:
(.venv) $ python -m pip install langchain==1.4.3 langchain-openai==1.6.6
With this command, you install the langchain library, which is the main subject of this tutorial. You also install langchain-openai to use OpenAI’s services.
You’ll also need to install python-dotenv to help you manage environment variables:
(.venv) $ python -m pip install python-dotenv==1.2.3
With this package, you can load environment variables from .env files into your Python environment. You’ll find this handy for keeping your API key out of your code.
You’ll use OpenAI’s models, so make sure you have an OpenAI account, a valid API key, and credits in your account. Running the examples in this tutorial might cost only a small amount, but every model and embedding call is billed.
Create a file called .env in your working directory and add your key to it:
OPENAI_API_KEY=<YOUR_OPENAI_API_KEY>
Every script or REPL session in this tutorial calls dotenv.load_dotenv() to read the .env file and load your key into the environment before using any OpenAI model.
Note: Your .env file contains your API key in plain text. If your working directory is under version control, add .env to your .gitignore file so you don’t accidentally commit your key. If you commit your key and publish the repository, revoke the key and generate a new one.
You can run each section’s code on its own, but the concepts build on each other, so work through the sections in order if you’re new to LangChain. In the RAG and agent sections, you’ll create scripts and use reviews.csv from the tutorial’s materials.
You’re now ready to start exploring LangChain!
Talk to an LLM Through LangChain
At the core of LangChain is the large language model (LLM) that powers its features. LangChain provides a modular interface for working with LLM providers, such as OpenAI, Anthropic, Google, and Hugging Face, as well as local models. In most cases, all you need is an API key from the provider to start using the LLM with LangChain.
In LangChain, you talk to an LLM through a model object, such as ChatOpenAI or ChatAnthropic. Instead of sending raw text, you usually send the model a list of messages, which represent the input and output of models.
Every message object has .type and .content attributes. The .type attribute tells the LLM who is sending the message ("system", "human", or "ai"), and .content holds the message itself.
You can also write messages as plain dictionaries, where a role key is equivalent to type:
{"role": "human", "content": "..."}
Here are the most commonly used message objects:
SystemMessage: A message that tells the language model how to behaveHumanMessage: A message from the user interacting with the language modelAIMessage: A message from the language model
Note that not all providers support SystemMessage. There’s also a ToolMessage, which carries the result of a tool call, but you’ll learn more about tools when you get to the section about building agents.
Note: In practice, you can refer to a SystemMessage as a system prompt and a HumanMessage as a user prompt. You can refer to an AIMessage as an AI response.
To try chat models in LangChain, start a REPL session and run the following code:
>>> import dotenv
>>> from langchain_openai import ChatOpenAI
>>> dotenv.load_dotenv()
True
>>> chat_model = ChatOpenAI(
... model="gpt-6-luna",
... output_version="responses/v1"
... )
You first import dotenv and ChatOpenAI. Then, you call dotenv.load_dotenv(), which reads your .env file and loads OPENAI_API_KEY into the environment, where ChatOpenAI looks for it.
Next, you instantiate ChatOpenAI using GPT-6 Luna as the target LLM. The output_version argument tells the class to return replies in the format of OpenAI’s Responses API.
Note: OpenAI offers a range of models with varying prices, capabilities, and performance. GPT-6 Luna is currently OpenAI’s most efficient model for focused, high-volume tasks, which makes it a low-cost fit for the examples in this tutorial.
To use chat_model, run the following code in the same REPL session:
>>> from langchain_core.messages import HumanMessage, SystemMessage
>>> messages = [
... SystemMessage(
... content="""You're an assistant knowledgeable about
... healthcare. Only answer healthcare-related questions."""
... ),
... HumanMessage(content="What is a normal resting heart rate?"),
... ]
>>> response = chat_model.invoke(messages)
>>> type(response)
<class 'langchain_core.messages.ai.AIMessage'>
>>> response.text
"For most adults, a normal resting heart rate is **60–100 beats per minute
(bpm)**. Well-trained athletes may normally have rates below 60 bpm, and
children's typical rates vary by age.\n\nMeasure it after sitting or lying
quietly for a few minutes. If your rate is repeatedly outside your usual
range—or comes with symptoms such as dizziness, fainting, chest pain, or
shortness of breath—contact a healthcare professional."
In this block, you import HumanMessage and SystemMessage. You then define a list with a SystemMessage and a HumanMessage and run them through chat_model with chat_model.invoke(), storing the result in response.
Under the hood, chat_model sends a request to OpenAI’s Responses API serving gpt-6-luna, and the response comes back as an AIMessage, as the call to type() confirms. You read the model’s reply from that message with its .text attribute.
As you can see, the chat model answers the question What is a normal resting heart rate? provided in the HumanMessage. You might be wondering what the chat model does with the SystemMessage in this context. Notice what happens when you ask the following question:
>>> messages = [
... SystemMessage(
... content="""You're an assistant knowledgeable about
... healthcare. Only answer healthcare-related questions."""
... ),
... HumanMessage(content="How do I change a tire?"),
... ]
>>> chat_model.invoke(messages).text
"I can't walk you through the mechanical steps, but I can help you avoid
injury: if you're near moving traffic, on soft or sloped ground, or unsure
the car is stable, stay clear and call roadside assistance. Keep passengers
away from traffic, and don't get under a vehicle supported only by a jack.
If anyone is injured, call emergency services."
Your healthcare assistant stays in its lane! It won’t explain how to change a tire, but it still makes sure that you don’t get hurt while you wait for roadside assistance.
As described earlier, the SystemMessage tells the model how to behave. In this case, you tell the model to only answer healthcare-related questions, so it declines to walk you through the tire change. Using text instructions to control how an LLM interacts with the user is powerful and forms the foundation for creating customized chatbots through prompt engineering.
While message classes provide a useful abstraction and help you give the LLM the right kind of message, you can also pass plain Python strings into chat models:
>>> chat_model.invoke("What is blood pressure?").text
"Blood pressure is the force of blood pushing against the walls of your
arteries as your heart pumps and rests. It's written as two numbers, in
millimeters of mercury (mmHg):\n\n- **Systolic** (top number): pressure
when the heart pumps.\n- **Diastolic** (bottom number): pressure when the
heart relaxes between beats.\n\nFor example, **120/80 mmHg** means a
systolic pressure of 120 and a diastolic pressure of 80."
In this code block, you pass the string "What is blood pressure?" directly to chat_model.invoke(), and LangChain wraps it in a HumanMessage for you.
You can still steer the model by adding instructions to the string, such as "You're an expert in medicine". However, those instructions become part of the user’s message, so the model treats them as part of the question rather than as rules for how to behave. A SystemMessage gives your instructions higher priority.
Keep in mind that chat models don’t remember previous calls, so you need to include the SystemMessage with every request that should follow those rules.
Next, you’ll learn a modular way to build reusable prompts (SystemMessage or HumanMessage objects) dynamically, so you can write your instructions once and reuse them with intentional variations.
Create Reusable Prompt Templates
In a real app, some parts of your messages may stay the same while other parts change on every call. For example, a user question may require a specific context on every turn. Prompt templates let you write the fixed part once and fill in the rest at runtime.
You can think of a prompt template as an f-string that you can carry around and fill in later. That’s also where the analogy breaks down: an f-string fills in its values right away, while a template waits until you hand it the values, and it can check that you didn’t forget any of them.
PromptTemplate: Fill in a Single String
Say you want to classify patient reviews as positive or negative. The instruction is the same for every review, and only the review text changes, so you can turn the prompt into a PromptTemplate instance with a {review} placeholder.
Start a new REPL session in your working directory, set up a chat model, and create the template:
>>> import dotenv
>>> from langchain_core.prompts import PromptTemplate
>>> from langchain_openai import ChatOpenAI
>>> dotenv.load_dotenv()
True