Welcome to LangGraph
Overview
Welcome to LangGraph – Beginner to Advanced (Agentic AI Engineering with Python).
This course takes you from understanding how generative AI works to designing, implementing, testing, and deploying sophisticated agentic AI applications using Python.
Modern AI engineering involves much more than sending a prompt to a large language model and displaying its response. Real-world applications need to retrieve information, interact with external services, maintain conversational context, make decisions, recover from failures, and sometimes request human approval before performing important actions.
These requirements introduce an engineering challenge: how do we coordinate all these operations reliably?
LangGraph provides a framework for solving that challenge.
Throughout this course, you will learn not only how to use LangGraph APIs but also how to think like an agentic AI engineer. You will understand why particular architectures exist, when to use them, and how to make intelligent applications predictable enough for production environments.
From Artificial Intelligence to Agentic AI
Artificial intelligence, or AI, is a broad field concerned with building computer systems capable of performing tasks associated with human intelligence, such as recognising patterns, understanding language, making predictions, and solving problems.
Traditional machine learning applications frequently perform narrowly defined tasks. For example, a model might predict whether a transaction is fraudulent or classify an email as spam.
Generative AI focuses on producing new content. It can generate text, images, audio, code, and other forms of information based on learned patterns.
Large language models, commonly called LLMs, are a category of models trained on large amounts of data to process and generate language.
Agentic AI goes beyond isolated generation. It combines models with application logic, tools, state, and decision-making mechanisms to accomplish objectives through multiple steps.
Consider an AI-powered customer support system:
- A basic chatbot generates a response to a customer’s question.
- A retrieval-powered assistant searches company documentation before responding.
- An agentic application can decide what information it needs, inspect an order through an API, consult company policies, and prepare an appropriate resolution.
- A production agent can additionally enforce permissions, request approval, recover from failures, and record its activities.
The progression is not simply about using increasingly powerful models. It is about building increasingly capable systems around those models.
What Is LangGraph?
LangGraph is an open-source orchestration framework for building stateful applications, including AI workflows and agents.
It represents application logic using graphs, where individual operations are connected through execution paths.
Three fundamental concepts appear throughout this course:
- State: Information shared across different stages of execution.
- Nodes: Functions or operations that perform individual pieces of work.
- Edges: Connections that determine which operations execute next.
Unlike an ordinary sequential pipeline, a graph can contain conditional branches, loops, and parallel execution paths. These capabilities allow applications to respond dynamically to changing information.
LangGraph also provides mechanisms for persistence, streaming, interrupts, fault tolerance, and durable execution.
Importantly, LangGraph is not itself a language model. It coordinates the components that make up an intelligent application.
You can explore the framework’s official capabilities in the LangGraph documentation.
How the Course Is Organised
The course follows a progressive, project-oriented learning path. Each stage introduces concepts that become building blocks for more advanced applications.
You do not need to understand every term introduced in this welcome lesson. The following roadmap provides context for what you will learn and why each subject matters.
Stage 1: Generative AI and LLM Fundamentals
Before building agents, you must understand the models that power them.
This opening chapter contains five lessons:
| Lesson | What You Will Learn |
|---|---|
| Welcome to LangGraph | Course structure, prerequisites, and engineering foundations |
| How LLMs work | Model behaviour, tokens, embeddings, context windows, and limitations |
| Calling models from Python | Provider integrations, messages, authentication, and model invocation |
| Prompts and structured output | Effective instructions and schema-based responses |
| Function and tool calling | Connecting language models to external capabilities |
You will learn why models sometimes hallucinate, how instructions influence their responses, and why generated content should not automatically be treated as verified information.
The chapter concludes with a hands-on project: building an LLM-powered question-answering application.
Stage 2: LangChain and LangGraph Foundations
After learning how to interact with models, you will begin constructing graph-based applications.
Topics include defining state schemas, implementing nodes, connecting edges, compiling graphs, and executing workflows.
You will progressively move from simple sequential workflows to conditional execution, dynamic routing, and iterative processing.
This stage establishes the programming model used throughout the remainder of the course.
Stage 3: Building Intelligent Agents
You will learn how to combine models, tools, and graphs to build applications capable of selecting actions dynamically.
Typical architectural patterns include:
- Tool-calling agents.
- Router-based workflows.
- Planning and execution systems.
- Retrieval-augmented generation, or RAG.
- Reflection and response refinement.
- Multi-agent coordination.
You will also learn when an ordinary workflow is preferable to an autonomous agent. More autonomy is not automatically better engineering.
Stage 4: Stateful and Human-Supervised Applications
Real applications frequently need to preserve information beyond a single function call.
You will study conversation history, checkpointing, persistent stores, thread management, and long-term memory.
Human-in-the-loop techniques will allow workflows to pause while waiting for approval or additional information, then resume using saved execution state.
For example, an agent could prepare a refund request automatically while requiring an authorised employee to approve it before execution.
Stage 5: Production Agentic AI Engineering
The advanced stages address the difference between a working demonstration and a dependable production system.
You will explore asynchronous execution, streaming, retries, timeouts, caching, external integrations, Model Context Protocol (MCP), and application deployment.
Production engineering also includes:
- Managing latency and operational costs.
- Protecting sensitive information.
- Validating model-generated data.
- Preventing uncontrolled execution loops.
- Tracing and debugging agent behaviour.
- Evaluating response quality and tool usage.
- Designing reliable failure-handling strategies.
You will work with the LangSmith ecosystem for observability and evaluation, alongside LangGraph deployment mechanisms.
The following diagram illustrates the learning progression.
What You Need
Programming Prerequisites
This course assumes that you already understand basic Python programming.
You should be comfortable working with variables, functions, dictionaries, lists, classes, imports, and exception handling.
The course also assumes familiarity with REST APIs, JSON data, and basic SQL queries.
Consider the following Python function:
def get_order(order_id: str) -> dict:
return {
"order_id": order_id,
"status": "shipped",
"total": 1499
}
order = get_order("ORD-1001")
print(order["status"])Expected output:
shippedIf you understand the function definition, type annotations, returned dictionary, and dictionary access, you have sufficient Python knowledge to begin.
Later lessons will introduce more advanced concepts, including typed state schemas, asynchronous programming, decorators, and data validation.
You do not need previous experience with machine learning mathematics, neural network training, or deep learning frameworks. This course focuses on building applications with existing models rather than training foundation models from scratch.
Development Environment
Python 3.11 or newer is recommended for this course.
You will also need:
- A code editor, such as Visual Studio Code or PyCharm.
- Access to a terminal or command prompt.
- Internet access for installing packages and calling hosted models.
- Git for version control.
- A model provider account or a supported local model.
Verify your Python installation:
python --versionOn systems where Python is exposed through the python3 command, use that command instead.
Create a dedicated project directory and virtual environment:
mkdir langgraph-course
cd langgraph-course
python -m venv .venvActivate the environment on macOS or Linux:
source .venv/bin/activateOn Windows PowerShell:
.venv\Scripts\Activate.ps1A virtual environment isolates your course dependencies from other Python projects. This reduces conflicts between incompatible package versions.
Installing the Core Libraries
The course uses the LangGraph 1.x and LangChain 1.x API families.
Install the initial dependencies:
python -m pip install --upgrade pip
python -m pip install "langgraph>=1,<2" "langchain>=1,<2" langchain-openai python-dotenvAdditional provider integrations and infrastructure packages will be installed when required.
The following complete script verifies that the core packages are installed and displays their versions.
from importlib.metadata import version
packages = [
"langgraph",
"langchain",
"langchain-openai",
"python-dotenv"
]
for package in packages:
print(f"{package}: {version(package)}")
assert version("langgraph").split(".")[0] == "1"
assert version("langchain").split(".")[0] == "1"
print("Core environment is ready.")Your output will contain the installed package versions, followed by:
Core environment is ready.Once your environment is working, record the resolved dependencies:
python -m pip freeze > requirements.txtThis makes it easier to recreate the environment and diagnose compatibility problems later.
Note: Many older tutorials use outdated LangGraph and LangChain APIs. This course uses the 1.x API families. Consult the current documentation before mixing code from different tutorial versions.
Choosing a Language Model Provider
LangGraph is not restricted to a particular model provider.
Throughout the course, OpenAI will serve as the primary provider for consistent examples, while other integrations demonstrate how applications can support different models.
| Provider | LangChain Integration | Execution | Credential |
|---|---|---|---|
| OpenAI | langchain-openai |
Hosted API | OPENAI_API_KEY |
| Google Gemini | langchain-google-genai |
Hosted API | GOOGLE_API_KEY |
| Anthropic | langchain-anthropic |
Hosted API | ANTHROPIC_API_KEY |
| Ollama | langchain-ollama |
Local model server | Usually none locally |
Ollama allows compatible models to run on your own machine. Performance depends on available memory, processing power, and model size.
You do not need accounts with every provider. However, some exercises depend on capabilities such as tool calling and structured output, which vary between models.
Hosted model APIs may charge for usage. API access and consumer chatbot subscriptions are generally separate products.
Configuring API Credentials
Create a file named .env in your project directory:
OPENAI_API_KEY=your_actual_api_keyReplace the placeholder with your real API key.
Create a .gitignore file containing:
.env
.venv/
__pycache__/
*.pycThe following script checks whether your OpenAI credential is configured without revealing its value.
import os
from dotenv import load_dotenv
load_dotenv()
if not os.getenv("OPENAI_API_KEY"):
raise RuntimeError("OPENAI_API_KEY is missing.")
print("OpenAI credentials are configured.")Expected output when the credential exists:
OpenAI credentials are configured.This checks configuration only. It does not verify that the key is valid or that the account can access a particular model.
Never hardcode credentials into source code, print them in logs, or commit them to version control. Production deployments should use appropriate secret-management infrastructure.
How the Pieces Fit
Understanding the AI Application Stack
A production agentic AI application typically contains several cooperating layers.
| Component | Responsibility |
|---|---|
| Language model | Generates content and proposes decisions |
| Prompt | Communicates instructions, context, and constraints |
| Tools | Provide controlled access to external capabilities |
| LangChain | Supplies model abstractions, messages, and integrations |
| LangGraph | Coordinates execution, routing, and state |
| Persistence | Preserves execution state and application memory |
| LangSmith | Supports tracing, debugging, and evaluation |
| Application interface | Connects users or external systems to the agent |
These components solve different problems. For example, changing the model does not automatically change the workflow architecture, and adding persistence does not automatically improve factual accuracy.
Understanding these boundaries will help you design applications that are easier to maintain and test.
Your First Language Model Call
Before introducing orchestration, consider the simplest possible LLM-powered application.
The following example sends a question to an OpenAI model using LangChain’s standard chat model interface.
Save it as first_model.py.
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from langchain.messages import SystemMessage, HumanMessage
load_dotenv()
model = init_chat_model("openai:gpt-5.4-mini")
messages = [
SystemMessage(
content="You are a concise Python programming tutor."
),
HumanMessage(
content="Explain a Python dictionary in one sentence."
)
]
response = model.invoke(messages)
print(response.text)Run the script:
python first_model.pyAn example response is:
A Python dictionary is a mutable collection that stores data as key-value pairs.The precise wording may differ between executions. Successful execution requires valid credentials, network access, available API usage, and access to the specified model.
The init_chat_model() function creates a model integration using a provider-qualified identifier. The invoke() method sends the messages and waits for the model’s response.
Notice that the system message describes the model’s role, while the human message contains the actual request.
The model call is useful, but it is not an agent. It does not independently query a database, maintain durable state, or coordinate multiple application operations.
See the LangChain model documentation and the GPT-5.4 mini model reference for integration and model details.
Essential LLM Concepts
Several concepts will become increasingly important as your applications grow.
Tokens are units of information processed by language models. They may represent words, parts of words, punctuation, or other content. Token usage affects model capacity, latency, and hosted API costs.
A context window defines how much tokenised information a model can handle within an interaction. Conversation history, retrieved documents, instructions, tool results, and generated output all need to be considered when managing context.
Embeddings represent information as numerical vectors. They allow applications to compare semantic similarity and retrieve relevant documents even when their wording differs from the user’s question.
Prompt engineering involves designing instructions and supplying relevant context to guide model behaviour.
Structured output constrains responses to an expected format, making them easier for software to consume. Schema validation improves structural reliability but does not guarantee factual correctness.
Tool calling allows a model to request an external operation using a defined interface. In a typical application-managed tool-calling workflow, your application validates and executes that operation before returning its result to the model.
These mechanisms transform a text-generation model into a useful component within a larger software system.
Your First LangGraph Application
Let us now create a small graph that does not require an LLM or an API key.
This demonstrates an important principle: LangGraph nodes can execute ordinary Python functions.
The workflow accepts a question, cleans it, and generates a predefined response.
Save the following example as first_graph.py.
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
class AppState(TypedDict, total=False):
question: str
answer: str
def clean_question(state: AppState) -> dict:
return {
"question": state["question"].strip()
}
def generate_answer(state: AppState) -> dict:
question = state["question"]
return {
"answer": f"Your question was: {question}"
}
builder = StateGraph(AppState)
builder.add_node("clean", clean_question)
builder.add_node("answer", generate_answer)
builder.add_edge(START, "clean")
builder.add_edge("clean", "answer")
builder.add_edge("answer", END)
graph = builder.compile()
result = graph.invoke({
"question": " What is LangGraph? "
})
print(result)Run the application:
python first_graph.pyExpected output:
{'question': 'What is LangGraph?', 'answer': 'Your question was: What is LangGraph?'}The application executes through the following graph.
How Graph Execution Works
The example introduces the fundamental LangGraph execution model.
AppStatedefines the fields that can exist in the graph’s shared state.StateGraph(AppState)creates a graph builder associated with that state schema.add_node()registers Python functions as executable graph nodes.add_edge()establishes the execution order.compile()produces an executable graph.invoke()starts execution with an initial state and returns the resulting state.
The first node returns an update to the question field. LangGraph applies that update before the second node executes.
The second node returns a new value for the answer field without removing the existing question.
Under the hood, LangGraph schedules node execution and applies state updates according to the graph’s configuration. More advanced graphs can schedule multiple nodes within execution steps and use reducers to combine updates.
The TypedDict definition provides a typed description of the state. It does not, by itself, enforce comprehensive runtime validation.
This example has no persistence configured, so it should not be treated as a durable conversational application.
The Graph API documentation provides further details about these mechanisms.
Workflows Versus Agents
A workflow typically follows execution paths defined by the developer. An agent uses a model to dynamically determine at least some of its actions.
| Characteristic | Workflow | Agent |
|---|---|---|
| Execution path | Primarily developer-defined | Partly model-driven |
| Predictability | Generally higher | Generally lower |
| Flexibility | Limited to designed paths | Adapts to changing inputs |
| Testing | Often straightforward | Requires behavioural evaluation |
| Suitable for | Repeatable business processes | Open-ended tasks |
LangGraph supports both approaches, including hybrid architectures that combine deterministic business rules with model-driven decisions.
Common Beginner Mistakes
One common mistake is assuming that a fluent model response must be correct. LLMs can generate convincing but inaccurate information, a behaviour commonly called hallucination.
Other mistakes include passing unnecessary information into prompts, trusting model-generated tool arguments, adding complex agent architectures prematurely, and overlooking the cost of repeated model calls.
Start with the simplest architecture that satisfies the requirement. Introduce additional autonomy only when it provides measurable value.
Tip: Test ordinary Python nodes independently before integrating language models. Deterministic components are usually easier to debug, faster to execute, and less expensive to test.
The Capstone
Chapter Project: LLM-Powered Question-Answering Application
The first chapter’s hands-on project is a Python application that accepts questions and produces answers using a language model.
You will progressively incorporate:
- Model initialisation and invocation.
- System and human messages.
- Prompt design.
- Structured responses.
- Basic tool integration.
- Input validation and error handling.
This project establishes the foundation for later graph-based applications.
For example, the application might answer programming questions and use a calculator tool when a question requires arithmetic.
The objective is to understand the complete interaction between user input, application logic, model requests, and generated responses.
Course Capstone: Production-Oriented Agentic AI Application
A suitable capstone architecture for bringing the course concepts together is an intelligent customer support agent.
Such an application can retrieve knowledge base information, inspect customer orders, classify requests, recommend resolutions, and escalate sensitive cases.
The production-oriented design should incorporate persistent conversation state, controlled tool execution, conditional routing, human approval, streaming, failure recovery, and evaluation.
The support-agent scenario is a practical reference architecture that can also be adapted to domains such as internal enterprise assistants, research applications, and IT service management.
A successful capstone should demonstrate more than the ability to generate answers. It should demonstrate that you can explain the application’s execution paths, manage failures, protect sensitive operations, and evaluate whether the system fulfils its intended requirements.
Assessment
Assessment throughout the course should measure practical understanding rather than memorisation of framework syntax.
Knowledge and Practical Assessment
You will develop your skills through conceptual questions, coding exercises, debugging activities, hands-on projects, and architectural reasoning.
Use the following criteria to evaluate your progress.
| Assessment Area | Demonstrated Competency |
|---|---|
| Conceptual understanding | Explain why a particular mechanism exists |
| Implementation | Build functioning applications using current APIs |
| Debugging | Identify and resolve execution failures |
| Architecture | Select appropriate workflows and agent patterns |
| Reliability | Handle invalid inputs and unexpected behaviour |
| Production readiness | Consider security, persistence, cost, and observability |
When testing an AI application, remember that exact response wording is rarely the most useful success criterion.
Instead, evaluate factual accuracy, required output fields, permitted tool usage, successful task completion, and appropriate handling of uncertainty.
Deterministic graph nodes can be tested using ordinary Python assertions. Model-driven components additionally require evaluation datasets and behavioural checks, which will be introduced in later lessons.
Preparing for the Next Lesson
The next lesson, How LLMs work, examines the mechanisms behind large language models.
You will explore tokenisation, embeddings, transformer fundamentals, next-token prediction, inference, context windows, and hallucinations.
Understanding these mechanisms will help you make informed engineering decisions about prompt construction, model selection, context management, and agent reliability.
Before proceeding, ensure that your Python environment is configured and that you can execute the first LangGraph application successfully. The model-independent example is sufficient to verify your initial graph setup; hosted model access can be confirmed separately when you begin working with provider APIs.
Build Your First LangGraph Workflow
Build a simple question-answering workflow using LangGraph without calling an external language model. Create one node that normalises the question and another that returns an answer from a predefined knowledge base. Connect the nodes using edges, compile the graph, and test it with both known and unknown questions.
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
class QAState(TypedDict, total=False):
question: str
answer: str
KNOWLEDGE_BASE = {
"what is langgraph?": "LangGraph is a framework for stateful AI workflows.",
"what is an llm?": "An LLM is a large language model."
}
def normalise_question(state: QAState) -> dict:
# TODO: Remove surrounding whitespace and convert to lowercase.
raise NotImplementedError
def answer_question(state: QAState) -> dict:
# TODO: Look up the question in the knowledge base.
# Return a fallback answer when the question is unknown.
raise NotImplementedError
builder = StateGraph(QAState)
# TODO: Register both nodes.
# TODO: Connect START, both nodes, and END.
# TODO: Compile the graph.
# TODO: Invoke the graph with a sample question.from typing import TypedDict
from langgraph.graph import StateGraph, START, END
class QAState(TypedDict, total=False):
question: str
answer: str
KNOWLEDGE_BASE = {
"what is langgraph?": "LangGraph is a framework for stateful AI workflows.",
"what is an llm?": "An LLM is a large language model."
}
def normalise_question(state: QAState) -> dict:
return {
"question": state["question"].strip().lower()
}
def answer_question(state: QAState) -> dict:
return {
"answer": KNOWLEDGE_BASE.get(
state["question"],
"I do not know the answer."
)
}
builder = StateGraph(QAState)
builder.add_node("normalise", normalise_question)
builder.add_node("answer", answer_question)
builder.add_edge(START, "normalise")
builder.add_edge("normalise", "answer")
builder.add_edge("answer", END)
graph = builder.compile()
known = graph.invoke({
"question": " What is LangGraph? "
})
unknown = graph.invoke({
"question": "What is quantum computing?"
})
print(known["answer"])
print(unknown["answer"])
assert known["answer"] == KNOWLEDGE_BASE["what is langgraph?"]
assert unknown["answer"] == "I do not know the answer."Summary
- LangGraph is an orchestration framework for building stateful workflows and agentic AI applications.
- Large language models generate responses but require surrounding application logic to perform reliable real-world tasks.
- LangChain provides standardised model and tool integrations, while LangGraph manages workflow execution and state.
- Graph-based applications organise computation into nodes, edges, and shared state.
- The course progresses from generative AI fundamentals to advanced agent architectures and production deployment.
- Reliable AI applications require validation, error handling, security, observability, and systematic evaluation.
- Practical projects develop the engineering skills needed to build AI systems beyond simple chatbot demonstrations.