Production project structure and configuration

Topic 1 of 5 in Deployment & LLMOps29 min readAdvancedFree course

Overview

Throughout this course, you have learned how to construct graphs, implement agentic workflows, integrate tools, manage persistent state, implement human approvals, and connect agents to enterprise systems.

In the previous lesson, you explored enterprise integration using APIs, databases, audit logs, and multi-tenancy. You now have the technical foundation required to build sophisticated AI agents. The next challenge is transforming those agents into applications that can be deployed, maintained, tested, and operated reliably.

A working agent is not necessarily a production-ready application.

Consider an agent implemented in a single Python file containing:

  • Graph construction and routing logic.
  • Model initialization.
  • Database connections.
  • Hardcoded prompts and configuration values.
  • API credentials.
  • Tool implementations.
  • Interactive command-line input.
  • Testing code.

Although this arrangement may be convenient during experimentation, it becomes increasingly difficult to maintain when multiple developers contribute, environments require different settings, or deployments must be reproduced consistently.

Production engineering introduces several additional requirements:

  • Predictable application startup.
  • Secure configuration and credential management.
  • Reproducible dependencies.
  • Independently testable components.
  • Clear deployment entry points.
  • Environment isolation.
  • Controlled infrastructure ownership.

LangGraph applications deployed through LangSmith Agent Server generally require application code, dependency declarations, environment settings, and a deployment manifest named langgraph.json.

The following diagram illustrates the relationship between these components.

Overview diagram: Application code to Agent Server; Environment variables to Agent Server; Project dependencies to Agent Server; Deployment manifest to Agent Server; Agent Server to Graph execution; Graph execution to PostgreSQL; Agent Server to Redis; Graph execution to Model provider; Graph execution to External tools.

The objective of this lesson is to establish the project foundation that subsequent lessons will deploy through Agent Server, expose through APIs, containerize, and connect to a user interface.

We will use a customer support agent as our running example.

A production layout

Separating application responsibilities

There is no mandatory directory structure imposed by the LangGraph Graph API. However, a consistent structure makes larger applications easier to understand and operate.

Consider the following production-oriented layout:

Text
support-agent/
├── support_agent/
│   ├── __init__.py
│   ├── graph.py
│   ├── state.py
│   ├── config.py
│   ├── models.py
│   ├── nodes.py
│   ├── tools/
│   │   └── __init__.py
│   ├── services/
│   │   └── __init__.py
│   └── prompts/
│       └── __init__.py
├── tests/
│   ├── test_config.py
│   └── test_graph.py
├── scripts/
│   └── smoke_test.py
├── .env.example
├── .env
├── .gitignore
├── pyproject.toml
├── langgraph.json
├── langgraph.local.json
└── README.md

Each module has a specific responsibility.

Component Responsibility
graph.py Graph construction, edges, routing, and compilation
state.py State and runtime context schemas
config.py Typed application configuration
models.py Model initialization and reuse
nodes.py Graph node implementations
tools/ Agent-callable tools
services/ Database, HTTP, and enterprise integrations
prompts/ Prompt templates and instructions
tests/ Automated application tests
scripts/ Operational utilities and smoke tests
pyproject.toml Python packaging and dependencies
langgraph.json Deployment configuration

Create empty __init__.py files in the indicated packages. The tools, services, and prompts packages provide extension points for capabilities introduced in earlier lessons.

For larger projects, nodes.py can become a nodes/ package containing separate modules for classification, retrieval, reasoning, validation, and human approval.

Avoid splitting every small function into its own module. The objective is separation of responsibilities, not maximizing the number of files.

Step 1: Define graph state and runtime context

Install the initial dependencies in a Python 3.12 virtual environment:

Terminal
python -m venv .venv
source .venv/bin/activate

pip install "langgraph>=1,<2" "langchain>=1,<2" \
    langchain-openai pydantic-settings python-dotenv pytest

On Windows PowerShell, activate the environment using .venv\Scripts\Activate.ps1.

Create support_agent/state.py:

Python
from dataclasses import dataclass
from typing import Literal

from langgraph.graph import MessagesState

class SupportState(MessagesState):
    pass

@dataclass(frozen=True)
class SupportContext:
    language: Literal["English", "Spanish"] = "English"

SupportState inherits the message field and reducer provided by MessagesState.

The runtime context contains request-specific information that influences execution without becoming part of the graph’s evolving message history.

As the application expands, runtime context might contain verified tenant identifiers, user roles, or approved feature selections.

However, identity information must originate from a trusted authentication and authorization layer. Merely placing a tenant identifier in runtime context does not establish tenant isolation.

Step 2: Centralize model initialization

Model construction should not be scattered across node implementations.

Create support_agent/models.py:

Python
import os
from functools import lru_cache

from langchain.chat_models import init_chat_model

@lru_cache(maxsize=8)
def get_model(model_name: str, timeout_seconds: float):
    if not os.getenv("OPENAI_API_KEY"):
        raise RuntimeError("OPENAI_API_KEY is required")

    return init_chat_model(
        model_name,
        timeout=timeout_seconds,
        max_retries=2,
    )

The model is initialized lazily when first requested. Subsequent calls with the same arguments reuse the cached model instance within that Python process.

This reduces repeated initialization work and allows model selection to remain centralized.

The cache does not cache model responses, persist across process restarts, or coordinate different server workers. Each worker process maintains its own cache.

The factory currently supports the OpenAI provider. If you introduce additional providers, extend credential validation accordingly.

Step 3: Implement independent graph nodes

Create support_agent/nodes.py.

This implementation receives settings and an optional model-response function through dependency injection.

Python
from langchain.messages import SystemMessage
from langgraph.runtime import Runtime

from support_agent.config import Settings
from support_agent.models import get_model
from support_agent.state import SupportState, SupportContext

def make_answer_node(settings: Settings, respond=None):

    async def answer(
        state: SupportState,
        runtime: Runtime[SupportContext],
    ):
        context = runtime.context or SupportContext()

        if context.language not in {"English", "Spanish"}:
            raise ValueError("Unsupported response language")

        system_message = SystemMessage(
            content=(
                "You are a professional customer support assistant. "
                "Do not invent company policies or account information. "
                f"Respond in {context.language}."
            )
        )

        messages = [system_message, *state["messages"]]

        if respond is not None:
            response = await respond(messages)
        else:
            model = get_model(
                settings.model_name,
                settings.model_timeout_seconds,
            )
            response = await model.ainvoke(messages)

        return {"messages": [response]}

    return answer

The node does not read environment variables directly. It receives validated settings, while the model factory handles provider initialization.

Dependency injection also makes it possible to replace the real model with a deterministic test implementation.

The asynchronous model call is appropriate for a network-bound workload and helps avoid blocking the server’s event loop.

Step 4: Export the compiled graph

Create support_agent/graph.py:

Python
from langgraph.graph import StateGraph, START, END

from support_agent.config import Settings
from support_agent.nodes import make_answer_node
from support_agent.state import SupportState, SupportContext

def build_graph(
    settings: Settings | None = None,
    *,
    respond=None,
    checkpointer=None,
):
    settings = settings if settings is not None else Settings()

    builder = StateGraph(
        SupportState,
        context_schema=SupportContext,
    )

    builder.add_node(
        "answer",
        make_answer_node(settings, respond),
    )

    builder.add_edge(START, "answer")
    builder.add_edge("answer", END)

    return builder.compile(checkpointer=checkpointer)

graph = build_graph()

The module exposes two useful interfaces:

  • build_graph() constructs isolated graph instances for tests or custom hosting.
  • graph provides a compiled application object that Agent Server can discover.

Keep deployment entry points importable. Avoid interactive input, background jobs, database migrations, and model requests at module import time.

Importing graph.py should construct the application, not execute an agent run.

Environment configuration

Why environments exist

A production application commonly operates in several independent environments.

Configuration Development Staging Production
Primary purpose Implementation Release validation Real workloads
Data Synthetic Sanitized Authorized customer data
Credentials Developer keys Staging keys Production secrets
Logging Debug Info Info or warning
Model access Budget-limited Production-like Approved models
Database Local or temporary Isolated database Durable database
Availability Best effort Production-like Operational requirements

The same application code should generally run in every environment.

What changes is its configuration and infrastructure, not its core business logic.

For example, developers should not modify Python source files whenever the production model changes. Instead, the deployment environment supplies a different model identifier.

This approach supports promoting the same tested application artifact from staging to production.

Application settings, runtime context, and state

LangGraph applications have several distinct configuration mechanisms.

Confusing them creates security, persistence, and maintainability problems.

Mechanism Scope Example
Environment variables Deployment process Model name, API credentials
Runtime context Invocation Response language, verified user identity
Graph state Workflow execution Messages, decisions, intermediate results
Runnable configuration Execution controls Recursion limit, thread ID
langgraph.json Deployment definition Graph paths, Python version

A database password belongs in deployment secrets, not graph state.

A conversation message belongs in state, not environment variables.

Request-specific data belongs in runtime context, rather than being passed through config["configurable"].

The configurable.thread_id field remains appropriate for identifying persistent LangGraph threads.

The following diagram shows these configuration boundaries.

Environment configuration diagram: Environment variables to Typed settings; Typed settings to Graph factory; Graph factory to Compiled graph; Runtime context to Compiled graph; Runnable config to Compiled graph; Input state to Compiled graph; Compiled graph to Graph nodes; Graph nodes to Updated state.

Managing environment variables with dotenv

Create .env.example:

DOTENV
APP_ENV=development
MODEL_NAME=openai:gpt-5.4-mini
MODEL_TIMEOUT_SECONDS=30
LOG_LEVEL=DEBUG

OPENAI_API_KEY=

LANGSMITH_TRACING=false
LANGSMITH_API_KEY=
LANGSMITH_PROJECT=support-agent-development

Copy this template into a local environment file:

Terminal
cp .env.example .env

Populate the local API key using an authorized provider credential.

The .env.example file documents the variables developers need. The actual .env file contains private configuration and must not enter version control.

Create .gitignore:

Text
.env
.env.*
!.env.example

.venv/
__pycache__/
.pytest_cache/
*.pyc
*.sqlite
*.sqlite3
build/
dist/
*.egg-info/

Production deployments should inject credentials using their platform’s secret-management facilities rather than distributing development environment files.

Note: Environment variables are a configuration delivery mechanism, not a secret-management system. Access controls, credential rotation, auditability, and secure injection must be provided by the surrounding infrastructure.

Typed configuration using Pydantic Settings

Environment variables arrive as strings. Without validation, incorrect values may remain undetected until a node executes.

For example, an accidentally configured negative timeout should be rejected before contacting a model provider.

Create support_agent/config.py:

Python
from typing import Literal

from pydantic import Field, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict

class Settings(BaseSettings):
    model_config = SettingsConfigDict(
        case_sensitive=False,
        extra="ignore",
        frozen=True,
    )

    app_env: Literal[
        "development", "staging", "production"
    ] = "development"

    model_name: str = "openai:gpt-5.4-mini"

    model_timeout_seconds: float = Field(
        default=30,
        gt=0,
        le=120,
    )

    log_level: Literal[
        "DEBUG", "INFO", "WARNING", "ERROR"
    ] = "INFO"

    @field_validator("model_name")
    @classmethod
    def validate_model_name(cls, value: str) -> str:
        if not value.startswith("openai:"):
            raise ValueError("An OpenAI model identifier is required")

        if not value.split(":", 1)[1].strip():
            raise ValueError("Model name cannot be empty")

        return value

if __name__ == "__main__":
    settings = Settings()
    print(settings.model_dump_json(indent=2))

The settings model provides automatic type conversion, validation, defaults, and protection against accidental attribute mutation.

Run it from the project root:

