Generative AIBuilding with foundation modelsTools & frameworks

LangChain basics

16 minutes read

You can build an LLM application with nothing more than a provider's SDK or plain HTTP requests: you send a list of messages and get a response back. Many production systems, including agents and RAG pipelines, are written exactly that way. LangChain is an open-source library that sits on top of these APIs. You don't need it, but it's widely used, and its components give the common parts of LLM applications standard names and interfaces.

In this topic, you'll look at LangChain's main components and use them to call a model, keep a chat history, search your own documents, and create a simple agent.

What is LangChain and why?

LangChain is an open-source framework for building applications on top of LLMs. Its main idea is a consistent interface: a chat model, a prompt template, or a vector store is used the same way in your code, whichever provider is behind it.

Reasons you might use LangChain:

  • You build the application from reusable components (models, prompt templates, retrievers, tools) instead of writing every request and response by hand.

  • Switching providers usually means changing a package and a model name, not rewriting your code. LangChain has integrations for OpenAI, Anthropic, Hugging Face, Cohere, and many others.

  • It has ready-made integrations for data sources such as databases, APIs, and vector stores.

  • Its component names (chat model, retriever, tool, agent) are used across tutorials, documentation, and related tools, so they give you a common language for describing LLM systems.

The cost is size: LangChain adds dependencies and layers of abstraction between your code and the model API, which can make debugging harder. For a single model call, the provider's own SDK is often simpler.

The name comes from chaining: connecting components such as a prompt template, a model, and a retriever, so that the output of one becomes the input of the next. You'll see how this works in the next sections.

LLM interfaces

LangChain has packages for different model providers (like langchain-openai for OpenAI models) that act as an intermediary between your code and the model API. Instead of building requests and parsing responses yourself, you use these packages, which:

  • give different models a similar interface, so the calling code stays the same;

  • take common parameters such as temperature, max tokens, and the API key in the same form for every provider;

  • return the response as a message object, so you don't parse each provider's JSON yourself.

Here's the same request with and without LangChain:

try:
    response = requests.post(
        "https://api.groq.com/openai/v1/chat/completions",
        headers={"Authorization": f"Bearer {api_key}"},
        json={
            "model": "openai/gpt-oss-120b",
            "messages": [
                {
                    "role": "user",
                    "content": "What is LangChain",
                }
            ]
        }
    )
    response.raise_for_status()
    chat_completion = response.json()
    print(chat_completion["choices"][0]["message"]["content"])
except Exception as e:
    print(f"An error occurred: {e}")
llm = ChatGroq(model="openai/gpt-oss-120b", temperature=0.5, max_retries=2)

messages = [
    ("system", "You are an AI assistant that provides concise answers."),
    ("human", "What is LangChain?"),
]

response = llm.invoke(messages)
print(response.content)

Both versions send the same request. The LangChain version describes it as a model and a list of messages, and that code stays the same if you switch to another provider. LangChain has integrations for many model providers.

Full code
# install the required packages:
# pip install langchain-groq langchain-core python-dotenv

from langchain_core.prompts import PromptTemplate
from langchain_groq import ChatGroq
import dotenv

dotenv.load_dotenv()

llm = ChatGroq(model="openai/gpt-oss-120b", temperature=0.0, max_retries=2)

template = PromptTemplate.from_template("Explain {concept} in simple terms. Your output should be concise and informative.")

prompt = template.invoke({"concept": "black holes"})
response = llm.invoke(prompt)
print(response.content)

Messages

In chat models, messages are a structured conversation history. A message has at least two parts:

  • role: the sender (e.g., user, assistant, system, or tool)

  • content: the actual message or payload.

When calling models, you pass a list of messages, for example:

messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "What’s 2+2?"},
    {"role": "assistant", "content": "4"},
    {"role": "user", "content": "Now square it."}
]

When the model sees these messages, it generates the next assistant message. LangChain has a class for each message type, and you can pass a list of them to any chat model:

  • SystemMessage: the system prompt, defining some guidelines for the model to follow.

  • HumanMessage: represents the user's prompt and interactions.

  • AIMessage: the response from the model. In some cases, it might also include tool calls for models that support function calling.

  • ToolMessage: outputs from tool calls.

Here's an example using various messages:

from langchain_core.messages import HumanMessage, AIMessage, SystemMessage

system_prompt = SystemMessage("You are a helpful assistant.")
user_input = HumanMessage("What is 2+2?")

messages = [system_prompt, user_input]

final_response = llm.invoke(messages)
print(type(final_response)) # <class 'langchain_core.messages.ai.AIMessage'>

Models don't remember earlier requests. To hold a multi-turn conversation, you send the whole history with every call, and messages make that history easy to build:

from langchain_core.messages import SystemMessage, HumanMessage

# Start conversation with a system prompt
messages = [SystemMessage(content="You are a helpful assistant specializing in Python programming.")]

# Simulate multi-turn conversation
while True:
    user_input = input("Enter your query here: ")
    if user_input.lower() == "exit":
        break

    # Add user message
    messages.append(HumanMessage(content=user_input))

    # Get model response (returns an AIMessage)
    response = llm.invoke(messages)

    # Append model's reply to history
    messages.append(response)

    print(f"Assistant: {response.content}")

