LangChain Explained: Getting Started, Documentation and Examples

LangChain explained with Python examples, official documentation and AI workflows connecting prompts, language models, tools, documents and agents.

LangChain is an open-source framework for developing applications and AI agents powered by large language models (LLMs). It helps developers connect AI models with prompts, external data, tools and application logic through reusable software components.

Instead of building every integration from scratch, developers can use LangChain to create chatbots, document question-answering systems, research assistants and intelligent automation workflows.

This guide explains what LangChain is, how to get started, where to find LangChain official documentation and how to learn LangChain for free through practical Python examples and educational resources.

Key Takeaways

  • LangChain is an open-source AI application development framework, not an AI model.
  • It supports multiple language model providers and external integrations.
  • Developers can build AI agents, retrieval systems and conversational applications.
  • Python and TypeScript are supported.
  • Official documentation and free courses are available online.
  • The framework is free, but model APIs and hosting may involve costs.

What Is LangChain?

LangChain is a development framework that simplifies the creation of language model-powered applications. It provides standardized interfaces for interacting with language models, managing prompts, connecting tools and organizing AI application workflows.

The framework enables developers to work with different AI models without completely redesigning their application whenever they change model providers.

User Input

Question, instruction or request

LangChain

AI application development framework

Prompts
Models
Tools
Middleware
Language Models

Hosted or local models

External Data

Documents and databases

External Tools

Functions and APIs

Application Response

Generated answer or processed result

Conceptual LangChain application architecture. Individual applications may use only the components they require.

For example, a document assistant built with LangChain could retrieve relevant information from a collection of documents, provide that information to a language model and generate an answer based on the retrieved context.

LangChain manages the application integrations, while the selected language model performs the language generation and other supported model operations.

How Does LangChain Work?

LangChain connects different application components through standardized interfaces. A simple application may only send a prompt to a model, while an advanced application may retrieve documents, call tools and perform multiple processing steps.

1
Receive User Input

Accept a question, instruction or application request.

2
Prepare the Prompt

Combine instructions with user input and any required context.

3
Invoke the Language Model

Send the prepared information to the selected model.

4
Use Tools or Data When Required

Retrieve information or execute supported operations. Agent workflows may repeat model and tool calls.

5
Return the Response

Process and deliver the result to the application or user.

Simplified workflow. Retrieval may also occur before the first model call, depending on the application design.

This modular approach allows developers to start with a basic model integration and gradually introduce retrieval, tools, structured output and more complex agent behavior.

Core Components of LangChain

Understanding the following components helps beginners identify which parts of the LangChain ecosystem are useful for their applications.

Chat Models

Provide a standardized interface for sending messages to supported language models and receiving responses.

Prompts and Messages

Define instructions, user input and contextual information passed to the language model.

Tools

Expose functions or external operations that applications and compatible models can use.

Agents

Combine models and tools to determine and execute actions based on a request.

Middleware

Customizes agent execution through mechanisms such as processing hooks, model selection and intervention policies.

Conversation State

Maintains relevant messages and application information across an interaction when configured.

Retrieval Components

Help applications locate relevant information from documents, search indexes and external knowledge sources.

Structured Output

Allows supported models and applications to return information using a defined data structure.

Additional ecosystem packages provide document loaders, text splitters, embedding integrations and vector stores for applications that work with external knowledge. These components are particularly useful for retrieval-augmented generation (RAG).

Getting Started With LangChain

The easiest way to get started with LangChain is to build a simple Python application that sends a request to a language model. You can then extend the application with prompts, tools and agents.

Prerequisites

  • Python 3.11 or newer for this tutorial.
  • Basic knowledge of Python functions, variables and dictionaries.
  • A terminal or development environment such as VS Code.
  • Access to a supported language model.
  • An API key if required by the selected model provider.

Step 1: Create a Virtual Environment

A virtual environment keeps your project dependencies separate from other Python applications.

Terminal
python -m venv .venv

Activate on Windows PowerShell:

.\.venv\Scripts\Activate.ps1

Activate on macOS or Linux:

source .venv/bin/activate

Step 2: Install LangChain

Install LangChain and the OpenAI integration package used in the following examples.

Terminal
python -m pip install -U langchain langchain-openai