Terminal
APP_ENV=staging MODEL_TIMEOUT_SECONDS=45 \
python -m support_agent.config

With no other relevant environment overrides, the expected output is:

JSON
{
  "app_env": "staging",
  "model_name": "openai:gpt-5.4-mini",
  "model_timeout_seconds": 45.0,
  "log_level": "INFO"
}

The value "45" was automatically converted into a floating-point number.

Now try an invalid value:

Terminal
MODEL_TIMEOUT_SECONDS=-10 python -m support_agent.config

Pydantic raises a validation error because the timeout must be positive.

Importantly, Settings() does not automatically load .env in this implementation. Local entry points explicitly load the file, while production processes consume their injected environment variables.

Provider credentials remain outside the settings model, reducing the risk of exposing them when printing configuration.

The timeout controls the model request, not the total duration of an agent run. Likewise, log_level declares an operational preference; a logging configuration must consume it before it changes actual logging behavior.

Running the application locally

Create scripts/smoke_test.py.

This script loads local settings and verifies that the complete graph can execute a request.

Python
import asyncio

from dotenv import load_dotenv

async def main():
    load_dotenv(override=False)

    from langchain.messages import HumanMessage
    from support_agent.graph import graph
    from support_agent.state import SupportContext

    result = await graph.ainvoke(
        {
            "messages": [
                HumanMessage(
                    content="How can I contact customer support?"
                )
            ]
        },
        config={"recursion_limit": 10},
        context=SupportContext(language="English"),
    )

    print(result["messages"][-1].content)

if __name__ == "__main__":
    asyncio.run(main())

Once the project is installed as described in the Dependencies section, run:

Terminal
python -m scripts.smoke_test

With valid credentials and model access, the expected result is a natural-language support response.

The exact wording varies because model generation is not deterministic. If your provider account cannot access the configured model, set MODEL_NAME to an authorized OpenAI model identifier.

Testing without external API calls

Automated tests should not require production credentials or incur model charges for every execution.

Create tests/test_graph.py:

Python
import asyncio

from langchain.messages import AIMessage, HumanMessage

from support_agent.config import Settings
from support_agent.graph import build_graph
from support_agent.state import SupportContext

async def fake_response(messages):
    assert "Spanish" in messages[0].content

    return AIMessage(
        content="Hola, ¿cómo puedo ayudarte?"
    )

def test_support_graph():
    graph = build_graph(
        Settings(app_env="development"),
        respond=fake_response,
    )

    result = asyncio.run(
        graph.ainvoke(
            {"messages": [HumanMessage(content="Hello")]},
            context=SupportContext(language="Spanish"),
        )
    )

    assert len(result["messages"]) == 2

    assert (
        result["messages"][-1].content
        == "Hola, ¿cómo puedo ayudarte?"
    )

Run:

Terminal
python -m pytest tests/test_graph.py -v

Expected result:

Text
tests/test_graph.py::test_support_graph PASSED

1 passed

This test verifies graph construction, state updates, runtime context handling, and dependency injection without contacting an external provider.

In production projects, complement deterministic tests with a smaller set of real-provider integration tests.

LangGraph application configuration: langgraph.json

What is langgraph.json?

langgraph.json is the application manifest consumed by the LangGraph CLI and associated Agent Server build tooling.

It describes how the application should be packaged and which graphs should be exposed.

It is not a graph definition, a Python dependency lockfile, or an operating-system environment manager.

The graph’s nodes and edges remain defined in Python.

Create the production-safe langgraph.json in the project root:

JSON
{
  "$schema": "https://langgra.ph/schema.json",
  "python_version": "3.12",
  "dependencies": ["."],
  "graphs": {
    "support_agent": "./support_agent/graph.py:graph"
  }
}

This manifest intentionally excludes local environment files. Staging and production environments can supply their settings externally.

The current configuration options are documented in the LangGraph CLI configuration reference.

Understanding the configuration fields

Schema

JSON
{
  "$schema": "https://langgra.ph/schema.json"
}

