Installation and setup
Overview
In the previous lesson, you learned why LangGraph exists and how graph-based orchestration helps engineers build applications that go beyond simple prompt-and-response interactions.
Before implementing agents, conditional workflows, memory, tool calling, and human-in-the-loop systems, you need a reliable development environment.
Environment setup is more than installing a Python package. A professional AI engineering project must manage dependencies, credentials, configuration, testing, and compatibility between libraries.
In this lesson, you will:
- Create an isolated Python project.
- Install LangGraph and its essential companion packages.
- Understand which dependencies provide different capabilities.
- Configure model provider credentials securely.
- Verify local graph execution and external model connectivity separately.
- Organize your project for future development.
Throughout this course, we use the LangGraph 1.x and LangChain 1.x API families, with Python 3.12 as the recommended development interpreter.
Understanding the technology stack
LangGraph and LangChain are related but serve different purposes.
LangGraph provides the workflow execution engine. LangChain provides standardized abstractions for interacting with language models, messages, tools, and external integrations.
A model provider integration connects those abstractions to a particular service, such as OpenAI.
The following diagram illustrates how these components work together in a typical agentic application.
Not every application needs every component in this diagram.
A workflow that validates customer records, performs calculations, or transforms JSON can run entirely inside Python using LangGraph. A workflow that interprets natural language may additionally require LangChain and a model provider integration.
Persistence and observability can be introduced independently as application requirements grow.
This separation is important because it allows you to test workflow logic without repeatedly paying for language model requests.
Create a project
Step 1: Install and verify Python
Use Python 3.11 or newer for the course environment. Python 3.12 is recommended because it provides a mature development ecosystem and broad compatibility with the required packages.
Although LangGraph itself supports Python 3.10, the current LangChain and OpenAI integration packages require Python 3.11 or newer.
Download Python from the official Python website if necessary.
Check your installed version:
python --versionOn macOS or Linux, you may need:
python3 --versionOn Windows, you can also use the Python launcher:
py -3.12 --versionExpected output:
Python 3.12.xA newer compatible Python version is also acceptable.
If multiple Python versions are installed, explicitly select the interpreter you intend to use when creating your virtual environment.
Step 2: Create a project directory
Open a terminal and execute:
mkdir langgraph-course
cd langgraph-courseThis directory will contain your application code, configuration, dependencies, tests, and learning experiments.
You can open the directory in Visual Studio Code, PyCharm, or another Python-compatible editor.
Keeping course-related code inside a dedicated project prevents accidental mixing with unrelated applications.
Step 3: Create a virtual environment
A virtual environment provides an isolated location for a project’s Python packages.
Without isolation, installing or upgrading a package for one project could unexpectedly break another project.
For example, one application might depend on LangChain 0.x while this course requires LangChain 1.x. Installing both into the same global Python environment creates incompatible requirements.
Create a virtual environment on macOS or Linux:
python3.12 -m venv .venvOn Windows:
py -3.12 -m venv .venvAlternatively, if the python command already points to a suitable interpreter:
python -m venv .venvThe .venv directory contains an isolated Python executable and a dedicated package installation directory.
Activate it using the appropriate command for your operating system.
| Operating system or shell | Activation command |
|---|---|
| macOS / Linux | source .venv/bin/activate |
| Windows PowerShell | .\.venv\Scripts\Activate.ps1 |
| Windows Command Prompt | .venv\Scripts\activate.bat |
After activation, your terminal will usually display a prefix similar to:
(.venv)Activation changes how your shell resolves commands such as python and pip. It does not modify your application code.
To leave the virtual environment later, execute:
deactivateTip: Select the
.venvinterpreter in your code editor as well. Activating a terminal environment does not necessarily change the interpreter used by your editor or notebook.
If PowerShell blocks activation scripts, you can use Command Prompt or execute the virtual environment’s Python interpreter directly without changing system-wide security settings.
Step 4: Install the core packages
Upgrade pip inside your activated environment:
python -m pip install --upgrade pipInstall the essential dependencies:
python -m pip install "langgraph>=1.2,<2" "langchain>=1.4,<2" "langchain-openai>=1,<2" "python-dotenv>=1,<2"These version constraints select the API generations used throughout the course while preventing automatic upgrades to incompatible major versions.
Using python -m pip instead of simply pip helps ensure that packages are installed into the environment belonging to the selected Python interpreter.
What did we install?
| Package | Responsibility | Required now? |
|---|---|---|
langgraph |
Graph construction, state management, and workflow execution | Yes |
langchain |
Standard model, message, agent, and tool interfaces | Yes |
langchain-openai |
Integration with OpenAI models and embeddings | For model examples |
python-dotenv |
Loading configuration from local .env files |
Recommended |
langchain-core |
Shared abstractions and foundational components | Installed automatically |
langgraph-checkpoint |
Checkpoint interfaces and foundational persistence support | Installed automatically |
langgraph-prebuilt |
Reusable graph components, including tool execution | Installed automatically |
Some packages are direct dependencies that you explicitly request. Others are transitive dependencies installed because another package requires them.
Python’s package resolver examines dependency constraints and attempts to select mutually compatible versions.
Avoid independently upgrading foundational transitive dependencies without checking compatibility with the rest of your environment.
Validate the resolved dependencies:
python -m pip checkExpected output:
No broken requirements found.This confirms that installed package versions satisfy their declared dependency requirements. It does not yet prove that every runtime operation works.
Step 5: Record your dependencies
Create a file named requirements.txt in the project root:
langgraph>=1.2,<2
langchain>=1.4,<2
langchain-openai>=1,<2
python-dotenv>=1,<2Another developer can reproduce a compatible environment using:
python -m pip install -r requirements.txtHowever, version ranges allow newer compatible releases to be selected. Two installations performed several months apart may resolve different versions.
To capture the exact installed package versions, generate a separate environment snapshot:
python -m pip freeze > requirements.lock.txtReinstall those recorded versions in a fresh, compatible environment with:
python -m pip install -r requirements.lock.txtA pip freeze snapshot is useful for learning projects, although it is not a complete cross-platform, hash-verified dependency lock.
Larger production projects commonly use pyproject.toml together with a dependency management tool such as uv, which provides more comprehensive dependency locking.
Packages you will add later
You do not need to install every LangGraph-related package immediately.
LangGraph applications can range from small local workflows to distributed agent systems. Their infrastructure requirements differ considerably.
Install additional packages when a lesson or application introduces the corresponding capability.
Persistence and memory
LangGraph can save workflow state through checkpointers.
For development and testing, the built-in in-memory implementation is sufficient:
from langgraph.checkpoint.memory import InMemorySaver
checkpointer = InMemorySaver()
print(type(checkpointer).__name__)Expected output:
InMemorySaverThis implementation keeps checkpoint data in memory. It is useful for experiments, but it does not provide durable storage across process restarts.
When you need local database-backed checkpointing, install SQLite support:
python -m pip install langgraph-checkpoint-sqliteFor PostgreSQL-backed persistence:
python -m pip install langgraph-checkpoint-postgres "psycopg[binary,pool]"Installing PostgreSQL support does not create a PostgreSQL database. You will also need a running database, connection credentials, and initialization of the required database tables.
Those responsibilities will be covered in the persistence lessons.
Additional model providers
LangChain supports multiple model providers through independently distributed integration packages.
For example:
python -m pip install langchain-anthropicOr:
python -m pip install langchain-google-genaiThese packages are unnecessary when your application exclusively uses OpenAI.
The standardized model interface reduces provider-specific changes in application code, although models still differ in capabilities, parameters, pricing, and response behavior.
Observability, evaluation, and deployment
As your applications become more sophisticated, you will introduce additional development infrastructure.
| Package | Purpose |
|---|---|
langsmith |
Tracing, monitoring, datasets, and evaluation |
openevals |
Evaluating generated outputs |
agentevals |
Evaluating agent execution trajectories |
pytest |
Automated application testing |
langgraph-cli |
Agent Server development and deployment tooling |
langgraph-sdk |
Communicating with deployed Agent Server applications |
langchain[mcp] |
Connecting applications to MCP-compatible tools |
For example, install testing and evaluation packages when needed:
python -m pip install pytest langsmith openevals agentevalsFor local Agent Server development:
python -m pip install "langgraph-cli[inmem]"For Model Context Protocol integrations:
python -m pip install "langchain[mcp]>=1.4,<2"The MCP, deployment, and evaluation workflows will receive dedicated coverage later in the course.
You do not need Docker, PostgreSQL, Redis, a vector database, or an Agent Server to execute the introductory graphs.
A smaller dependency set makes installation faster, reduces compatibility problems, and limits the amount of software that must be maintained.
Environment variables
Why configuration belongs outside your code
Agentic applications frequently communicate with external services that require authentication.
An API key is a credential that authorizes requests against an account or project. Anyone who obtains an unrestricted key may be able to make requests and generate charges against that account.
Never embed an API key directly inside Python source code.
Instead, use environment variables.
An environment variable is a named value made available to a running process. Python accesses these values through the standard os module.
This approach separates application behavior from environment-specific configuration.
The same application can run locally, in a testing environment, or in production without changing its source code.
Create an OpenAI API key
For the model-based examples in this course, you will need access to the OpenAI API.
- Visit the OpenAI API platform.
- Create or select an API project.
- Configure API billing or available credits as required.
- Generate an API key from the API keys section.
- Store the key securely.
A ChatGPT subscription is separate from OpenAI API billing and does not automatically provide API credits.
You can complete deterministic LangGraph examples without obtaining an API key.
Create a local dotenv file
Create a file named .env inside your project root:
OPENAI_API_KEY=replace_with_your_actual_api_key
LANGSMITH_TRACING=false
LANGSMITH_API_KEY=
LANGSMITH_PROJECT=langgraph-courseReplace the OpenAI placeholder with your actual key.
The LangSmith variables are optional at this stage. Tracing is explicitly disabled until you are ready to configure observability.
| Variable | Purpose |
|---|---|
OPENAI_API_KEY |
Authenticates OpenAI API requests |
LANGSMITH_TRACING |
Enables or disables LangSmith tracing |
LANGSMITH_API_KEY |
Authenticates LangSmith requests |
LANGSMITH_PROJECT |
Groups related execution traces |
When tracing is enabled later, execution information may be sent to LangSmith. Review your organization’s privacy and data-handling requirements before tracing sensitive application inputs.
Load environment variables in Python
Python does not automatically load arbitrary .env files when an application starts.
The python-dotenv package provides this functionality.
Create check_config.py in the project root. This example loads your configuration and verifies credential availability without exposing sensitive values.
import os
from pathlib import Path
from dotenv import load_dotenv
env_file = Path(__file__).resolve().parent / ".env"
load_dotenv(env_file)
api_key = os.getenv("OPENAI_API_KEY", "").strip()
tracing = os.getenv("LANGSMITH_TRACING", "false")
project = os.getenv("LANGSMITH_PROJECT", "langgraph-course")
configured = bool(api_key) and api_key != "replace_with_your_actual_api_key"
print("OpenAI API key configured:", configured)
print("LangSmith tracing:", tracing)
print("LangSmith project:", project)Execute it:
python check_config.pyExpected output when a key has been configured:
OpenAI API key configured: True
LangSmith tracing: false
LangSmith project: langgraph-courseBy default, load_dotenv() does not overwrite environment variables that already exist. This allows externally injected configuration to take precedence over local defaults.
Checking whether a credential exists does not prove that it is valid or authorized to access a particular model.
Protect credentials from version control
Create a .gitignore file:
.venv/
.env
.env.*
!.env.example
__pycache__/
*.py[cod]
.pytest_cache/
.langgraph_api/
*.sqlite
*.sqlite3
*.db
*.db-wal
*.db-shmCreate a separate .env.example file containing safe configuration placeholders:
OPENAI_API_KEY=
LANGSMITH_TRACING=false
LANGSMITH_API_KEY=
LANGSMITH_PROJECT=langgraph-courseCommit .env.example to version control, but never commit the actual .env file.
The example file documents which configuration variables developers need to supply.
Note: Adding
.envto.gitignoredoes not remove secrets that were previously committed. If an API key is exposed, revoke or rotate it immediately and follow your repository’s secret-remediation procedure.
In production, credentials should typically be injected through your hosting platform or a dedicated secrets manager rather than copied into a deployed dotenv file.
Check the install
A reliable installation check should verify three independent layers:
- Python imports and package compatibility.
- Local LangGraph workflow execution.
- External language model connectivity.
Separating these checks makes troubleshooting considerably easier.
Check 1: Verify installed packages
Create check_install.py. The following example confirms the active interpreter and checks whether the primary public API imports are available.
import sys
from importlib.metadata import version
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage
from langgraph.graph import StateGraph, START, END
from langgraph.prebuilt import ToolNode, tools_condition
print("Python version:", sys.version.split()[0])
print("Python executable:", sys.executable)
for package in [
"langgraph",
"langchain",
"langchain-openai",
"python-dotenv",
]:
print(f"{package}: {version(package)}")
print("Core imports successful.")Run:
python check_install.pyIllustrative output:
Python version: 3.12.x
Python executable: .../.venv/bin/python
langgraph: 1.2.x
langchain: 1.x.x
langchain-openai: 1.x.x
python-dotenv: 1.x.x
Core imports successful.Your actual package versions and interpreter path will differ.
Importing init_chat_model does not itself send a model request or require an API key.
Check 2: Execute a minimal LangGraph workflow
A smoke test is a small test designed to establish whether a system’s essential functionality works.
Create smoke_test.py. This example executes a single-node graph without any external services.
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
class State(TypedDict):
text: str
def normalize_text(state: State) -> dict:
return {
"text": state["text"].strip().lower()
}
builder = StateGraph(State)
builder.add_node("normalize", normalize_text)
builder.add_edge(START, "normalize")
builder.add_edge("normalize", END)
graph = builder.compile()
result = graph.invoke({
"text": " HELLO LANGGRAPH "
})
assert result["text"] == "hello langgraph"
print(result)
print("LangGraph smoke test passed.")Run the script:
python smoke_test.pyExpected output:
{'text': 'hello langgraph'}
LangGraph smoke test passed.The following diagram represents the workflow executed by this smoke test.
Internally, StateGraph records the workflow’s structure and state schema. Calling compile() validates the graph and produces an executable runtime object.
Calling invoke() supplies initial state. The runtime schedules the normalization node, applies its returned state update, and finishes execution at END.
The next lesson will explain these operations in detail.
If this test succeeds, your LangGraph installation can construct, compile, and execute a basic graph.
Check 3: Verify model connectivity
The next example verifies that LangChain can communicate with OpenAI through the installed provider integration.
Create check_model.py:
import os
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage
load_dotenv()
api_key = os.getenv("OPENAI_API_KEY", "").strip()
if not api_key or api_key == "replace_with_your_actual_api_key":
raise RuntimeError(
"Configure OPENAI_API_KEY before running this test."
)
model = init_chat_model("openai:gpt-5.4-mini")
response = model.invoke([
HumanMessage(
content="Reply with the single word READY."
)
])
print("Response:", response.text)
print("Model connectivity check completed.")Execute it:
python check_model.pyTypical output:
Response: READY
Model connectivity check completed.Unlike the previous test, this example sends a real API request and may incur a small usage charge.
The openai: prefix identifies the provider, while gpt-5.4-mini identifies the requested model.
LangChain selects the corresponding provider integration, constructs the model client, and converts the standardized message into a provider-compatible request.
The resulting response is represented as an AIMessage.
Model-generated text is not guaranteed to match a requested string exactly. A successful response establishes connectivity even if the wording differs.
The expected outputs in this lesson are reference examples rather than logs from a live execution against your machine or API account.
Troubleshooting common installation problems
| Error or symptom | Likely cause | Recommended action |
|---|---|---|
ModuleNotFoundError |
Package missing from the active environment | Verify the interpreter and reinstall dependencies |
ImportError |
Incompatible or outdated package versions | Inspect versions and run python -m pip check |
| Python version incompatibility | Unsupported interpreter | Recreate .venv using Python 3.12 |
| HTTP 401 | Invalid or revoked API credentials | Verify or replace the API key |
| HTTP 403 or 404 | Model access, permissions, or identifier problem | Check project permissions and model availability |
| HTTP 429 | Rate limit or insufficient quota | Inspect the provider’s error details and billing configuration |
| Connection timeout | Network, firewall, proxy, or service issue | Verify connectivity and network configuration |
| API key not detected | Missing configuration or incorrect dotenv path | Check the .env location and variable name |
Avoid naming your Python files langgraph.py, langchain.py, openai.py, or dotenv.py.
Such filenames can shadow installed packages because Python searches local modules during import resolution.
When dependency conflicts become difficult to resolve, creating a fresh virtual environment from your recorded requirements is often safer than repeatedly upgrading individual dependencies.
Suggested layout
A project structure that grows with you
For introductory examples, standalone Python scripts are sufficient. As your application grows, separate graph definitions, business logic, configuration, and tests.
A suggested course project structure is:
langgraph-course/
├── .venv/
├── .env
├── .env.example
├── .gitignore
├── requirements.txt
├── requirements.lock.txt
├── README.md
├── app/
│ ├── __init__.py
│ ├── graph.py
│ ├── state.py
│ ├── nodes.py
│ ├── tools.py
│ └── config.py
├── examples/
│ └── sequential_graph.py
├── tests/
│ └── test_graph.py
├── check_config.py
├── check_install.py
├── check_model.py
└── smoke_test.pyYou do not need to implement every file immediately.
The app directory will eventually contain reusable application logic. The examples directory holds standalone experiments, while tests contains automated checks.
| File | Responsibility |
|---|---|
graph.py |
Graph construction and compilation |
state.py |
Shared state schemas |
nodes.py |
Workflow operations |
tools.py |
Functions exposed to language models |
config.py |
Application configuration |
test_graph.py |
Automated graph behavior tests |
README.md |
Installation and execution instructions |
Later, when introducing Agent Server deployment, you will add a langgraph.json configuration file and organize the project for deployment.
Establish good development habits
Run commands from the project root unless instructed otherwise. Use one virtual environment per project, keep credentials outside source code, and record dependency changes.
Keep deterministic tests separate from tests that require external model APIs. This enables fast, repeatable verification of workflow behavior even when model services are unavailable.
When upgrading packages, consult the LangGraph documentation, LangChain installation guide, and OpenAI integration documentation. Package compatibility can also be checked against the published LangGraph and LangChain OpenAI release metadata.
Preparing for the next lesson
In the next lesson, Your first graph, you will move beyond installation verification and build a complete sequential LangGraph application.
You will examine how state is defined, how nodes receive and update state, how edges control execution, and how compilation transforms a graph definition into an executable workflow.
That application will form the foundation of the chapter’s hands-on project and prepare you for conditional routing, cyclic workflows, persistent state, and increasingly sophisticated agentic systems.
Keep your virtual environment and project directory available. You will reuse both throughout the course.
Build a LangGraph environment checker
Create a Python script that verifies your Python version, displays the installed LangGraph and LangChain package versions, and checks whether an OpenAI API key is configured without exposing it. Build and execute a small deterministic graph to confirm that LangGraph works correctly. Your script must successfully execute the graph even when no API key is available.
import os
import sys
from importlib.metadata import version
from typing import TypedDict
from dotenv import load_dotenv
from langgraph.graph import StateGraph, START, END
load_dotenv()
# TODO 1: Verify that Python is at least version 3.11.
# TODO 2: Print the installed versions of:
# langgraph, langchain, langchain-openai, python-dotenv
# TODO 3: Report whether OPENAI_API_KEY is configured.
# Never print the actual API key.
class State(TypedDict):
number: int
def double_number(state: State) -> dict:
# TODO 4: Return a state update that doubles the number.
raise NotImplementedError
# TODO 5: Create a StateGraph using State.
# TODO 6: Register double_number as a node.
# TODO 7: Connect START to the node and the node to END.
# TODO 8: Compile the graph and invoke it with number=10.
# TODO 9: Assert that the resulting number equals 20.
# TODO 10: Print a success message.import os
import sys
from importlib.metadata import version
from typing import TypedDict
from dotenv import load_dotenv
from langgraph.graph import StateGraph, START, END
load_dotenv()
if sys.version_info < (3, 11):
raise RuntimeError("Python 3.11 or newer is required.")
print(f"Python: {sys.version.split()[0]}")
packages = [
"langgraph",
"langchain",
"langchain-openai",
"python-dotenv",
]
for package in packages:
print(f"{package}: {version(package)}")
has_api_key = bool(os.getenv("OPENAI_API_KEY", "").strip())
print(
"OpenAI API key:",
"Configured" if has_api_key else "Not configured",
)
class State(TypedDict):
number: int
def double_number(state: State) -> dict:
return {"number": state["number"] * 2}
builder = StateGraph(State)
builder.add_node("double_number", double_number)
builder.add_edge(START, "double_number")
builder.add_edge("double_number", END)
graph = builder.compile()
result = graph.invoke({"number": 10})
assert result["number"] == 20, "Graph execution failed."
print("Graph result:", result)
print("SUCCESS: LangGraph environment is ready.")Summary
- LangGraph executes stateful workflows and does not require an LLM or API key for deterministic graph execution.
- An isolated Python virtual environment prevents dependency conflicts between projects.
- LangChain provides standardized model and tool interfaces, while provider-specific packages connect those interfaces to external services.
- Use environment variables and local dotenv files to configure credentials without embedding secrets in source code.
- Package version checks, dependency validation, and deterministic graph execution provide complementary installation checks.
- Install optional persistence, integration, evaluation, and deployment packages only when their capabilities are needed.
- A structured project layout and reproducible dependencies make LangGraph applications easier to test, maintain, and deploy.