LangChain supports multiple model providers through dedicated integration packages. Install the package appropriate for the provider you intend to use.

Step 3: Configure Your API Key

The following examples use a hosted OpenAI model. Configure your API key as an environment variable instead of placing it directly in your Python source code.

Windows PowerShell:

$env:OPENAI_API_KEY = "your-api-key"

macOS or Linux:

export OPENAI_API_KEY="your-api-key"

Replace the placeholder with your actual API key in your local environment. These commands configure the variable for the current terminal session. For sensitive credentials, use a secure credential manager or protected configuration method where possible.

Important: Never publish API keys in source code, screenshots or public repositories. LangChain is free to install, but hosted model requests may incur usage charges.

LangChain Examples for Beginners

The following examples demonstrate three fundamental LangChain development tasks: interacting with a language model, creating reusable prompts and building a simple tool-enabled AI agent.

These examples use modern LangChain 1.x-style APIs. They are instructional examples and have not been executed in a live model environment. Model availability and package compatibility should be checked before running them.

Example 1: Basic Language Model Interaction

This example initializes a chat model, sends a question and prints the generated response. Save the code in a file named basic_example.py.

basic_example.py Python
from langchain_openai import ChatOpenAI

# Initialize the model
model = ChatOpenAI(
    model="gpt-4.1-mini"
)

# Send a request
response = model.invoke(
    "Explain LangChain in two sentences."
)

# Display the response
print(response.content)

Run the Python file:

python basic_example.py
Illustrative Output

LangChain is an open-source framework for developing applications powered by language models. It provides reusable components for connecting models with prompts, data and tools.

The actual response may differ. This example demonstrates how LangChain provides a consistent interface for interacting with a chat model. If the example model is unavailable in your account, substitute a supported model identifier.

Example 2: Creating a Reusable Prompt Template

Prompt templates allow developers to reuse a set of instructions with different input values. This is useful for educational assistants, content generation and other applications that repeatedly perform similar operations.

prompt_example.py Python
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

model = ChatOpenAI(
    model="gpt-4.1-mini"
)

# Create a reusable prompt
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a beginner-friendly AI tutor."),
    ("human", "Explain {topic} using simple language.")
])

# Connect the prompt and model
chain = prompt | model

# Provide a topic
response = chain.invoke({
    "topic": "machine learning"
})

print(response.content)

The prompt contains a system instruction and a variable named {topic}. Changing the topic allows the same application to generate explanations for different subjects.

Topic Input

Machine learning

Prompt Template

Reusable instructions

Language Model

Generated explanation

The pipe operator connects the prompt and model into a runnable sequence. When invoked, the prompt is formatted using the supplied input before being sent to the model.

Example 3: Building a Simple AI Agent

LangChain’s create_agent interface enables developers to combine a language model with callable tools. The following example creates an agent with a simple multiplication function.

agent_example.py Python
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI

# Define a custom tool
def multiply(a: int, b: int) -> int:
    """Multiply two integers."""
    return a * b

model = ChatOpenAI(
    model="gpt-4.1-mini"
)

# Create the agent
agent = create_agent(
    model=model,
    tools=[multiply],
    system_prompt="Use the multiplication tool for multiplication requests."
)

# Invoke the agent
result = agent.invoke({
    "messages": [
        {
            "role": "user",
            "content": "What is 15 multiplied by 8?"
        }
    ]
})

# Display the final message
print(result["messages"][-1].content)
Expected Result

15 multiplied by 8 equals 120.

The agent can request execution of the multiplication function, receive its result and use that result to produce a final answer. Actual tool selection depends on the model and agent execution.

User Request

Multiply 15 by 8

LangChain Agent

Determines whether a tool is required

Multiplication Tool

multiply(15, 8) returns 120

The tool result returns to the agent, which prepares the final response.

Final Answer

120

This example introduces a fundamental concept of agentic AI: combining language model decisions with controlled external operations.

LangChain Official Documentation

The LangChain official documentation is the primary resource for installation instructions, framework concepts, model integrations, API references and practical tutorials.

Because LangChain’s packages and interfaces evolve, beginners should use documentation that matches their installed framework version rather than relying entirely on older tutorials.