The schema declaration helps compatible editors provide configuration validation and autocomplete.

Python version

JSON
{
  "python_version": "3.12"
}

This selects the Python version for the server image build.

Use the same Python version in local development and automated testing to reduce compatibility problems.

Dependencies

JSON
{
  "dependencies": ["."]
}

The period identifies the project directory as a local dependency source. The build tooling can discover the project’s Python packaging and dependency declarations there.

It does not mean that every package installed in your developer’s virtual environment will automatically become available in production.

Graph registration

JSON
{
  "graphs": {
    "support_agent": "./support_agent/graph.py:graph"
  }
}

The registration contains three elements:

  • support_agent: The public graph identifier.
  • ./support_agent/graph.py: The Python source file.
  • graph: The exported compiled graph object.

Agent Server uses this registration to discover the graph and make it available to its execution APIs.

A single application can register multiple graph entry points. Each entry point needs a unique identifier and a valid import target.

Treat graph identifiers as part of your application contract. Renaming an identifier can break clients and existing assistant configurations.

Local development configuration

Create a separate langgraph.local.json:

JSON
{
  "$schema": "https://langgra.ph/schema.json",
  "python_version": "3.12",
  "dependencies": ["."],
  "graphs": {
    "support_agent": "./support_agent/graph.py:graph"
  },
  "env": "./.env"
}

The env field identifies the environment file used for local execution.

The default CLI configuration filename is langgraph.json. An alternative manifest can be selected explicitly:

Terminal
langgraph dev --config langgraph.local.json

The next lesson will cover CLI installation, server startup, and API interaction in detail.

For now, understand that these two manifests describe the same application while allowing different configuration-delivery mechanisms.

Additional application configuration

The manifest supports optional capabilities beyond graph registration.

Field Purpose
env Environment file or variable mapping
auth Custom authentication and authorization
http HTTP server customization
store Long-term memory indexing and retention
checkpointer Checkpoint backend and retention configuration
dockerfile_lines Additional container build instructions
pip_config_file Custom Python package installer configuration
source Lockfile-based dependency installation

Only configure features your application actually requires.

For example, an application requiring semantic memory search can extend its manifest with an indexing configuration:

JSON
{
  "$schema": "https://langgra.ph/schema.json",
  "python_version": "3.12",
  "dependencies": ["."],
  "graphs": {
    "support_agent": "./support_agent/graph.py:graph"
  },
  "store": {
    "index": {
      "embed": "openai:text-embedding-3-small",
      "dims": 1536
    }
  }
}

The embedding configuration defines how the server-managed store indexes searchable memory.

The embedding provider must be accessible, and the configured dimensions must match the embedding model’s output.

This configuration does not automatically store conversation messages as semantic memory. Your application must still write appropriate items to the store, typically through runtime.store.

PostgreSQL, Redis, and persistence ownership

A significant architectural decision concerns which component manages persistence.

When deploying through LangSmith Agent Server, the server provides managed checkpointing and storage infrastructure. PostgreSQL normally provides durable persistence, while Redis supports internal coordination and communication.

Consequently, the deployable graph in this lesson is compiled without explicitly attaching an in-memory or PostgreSQL checkpointer.

When executing LangGraph directly, outside Agent Server, your application is responsible for selecting and managing persistence.

Execution environment Persistence responsibility
Standalone unit tests Application or test fixture
Direct local execution Application
Custom API hosting Application
LangGraph development server Development server
Production Agent Server Agent Server infrastructure

For example, the graph factory can construct a standalone graph with temporary checkpointing:

Python
import asyncio

from langchain.messages import AIMessage, HumanMessage
from langgraph.checkpoint.memory import InMemorySaver

from support_agent.graph import build_graph
from support_agent.state import SupportContext

async def respond(messages):
    return AIMessage(content="Support request received.")

