How to Build an AI Agent With LangChain: Tools, Memory and Workflows
Learn how to build an AI agent with LangChain: define tools, add memory with a checkpointer and wire a workflow. A practical step-by-step guide for developers.
By Galactic News Editorial · Published 2026-11-28T04:41:00+00:00 · Updated 2026-11-28T04:41:00+00:00
How to Build an AI Agent With LangChain: Tools, Memory and Workflows
To build an AI agent with LangChain, call create_agent with a model, a list of tools and a system prompt. Add a checkpointer for memory and middleware for retries and limits. This guide walks through each step in Python, from setup to a working agent you can run.
What you need before you start
You need Python 3.10 or later. LangChain 1.x no longer supports Python 3.9. You also need a key from a model provider. The examples here use OpenAI, but any supported chat model works.
Install the packages with pip:
pip install langchain langchain-openai langchain-tavily langgraph-checkpoint-sqlite python-dotenv fastapi uvicornThese packages give you the LangChain agent API, the OpenAI integration, web search via Tavily, a SQLite checkpointer for memory and FastAPI for serving the agent later.
LangChain v1 changed the agent API. create_agent is now the standard high-level entry point. It runs on the LangGraph runtime. Older tutorials use AgentExecutor or create_react_agent. Those no longer import from the langchain package. Start new projects with create_agent.
How to build an AI agent with LangChain in 7 steps
Step 1: Set up the project
Create a project folder and a virtual environment. Keep secrets in a .env file. Never hard-code API keys in your source.
mkdir langchain-agent && cd langchain-agent
python -m venv .venv
source .venv/bin/activateYour .env file holds the model key and any search keys. Load it with load_dotenv() at the top of each script.
Step 2: Define tools the agent can call
Tools are plain Python functions with the @tool decorator. Each tool needs a clear name, a description and typed inputs. The model reads the description to decide when to call it.
from pydantic import BaseModel, Field
from langchain.tools import tool
class WeatherInput(BaseModel):
location: str = Field(description="City and country, e.g. Lahore, Pakistan")
@tool(args_schema=WeatherInput)
def get_weather(location: str) -> str:
"""Return the current weather for a location."""
return f"Weather data for {location} goes here."Good tool design matters more than model choice. Give each tool one job. Use a typed schema so inputs are validated. Return short, structured text. The agent passes tool output back into its reasoning, so keep results compact.
Step 3: Create the agent with create_agent
Pass the model, the tools and a system prompt to create_agent. The system prompt sets the agent's role and rules.
from dotenv import load_dotenv
from langchain.agents import create_agent
from langchain_tavily import TavilySearch
load_dotenv()
agent = create_agent(
model="gpt-4o-mini",
tools=[TavilySearch(max_results=3), get_weather],
system_prompt="You are a helpful assistant. Use tools when you need fresh information.",
)Run it with a message and read the result:
result = agent.invoke({"messages": [{"role": "user", "content": "What is the weather in Lahore?"}]})
print(result["messages"][-1].content)The agent reasons, picks a tool, reads the result and answers. That loop is the core of every LangChain agent.
Step 4: Add memory with a checkpointer
Memory in LangChain v1 comes from a checkpointer. It saves the state of each conversation under a thread_id. Pass the same thread id on each call and the agent remembers the conversation.
from langgraph.checkpoint.memory import InMemorySaver
checkpointer = InMemorySaver()
agent = create_agent(
model="gpt-4o-mini",
tools=[get_weather],
checkpointer=checkpointer,
)
config = {"configurable": {"thread_id": "user-123"}}
agent.invoke({"messages": [{"role": "user", "content": "I live in Lahore."}]}, config)InMemorySaver suits local examples. Production systems should use a database-backed checkpointer such as Postgres or SQLite. The SQLite saver stores state in a local file. Define thread lifecycle and cleanup rules, and keep tenant data isolated when you serve more than one user.
Long-term memory is a separate concern. Facts that must survive across threads belong in a store or your own database. Thread state is short-term memory. Do not mix the two.
Step 5: Add middleware for production control
Middleware is the control plane for LangChain v1 agents. It replaces the scattered controls that older code spread across executor parameters and callbacks. Useful middleware includes model-call and tool-call limits, tool retry, model fallback, conversation summarisation and human-in-the-loop approval.
Set a tool-call limit so a runaway agent cannot loop forever. Add human approval before tools that change data, send messages or spend money. Add summarisation so long conversations do not blow up the context window.
Step 6: Connect the agent to your own data
Most real agents need more than web search. Add a retrieval tool that searches your own documents. Index them into a vector store, then expose a search function as a tool. The agent calls it like any other tool.
LangChain's documentation shows a full retrieval pattern: load documents, split them into chunks, embed them and store them in a vector store. The agent then retrieves relevant chunks at query time. Keep the retrieved text out of the main context where you can, and let subagents analyse chunks in parallel.
Step 7: Test, observe and deploy
Test the agent offline before you ship it. Write a small evaluation set: a list of questions and the tool each one should trigger. Check that the agent picks the right tool and handles failures.
Observe runs with LangSmith or plain logging. Watch for wrong tool choices, repeated calls and long loops. Fix the system prompt or the tool descriptions first. Those two inputs drive most agent behaviour.
Deploy the agent behind an API. FastAPI works well. Expose one endpoint that takes a message and a thread id. Keep the agent instance in memory and pass the thread id through. Add rate limits and authentication before you open it to users.
Common mistakes to avoid
- Using AgentExecutor in new code. It is legacy. Use
create_agent. - Vague tool descriptions. The model picks tools from their descriptions. Write them like documentation, not labels.
- No call limits. Always cap model and tool calls per run.
- Secrets in code. Use environment variables. Never commit keys.
- Skipping evaluation. A demo that works once is not a product. Test the tool-selection logic on real questions.
Bottom line
Build your LangChain agent with create_agent, typed tools and a checkpointer for memory. Add middleware for limits and approval. Connect your own data with a retrieval tool. Test tool selection before you deploy. That stack covers most real agent projects without extra framework code.