AI·Frontier
← Back to Home
AI Tutorials

Getting Started with LangChain: Build Your First Agent in 20 Minutes

Getting Started with LangChain: Build Your First Agent in 20 Minutes

Your First LangChain App in Twenty Minutes

LangChain has a reputation for being overwhelming. The documentation grows faster than anyone can read it, the ecosystem is crowded with integrations, and the loudest voices online keep arguing about whether it is still the right tool. Strip all of that noise away and LangChain is really just a thin layer of Python that makes it easier to chain together building blocks like models, prompts, and memory. In this tutorial you will build a genuinely useful first application in about twenty minutes: a small conversational assistant that remembers your name, calls the weather, and hands off to a fallback model when needed. You will learn the three core abstractions along the way, and you will understand enough to start reading the deeper docs with confidence.

The best way to start with any framework is to ignore ninety percent of it. I am going to show you exactly the ten percent you need for a working app, and I will point out the places where beginners routinely get stuck so you can avoid them.

A diagram showing how a LangChain chain connects a prompt template to a model to an output parser

Understand the Three Core Building Blocks

Everything in LangChain is composed of a handful of small concepts. If you learn these three, most of the rest of the library starts to make sense.

  • Models: the AI engines you call, whether that is a cloud chat model, an open-weight model on your own server, or an embedding model for text search.
  • Prompts: templates that turn user input and context into the exact text you send to a model, so your calls stay consistent and you stop typing prompt glue by hand.
  • Chains and loaders: the plumbing that moves data from one step to the next, including tools that read files, call APIs, or route requests to different models.

Keep that mental model. When the docs throw a new class name at you, ask yourself which of these three buckets it belongs to, and the learning curve flattens dramatically.

Set Up Your Environment

You need Python 3.9 or newer and a free API key from any model provider. The example below uses the OpenAI-compatible interface, but the pattern transfers to virtually any provider. Create a virtual environment and install the core package and the provider integration.

python -m venv .venv
.venv/bin/activate
pip install langchain langchain-openai

Put your key in a .env file and install python-dotenv so you never hard-code secrets into source files. A surprisingly large share of beginner bugs come from pasted keys or environment variables that never loaded.

Step 1: Build a Prompt That Carries Context

The first block is a prompt template. Instead of writing a full string every time, you declare the placeholders and LangChain fills them in.

from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages([
  ("system", "You are a friendly assistant. The user's name is {name}."),
  ("human", "{question}"),
])

Notice that the template carries the user's name as context rather than a hard-coded phrase. This is the key to making an assistant feel coherent across turns, and it is the seed of the memory patterns you will meet later.

Step 2: Attach a Model and a Tool

Next, define the model and give it a tool to call. A tool is just a Python function with a @tool decorator, which tells LangChain it is safe to call automatically.

from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
model = ChatOpenAI(model="gpt-4o-mini")
@tool
def get_weather(city: str) -> str:
    # a human-readable description tells the model when to call this
    if city.lower() == "paris":
        return "18C, light drizzle"
    return "22C, sunny"

The docstring matters. Modern models use function descriptions, not just signatures, to decide when to call a tool. Write the docstring like a human would describe the tool to a colleague.

Step 3: Wire It Into a Chain and Test

Now combine the pieces with the pipe operator or the LCEL syntax. This is the part that feels magical the first time you see it, because the whole pipeline is a small, readable object.

from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages([
  ("system", "You are helpful. The user's name is {name}."),
  ("human", "{input}"),
  ("placeholder", "{agent_scratchpad}"),
])
agent = create_tool_calling_agent(model, [get_weather], prompt)
executor = AgentExecutor(agent=agent, tools=[get_weather])
result = executor.invoke({"input": "Hi, what is the weather in Paris?", "name": "Sam"})

Run it and you should get a friendly answer that mentions Paris and the drizzle. If a call fails, the two most common causes are a missing environment variable and a prompt that forgot the agent_scratchpad placeholder, so check those first.

A terminal window showing the printed output of a working LangChain agent that called the weather tool

Step 4: Add Simple Memory

A one-off agent is neat, but a chat needs to remember. LangChain gives you memory classes that store the conversation history and feed it back into the next prompt automatically.

from langchain_core.messages import HumanMessage, AIMessage
history = [] # a simple in-memory store for this session
def chat(user_input):
    prompt_vars = {"input": user_input, "name": "Sam", "history": history}
    resp = executor.invoke(prompt_vars)
    history.append(HumanMessage(content=user_input))
    history.append(AIMessage(content=resp["output"]))
    return resp["output"]

For a real app you would swap the list for a database-backed store so memory survives restarts. The pattern, though, is identical: append the turn, then hand the whole history to the model on the next call.

Debugging Tips That Save Hours

LangChain wraps things in objects, which makes stack traces harder to read. When something misbehaves, do not re-read the whole chain. Turn on verbose logging or call the inner model directly with the exact prompt text to isolate the problem.

  • Set verbose=True on the executor to print every internal model call.
  • Test the prompt template alone before assuming the model is the issue.
  • Test the tool function alone before wiring it into the agent.
The fastest way to debug a LangChain app is to shrink the surface area. Test the prompt, the model, and the tool in isolation, then wire them back together one at a time.

Where to Go Next

You now have a conversational agent with tools, context, and memory. The natural next steps are replacing the toy weather tool with a real API call, swapping the model for a local open-weight one using llama.cpp or Ollama, and reading about document loaders if you want to feed files into your prompt. Each of those builds on the three core blocks you just learned, so nothing you learned today goes to waste.