async def main():
    graph = build_graph(
        respond=respond,
        checkpointer=InMemorySaver(),
    )

    config = {
        "configurable": {
            "thread_id": "support-demo-001"
        },
        "recursion_limit": 10,
    }

    await graph.ainvoke(
        {"messages": [HumanMessage(content="Hello")]},
        config,
        context=SupportContext(),
    )

    snapshot = await graph.aget_state(config)
    print(len(snapshot.values["messages"]))

if __name__ == "__main__":
    asyncio.run(main())

Expected output:

Text
2

The checkpointer retains the user message and agent response in memory.

It is appropriate for temporary testing but not durable production storage.

A directly hosted production application may instead require PostgresSaver or AsyncPostgresSaver, connection lifecycle management, and database initialization using .setup().

Redis is not a mandatory dependency for every standalone LangGraph application. Introduce it when your deployment architecture requires coordination, caching, or other Redis-backed capabilities.

Dependencies

Declaring project dependencies

Production deployments must reconstruct the application’s Python environment from declared dependencies.

A modern Python project commonly uses pyproject.toml for packaging metadata and dependency management.

Create the following file:

TOML
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"

[project]
name = "support-agent"
version = "0.1.0"
description = "Production-oriented LangGraph support agent"
requires-python = ">=3.12,<3.13"

dependencies = [
    "langgraph>=1,<2",
    "langchain>=1,<2",
    "langchain-openai",
    "pydantic>=2,<3",
    "pydantic-settings>=2,<3",
    "python-dotenv>=1,<2"
]

[project.optional-dependencies]
dev = [
    "pytest",
    "langgraph-cli[inmem]>=0.4.20"
]

[tool.setuptools.packages.find]
include = ["support_agent*"]

[tool.pytest.ini_options]
testpaths = ["tests"]

Install the project in editable mode with its development dependencies:

Terminal
pip install -e ".[dev]"

Verify the environment:

Terminal
pip check
python -m pytest
python -m scripts.smoke_test

Editable installation allows developers to modify application source code without reinstalling the package after every change.

The declaration also ensures that the OpenAI integration is installed explicitly. Installing LangGraph alone does not guarantee the availability of every model provider integration.

Version constraints and reproducibility

There is an important difference between declaring acceptable versions and locking exact versions.

For example:

Text
langgraph>=1,<2

This permits compatible releases across the LangGraph 1.x series. Two installations performed at different times may resolve different package versions.

That flexibility is useful during development, but production releases should use a tested dependency resolution.

Strategy Characteristics
Unrestricted dependencies Flexible but unpredictable
Version ranges Express intended compatibility
Exact version pins Fix individual package versions
Dependency lockfile Records resolved dependency versions

A practical approach is to maintain compatibility ranges in pyproject.toml and commit a dependency lockfile.

For example, using uv:

Terminal
pip install uv

uv lock
uv sync --extra dev
uv run --extra dev pytest

Commit the generated uv.lock file alongside the project.

For Agent Server image builds using a sufficiently recent CLI, configure lockfile-based installation explicitly:

JSON
{
  "$schema": "https://langgra.ph/schema.json",
  "python_version": "3.12",
  "source": {
    "kind": "uv"
  },
  "graphs": {
    "support_agent": "./support_agent/graph.py:graph"
  }
}

The source configuration replaces dependencies; do not specify both in this manifest.

This allows supported Agent Server builds to install the dependency resolution recorded in uv.lock.

Simply adding a lockfile to a project using the ordinary dependencies configuration does not guarantee that the image build will honor that lockfile.

For full reproducibility, also control the Python runtime, base image, system packages, and build tooling.

Installing infrastructure dependencies only when required

Not every agent requires PostgreSQL client libraries, Redis clients, embedding integrations, or web frameworks.

For standalone applications managing PostgreSQL persistence, additional packages may include:

Terminal
pip install langgraph-checkpoint-postgres "psycopg[binary,pool]"

For application-owned Redis integrations:

Terminal
pip install redis

When introducing these packages, update the project’s dependency declarations and regenerate its lockfile.

Avoid shipping unused integrations merely because the surrounding Agent Server infrastructure uses those technologies.

