Create a safe, temporary working directory
How to Build an AI Agent with LangChain: Step-by-Step Tutorial
The shift from large language models (LLMs) that merely generate text to AI agents that can take action is one of the most significant developments in modern software engineering. An agentic system perceives its environment, makes decisions, and uses tools to achieve specific goals, moving beyond simple question-and-answer chatbots . LangChain, an open-source framework, has emerged as the standard for building these sophisticated applications by connecting LLMs with external data, tools, and other LLMs .
This tutorial provides a comprehensive, step-by-step guide on how to build an AI agent with LangChain. You'll learn the foundational concepts and walk through a practical implementation, equipping you to create your own autonomous agents capable of performing real-world tasks.
What You'll Learn
By the end of this tutorial, you'll understand the core principles of agentic AI and the LangChain framework. You'll be able to set up a development environment, connect to an LLM, define custom tools, and build a functional agent using the modern create_agent API. You will build and run a complete AI agent that can interact with a local file system based on natural language commands, giving you a practical foundation for creating more complex automations.
1. LangChain Fundamentals and Key Concepts
Before diving into the code, it's essential to understand what an AI agent is and how LangChain facilitates its creation. At its core, an agent is a system that uses an LLM as its reasoning engine. The agent receives a user request, prompts the LLM to decide on an action, executes that action (often by calling a tool), and then processes the result to formulate a response. This cycle continues until the task is complete .
LangChain provides a standard framework to implement this reasoning loop, most notably through its support for the ReAct (Reason + Act) framework. LangChain is a high-level tool built on LangGraph, a lower-level orchestration framework that gives you granular control over the agent's workflow and state .
To build an agent with LangChain, you need four main components:
- An LLM: The reasoning engine of your agent.
- Tools: Functions that allow the agent to interact with the outside world, like APIs, databases, or a file system .
- The Agent Loop: The "brain" orchestration layer that manages the LLM, tools, and state.
- Memory (Checkpointing): The ability to persist the agent's state, allowing it to remember past interactions within a conversation thread .
2. Setting Up Your Development Environment
To get started, you need to install LangChain and its core dependencies. This tutorial demonstrates the process in Python, but the concepts and high-level patterns are similar for TypeScript users .
First, ensure you have Python 3 and Pip installed on your system. For Debian/Ubuntu-based systems, you can use the following commands. For other operating systems, follow the appropriate installation method .
sudo apt update
sudo apt install python3 python3-pip
Next, install the primary LangChain packages. The langchain package is the core framework. langchain-community contains tools maintained by the community, and langgraph is needed for the modern agent creation API .
pip install langchain langgraph langchain-community
3. Integrating a Large Language Model
The first step in building your agent is connecting it to an LLM. LangChain supports dozens of model providers, including Google Gemini, OpenAI, Anthropic, and more . For this tutorial, we'll use Google's Gemini model.
You'll need an API key from the Gemini console. Once you have it, you can install the Google GenAI integration package and set up your environment .
pip install -qU "langchain[google-genai]"
Now, you can write the Python code to initialize the model. The getpass module is used to securely prompt for your API key .
import getpass
import os
from langchain.chat_models import init_chat_model
from langchain_core.messages import HumanMessage, SystemMessage
if not os.environ.get("GOOGLE_API_KEY"):
os.environ["GOOGLE_API_KEY"] = getpass.getpass("Enter API key for Google Gemini: ")
model = init_chat_model("gemini-2.0-flash", model_provider="google_genai")
You can test the setup by invoking the model with a simple query .
response = model.invoke("When did the French Revolution start?")
print(response.content)
4. Defining Tools for Your Agent
Tools are what make agents powerful. They allow the LLM to perform actions beyond generating text . In this tutorial, we will build an agent that can manage files on your local computer using LangChain's FileManagementToolkit .
The FileManagementToolkit is part of the langchain-community package, which you have already installed. This toolkit allows you to specify which file operations the agent can perform, such as reading, writing, and listing files .
Import the necessary modules and define the tools. It is a critical security practice to restrict the agent to a temporary directory rather than giving it free rein over your entire file system .
from langchain_community.agent_toolkits import FileManagementToolkit
from tempfile import TemporaryDirectory
working_directory = TemporaryDirectory()
# Initialize the toolkit with selected tools and a root directory
tools = FileManagementToolkit(
root_dir=str(working_directory.name),
selected_tools=["read_file", "write_file", "list_directory"],
).get_tools()
5. Building the Agent with create_agent
With the LLM and tools ready, you can now build the agent. The modern and recommended way to build agents in LangChain is by using the create_agent function .
This function takes your model and a list of tools and creates an agent executor that manages the reasoning loop. It simplifies the process, eliminating the need to manually create a ReAct agent and an executor .
from langchain.agents import create_agent
# The "model" and "tools" variables are from the previous steps.
agent = create_agent(
model=model,
tools=tools
)
This single line of code creates a sophisticated agent. The agent uses the model to decide which tool to call based on the user's input. It can handle chaining multiple tool calls together to achieve a complex task .
⚠️ Important: While LangChain can be used with older agent creation methods like
create_react_agent, thecreate_agentAPI is the modern, recommended approach and should be your default choice for building new agents .
6. Running Your First Agent
Now that the agent is built, you can run it by invoking it with a user message. The following commands will demonstrate the agent's ability to interact with the file system.
Start by asking the agent to list the files in the current working directory. At this point, the directory is empty .
input_message = {"role": "user", "content": "List files in the current working directory"}
response = agent.invoke({"messages": [input_message]})
for message in response["messages"]:
message.pretty_print()
Next, instruct the agent to create a file named sample-file.txt .
input_message = {"role": "user", "content": "Create a file named sample-file.txt"}
response = agent.invoke({"messages": [input_message]})
for message in response["messages"]:
message.pretty_print()
Finally, ask the agent to list the files again. It will now show that sample-file.txt exists .
input_message = {"role": "user", "content": "List files in the current working directory"}
response = agent.invoke({"messages": [input_message]})
for message in response["messages"]:
message.pretty_print()
As you can see, the agent successfully interpreted the natural language commands, called the appropriate tools (list_directory, write_file), and provided feedback on the actions taken. This is a basic but powerful demonstration of how to build an AI agent with LangChain.
7. Adding Memory to Your Agent
One of the key limitations of a stateless agent is that it forgets all context after an invocation is complete. To create a conversational agent that can remember past interactions, you need to add memory. This is achieved through a "checkpointer" that saves the agent's state .
LangGraph provides a MemorySaver class, which is a simple in-memory checkpointer. In a production environment, you would use a more robust option like PostgresSaver or the MongoDB-based checkpointer, but MemorySaver is perfect for testing and development .
First, import and initialize the checkpointer .
from langgraph.checkpoint.memory import MemorySaver
checkpointer = MemorySaver()
Next, re-create your agent, passing the checkpointer as an argument .
agent_with_memory = create_agent(
model=model,
tools=tools,
checkpointer=checkpointer
)
To use the memory, you must specify a thread_id in the configuration. This thread_id acts as a conversation ID, allowing the agent to maintain separate memory for each distinct conversation .
config = {"configurable": {"thread_id": "user-123"}}
agent_with_memory.invoke(
{"messages": [{"role": "user", "content": "My name is Alice"}]},
config=config
)
result = agent_with_memory.invoke(
{"messages": [{"role": "user", "content": "What is my name?"}]},
config=config
)
# The agent responds: "Your name is Alice."
print(result["messages"][-1].content)
This simple addition enables your agent to hold conversations with context, making it feel much more intelligent and useful.
8. Beyond the Basics: Multi-Agent Systems
As you advance, you may encounter tasks too complex for a single agent. LangChain supports building sophisticated multi-agent systems, where specialized agents collaborate to solve problems. This is a powerful architectural pattern for complex workflows .
Subagents is a core multi-agent pattern where a main supervisor agent coordinates several specialized subagents, calling them as tools. For instance, one subagent might be responsible for research, another for content creation, and a third for reviewing work .
| Pattern | How it works |
|---|---|
| Subagents | A main agent coordinates subagents as tools. All routing passes through the main agent, which decides when to invoke each subagent. |
| Handoffs | Behavior changes dynamically based on state, where a tool call triggers a switch to a different agent or configuration. |
| Skills | Specialized prompts and knowledge are loaded on-demand into a single agent's context. |
| Router | A routing step classifies the input and directs it to one or more specialized agents for processing . |
Choosing the right pattern is crucial. For example, a subagents architecture is excellent for parallel execution and distributed development, while a handoff pattern is more efficient for repeat user requests in a single conversation . Using the subagents pattern in a personal assistant application allows for context isolation—each subagent works on a task in a clean context window, preventing the main agent's memory from being bloated .
Sources
- Chris Tozzi. "Build an AI agent with LangChain in this beginner tutorial." TechTarget, Sep 2025.
- "Quickstart" LangChain Official Documentation.
- "Multi-agent" LangChain Official Documentation.
- "Workflows and agents" LangChain Official Documentation.
- "langchain-fundamentals" LangChain Skills Documentation, GitHub.
- "How to Build an AI Agent with LangChain and LangGraph: Build an Autonomous Starbucks Agent." freeCodeCamp, Dec 2025.
- "Subagents" LangChain Official Documentation.
- "LangChain Python Tutorial: A Complete Guide for 2026." The JetBrains Blog, Mar 2026.
— Editorial Team
No comments yet.