Official Resource What You Can Learn
Documentation Portal Overview of the framework and related development tools.
Python Documentation Core concepts, model integrations and agent development.
Installation Guide Dependencies, package installation and setup.
Python Quickstart Build and configure a first LangChain agent.
API Reference Detailed classes, functions and method specifications.
Learning Tutorials Practical application development and retrieval examples.
Start With the Official Quickstart

Follow the installation requirements, create a basic agent and explore additional features as your development skills improve.

Open LangChain Quickstart →

How to Learn LangChain Free

You can learn LangChain for free through official documentation, structured online courses and practical coding exercises. Beginners do not need to purchase a commercial course to start building basic applications.

Free Course Content

LangChain Academy

Official structured courses covering agent development, models, tools, LangGraph and related technologies.

Explore courses →
Free Course

LangChain Essentials

A Python-focused quickstart course covering agents, messages, tools, streaming and structured output.

Access the course →
Free Documentation

Official Tutorials

Self-paced technical guides that explain how to develop language model applications and retrieval systems.

Explore tutorials →

Recommended LangChain Learning Roadmap

01
Learn Python Fundamentals

Understand functions, dictionaries, packages and environment variables.

02
Understand Language Models

Explore prompts, messages, tokens and model responses.

03
Build a Basic LangChain Application

Install the framework, configure a model and invoke it.

04
Practice Prompts and Structured Output

Create reusable instructions and predictable response structures.

05
Explore AI Agents and Tools

Build agents that can request controlled external operations.

06
Learn Retrieval and RAG

Connect language models with relevant document content and knowledge sources.

07
Test and Evaluate Applications

Inspect outputs, handle errors and evaluate application reliability.

LangChain Academy offers free educational course content, although its professional certification exam is a paid offering. Some exercises may also require model access, optional services or suitable local computing resources.

What Can You Build With LangChain?

LangChain can support several types of language model-powered applications, ranging from simple assistants to systems that retrieve information and perform controlled operations.

Application Practical Use
AI Chatbots Generate responses and support conversational interactions.
Document Assistants Answer questions using retrieved document information.
AI Agents Use models and tools to perform supported operations.
Research Assistants Retrieve, organize and summarize relevant information.
Customer Support Retrieve relevant knowledge and assist with customer inquiries.
Data Extraction Convert unstructured information into defined output formats.
Workflow Automation Combine language models with application logic and external tools.

LangChain and Retrieval-Augmented Generation (RAG)

Retrieval-augmented generation combines relevant external information with language model generation. LangChain provides integrations that help developers build retrieval pipelines using documents, embeddings, vector stores and retrievers.

Document Indexing
Documents
Text Chunks
Embeddings
Vector Store

Stores indexed document representations

Query and Retrieval

Find document passages relevant to the user’s question

Language Model

Processes the question and retrieved context

Context-Based Answer

Response generated using retrieved information

Document preparation tools such as Docling can help convert documents into structured content before that information is indexed by a retrieval system.

RAG can improve access to relevant information, but it does not guarantee factual accuracy. Retrieval quality, source reliability and generated responses still require evaluation.

LangChain vs LangGraph vs LangSmith

LangChain, LangGraph and LangSmith serve different purposes within the same AI development ecosystem. Understanding their roles helps developers choose the appropriate tool for their application.

Technology Primary Purpose Best Suited For
LangChain Application and agent development framework. Model integrations, tools and configurable AI agents.
LangGraph Low-level orchestration and stateful agent execution. Complex workflows, persistence and custom control flow.
LangSmith Agent engineering and management platform. Tracing, evaluation, debugging, monitoring and deployment.
Deep Agents Higher-level agent harness. Complex tasks involving planning and delegated work.

LangChain’s agent implementation is built on LangGraph, providing higher-level abstractions for common agent development tasks. Developers can use LangGraph directly when they need greater control over workflow execution.

For beginners, LangChain is a practical starting point. LangGraph becomes useful when an application needs more customized orchestration, while LangSmith helps developers inspect and improve application behavior.

Common LangChain Errors and Solutions

Beginners may encounter package, authentication or model configuration errors when following a LangChain tutorial.

Problem Possible Solution
ModuleNotFoundError Check that the required integration package is installed in the active Python environment.
Authentication Error Check that the correct API key is configured and available to the application.
Model Not Found Verify the model identifier and your provider account’s model access.
Import or Compatibility Error Compare installed package versions with the documentation used by the tutorial.
Rate Limit or Quota Error Review provider usage limits, billing status and request frequency.

To inspect your installed LangChain package versions, run:

python -m pip show langchain langchain-openai langchain-core

After confirming that your application works, record compatible dependency versions to make the project easier to reproduce.

Benefits and Limitations of LangChain

LangChain simplifies many aspects of AI application development, but it is not necessary for every project. Its usefulness depends on the complexity and requirements of the application.

Benefits Limitations
Open-source development framework. Requires programming and integration knowledge.
Supports multiple model providers. Provider-specific capabilities may differ.
Reusable application components. APIs and dependencies require version management.
Supports AI agents and tools. Agent decisions and tool execution require appropriate controls.
Supports external knowledge integrations. Retrieved information and generated outputs require validation.
Free documentation and learning resources. Hosted models, deployment and optional services may incur costs.

For a simple application that only sends requests to one language model, using the provider’s API directly may be sufficient. LangChain becomes particularly useful when a project needs reusable components, multiple integrations, retrieval or agent workflows.

Frequently Asked Questions

What is LangChain and what is it used for?

LangChain is an open-source framework for building language model-powered applications. It is used to integrate models, prompts, tools and external information for applications such as chatbots, document assistants and AI agents.

Is LangChain free to use?

Yes. LangChain’s open-source framework can be installed and used for free. However, hosted model APIs, cloud infrastructure and optional commercial services may involve usage charges.

Where can I find LangChain official documentation?

The official documentation is available at docs.langchain.com. It provides installation guides, framework concepts, quickstarts, integration documentation and practical tutorials.

How can I learn LangChain for free?

You can learn LangChain for free through LangChain Academy, official documentation and practical coding exercises. Begin with Python fundamentals, model interaction, prompt templates and simple AI agents.

Is LangChain suitable for beginners?

Yes. LangChain provides reusable interfaces and official quickstart guides that make it accessible to developers with basic programming knowledge. Beginners should start with simple model interactions before exploring more complex agents.

Do I need Python to learn LangChain?

No. LangChain supports both Python and TypeScript. Python is a popular starting point for AI application development, while JavaScript and TypeScript developers can use the corresponding LangChain packages and documentation.

Does LangChain require an API key?

LangChain itself does not require an API key. Hosted language model providers and certain external integrations may require credentials. Compatible local models can be used without a hosted model API key.

Can I use LangChain with local AI models?

Yes. LangChain supports compatible local model integrations, including models served through tools such as Ollama. Local inference requires suitable hardware, model availability and appropriate software configuration.

What is the difference between LangChain and LangGraph?

LangChain provides higher-level interfaces for developing language model applications and agents. LangGraph provides more detailed control over stateful workflows, execution logic and agent orchestration. They can be used together.

Can I build AI agents using LangChain?

Yes. LangChain provides agent development interfaces that combine language models with callable tools and configurable execution behavior. Developers can use these interfaces to build agents that retrieve information and perform supported operations.

Is LangChain necessary for every LLM application?

No. A direct model API may be sufficient for simple applications. LangChain is more useful when developers need reusable components, multiple integrations, retrieval pipelines or configurable agent workflows.

Conclusion

LangChain is an open-source framework that helps developers build applications and agents using language models, tools and external information. Its modular architecture supports everything from basic model interactions to more advanced retrieval and agent workflows.

The best way to get started is to follow the LangChain official documentation, practice simple Python examples and gradually explore more advanced components. Free resources such as LangChain Academy make it possible to learn the framework without purchasing a course.

Start with a small application, understand each component and introduce additional integrations only when your project requires them.

About the author

Stacey Riley

Stacey Riley is a contributor at AI Genius Works, covering artificial intelligence, intelligent automation, robotic process automation (RPA), enterprise technology, and digital transformation. Her published articles explore practical applications of AI across information technology, banking, insurance, pharmaceutical operations, and business process automation. Her writing focuses on explaining technology concepts through accessible language, practical examples, and real-world business use cases, helping readers understand the opportunities, challenges, and limitations of artificial intelligence and automation.