Smaller dependency surfaces reduce maintenance overhead, build complexity, and potential security vulnerabilities.

Tip: Upgrade dependencies deliberately in a separate change, regenerate the lockfile, run automated tests, and validate the resulting application before promoting it to production.

Common production mistakes

Hardcoding secrets and environment settings

Do not embed API keys, production database URLs, or credentials in Python files, prompts, graph state, or deployment manifests.

Use externally supplied secrets and validated settings.

Creating expensive resources during imports

Calling models or opening database connections when importing graph.py can make testing, worker startup, and application discovery unreliable.

Initialize resources lazily or through the hosting application’s lifecycle management.

Accidentally relying on local dependencies

A graph may work on a developer’s machine because an undeclared package was installed months earlier.

Verify installation and execution in a fresh environment.

Mixing persistence responsibilities

Attaching InMemorySaver unconditionally to every graph is inappropriate for production Agent Server deployment and prevents proper durable persistence in standalone multi-worker applications.

Separate graph construction from infrastructure selection.

Treating configuration as authorization

Environment variables, assistant settings, and runtime context are not substitutes for authentication, permission checks, or tenant-aware data access.

Authorization must be enforced at trusted application boundaries and within sensitive services.

Preparing for the next lesson

The project now exposes an importable compiled graph, validates application settings, separates local and deployment configuration, and declares its Python dependencies.

Before deployment, verify the graph import target:

Terminal
python -c "from support_agent.graph import graph; print(type(graph).__name__)"

Expected output:

Text
CompiledStateGraph

Validate both manifests as JSON:

Terminal
python -m json.tool langgraph.json
python -m json.tool langgraph.local.json

These commands validate JSON syntax, not the complete Agent Server configuration schema. Server-specific validation occurs through the relevant build and startup tooling.

The examples use Python 3.12, OpenAI models, a conventional Python package structure, and separate local and production manifests. These are architectural choices for this course project, rather than mandatory requirements for all LangGraph applications. The examples have been designed against the documented LangGraph 1.x interfaces; live provider execution and an Agent Server deployment have not been performed here.

For additional implementation details, consult the official application structure documentation, LangGraph CLI reference, and Agent Server infrastructure documentation.

In the next lesson, LangGraph CLI and the Agent Server, you will take this project and turn it into a running server, explore its execution endpoints, create persistent threads, and interact with the deployed graph through client APIs.

That server will become the foundation for the chapter’s hands-on project: deploying a complete LangGraph AI agent as an API with a user interface.

Exercise

Build an environment-aware deployment configuration

Create a Python configuration generator that produces valid LangGraph application manifests for development, staging, and production. Include a local environment file only in development, validate the target environment, and ensure that credentials never appear in generated configuration files. Write each configuration to a separate JSON file and verify its contents using assertions.

Python
import json
from pathlib import Path

ENVIRONMENTS = {"development", "staging", "production"}

def build_manifest(environment: str) -> dict:
    # TODO: Validate the environment.
    # TODO: Declare the Python version and dependencies.
    # TODO: Register the support agent graph.
    # TODO: Include .env only for development.
    raise NotImplementedError

def save_manifest(environment: str) -> Path:
    # TODO: Generate and save the configuration.
    raise NotImplementedError

if __name__ == "__main__":
    for environment in sorted(ENVIRONMENTS):
        path = save_manifest(environment)
        print(f"Created {path}")

Summary

  • Production LangGraph applications separate orchestration, business logic, configuration, integrations, and tests into maintainable modules.
  • Environment variables provide deployment-specific settings without requiring changes to application source code.
  • Typed configuration models validate operational settings before they cause runtime failures.
  • Runtime context carries request-specific information, while graph state represents evolving workflow data.
  • The langgraph.json manifest identifies deployable graphs, dependencies, runtime versions, and optional server configuration.
  • Agent Server manages persistence infrastructure, while directly hosted graphs require explicit persistence decisions.
  • Reproducible dependency management, isolated environments, and secure secret handling are essential for reliable deployments.