The history grows by two messages per turn, so the model always sees the whole conversation.

Working with data

LangChain also has components for getting your own data into an LLM application. You need them when the model should answer from information it wasn't trained on, such as internal documents. The main pieces are document loaders, text splitters, vector stores, and retrievers.

LangChain represents loaded data as Document objects: a piece of text (page_content) plus metadata such as its source. Document loaders convert raw data from files or other sources into such documents, and integration packages provide loaders for many data sources. For a plain text file, you don't need a loader at all: read the file and wrap its contents in a Document yourself. For example, to load planetary information from a text file:

from pathlib import Path
from langchain_core.documents import Document  # langchain-core comes with any LangChain package

# Load planetary data from a text file
path = "planets/mars.txt"
documents = [Document(page_content=Path(path).read_text(encoding="utf-8"), metadata={"source": path})]

print("Loaded documents:", documents)

After loading the data, you can use text splitters to break large documents into smaller, more manageable chunks. Splitting lets you send the model only the relevant parts of a long text and stay within its token limit. LangChain offers several ways to split documents. The table below summarizes these methods:

Method

Description

Splitter

Based on length (tokens or characters)

Split documents into chunks of a specified size.

Based on text structure

Text is split into units based on its paragraph, sentence, or word structure.

Based on the document's structure

Useful for documents with an inherent structure, such as JSON or Markdown.

Using CharacterTextSplitter
# Install the required package:
# pip install langchain-text-splitters tiktoken

from pathlib import Path
from langchain_text_splitters import CharacterTextSplitter
import tiktoken

# Load the contents of planets/earth.txt
planets_text = Path("planets/earth.txt").read_text(encoding="utf-8")

# Create a text splitter using the TikToken encoder.
# It splits the text at blank lines and merges the pieces into chunks of up to 50 tokens, with no overlap.
text_splitter = CharacterTextSplitter.from_tiktoken_encoder(
    encoding_name="cl100k_base", chunk_size=50, chunk_overlap=0
)

# Split the document text into chunks
texts = text_splitter.split_text(planets_text)
print(texts[0]) 

The next step involves using an embedding model to transform the raw text into vectors that capture its semantics. Here again, LangChain integrates with various providers, such as OpenAI, Google, and Cohere.

Next, you store the split chunks with their vector embeddings in a vector database for similarity search. Vector search and embeddings get their own topics later. Here, what matters is that LangChain's vector store integrations all work the same way: you give them an embedding model and the documents to embed.

# Install the required packages:
# pip install langchain-openai python-dotenv

import os
from langchain_openai import OpenAIEmbeddings
import dotenv

dotenv.load_dotenv()

# Initialize OpenAI embeddings.
embeddings_model = OpenAIEmbeddings(
    model="text-embedding-3-small",
    base_url="<base_url>", # in case you are using an LLM proxy
    api_key=os.getenv("OPENAI_API_KEY")
)

LangChain handles generating embeddings using the specified model and storing them in the database. Our example below uses Chromadb, which is free, open source, and runs locally:

# Install the required packages.
# pip install langchain-chroma

from langchain_chroma import Chroma

# Create a Chroma vector store from the loaded documents and embeddings.
db = Chroma(
    collection_name="hyper-collection",
    embedding_function=embeddings_model
)

# add documents
db.add_documents(documents=documents)

Finally, you can perform similarity searches and display the contents of the most relevant document:

# Perform a similarity search on the vector store with a sample query.
query = "What makes Mars unique?"
docs = db.similarity_search(query)

# Print the content of the most similar document.
print(docs[0].page_content)

You can also turn the vector store into a retriever, an object that takes a question in natural language and returns the most relevant documents:

retriever = db.as_retriever(search_kwargs={"k": 5})
retriever.invoke("Which planet is the largest?")

Other capabilities

LangChain also handles tool calling (function calling). You write a tool as a Python function, LangChain turns it into a schema the model understands, and it runs the calls the model asks for. Agents are built on this.

With structured output, you can make the model's response follow a predefined format, such as JSON, so your code can parse and validate it. You describe the format with a Pydantic model, a TypedDict, a JSON Schema, or a Python data class.

An agent is an LLM that calls tools in a loop until it finishes a task. LangChain's create_agent puts the model, the tools, and the instructions together. Here's a simple Reason and Act (ReAct) agent with one tool that converts an integer to binary:

# install packages and set your OpenAI API key in the environment: export OPENAI_API_KEY="sk-..." 
# pip install -U langchain langchain-openai

from langchain.agents import create_agent
def to_binary(n: int) -> str:
    """Convert a given integer to binary"""
    return bin(n)

agent = create_agent(
    model="openai:gpt-5.4-mini",
    tools=[to_binary],
    system_prompt="You are a helpful assistant that can help return the binary of integers.",
)
print(agent.invoke({"messages":[{"role":"user","content":"binary of 42"}]}))

Conclusion

LangChain gives the parts of an LLM application standard interfaces: chat models and messages, prompt templates, documents and text splitters, vector stores and retrievers, tools, and agents. You don't need it to build LLM applications, and it adds weight to a project. Its components and their names are, however, a common way to describe these systems, and code written with them is easier to move to another model provider.

9 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo