LangGraph CLI 是一个用于在本地构建和运行智能体服务器的命令行工具。生成的服务器公开运行、线程、助手等的所有 API 端点,并包括支持服务,例如用于检查点和存储的托管数据库。

安装

  1. 确保已安装 Docker(例如,docker --version)。
  2. 安装 CLI:
    pip install langgraph-cli
    
  3. 验证安装
    langgraph --help
    

快速命令

命令作用
langgraph dev启动轻量级本地开发服务器(无需 Docker),非常适合快速测试。
langgraph build构建 LangGraph API 服务器的 Docker 镜像以进行部署。
langgraph dockerfile根据您的配置生成 Dockerfile 以进行自定义构建。
langgraph up在 Docker 中本地启动 LangGraph API 服务器。需要运行 Docker;本地开发需要 LangSmith API 密钥;生产环境需要许可证。
对于 JS,使用 npx @langchain/langgraph-cli <command>(如果全局安装,则使用 langgraphjs)。

配置文件

要构建和运行有效的应用程序,LangGraph CLI 需要一个遵循此架构的 JSON 配置文件。它包含以下属性:
LangGraph CLI 默认使用当前目录中名为 langgraph.json 的配置文件。
  • Python
  • JS
KeyDescription
dependenciesRequired. Array of dependencies for LangSmith API server. Dependencies can be one of the following:
  • A single period ("."), which will look for local Python packages.
  • The directory path where pyproject.toml, setup.py or requirements.txt is located.
    For example, if requirements.txt is located in the root of the project directory, specify "./". If it’s located in a subdirectory called local_package, specify "./local_package". Do not specify the string "requirements.txt" itself.
  • A Python package name.
graphsRequired. Mapping from graph ID to path where the compiled graph or a function that makes a graph is defined. Example:
  • ./your_package/your_file.py:variable, where variable is an instance of langgraph.graph.state.CompiledStateGraph
  • ./your_package/your_file.py:make_graph, where make_graph is a function that takes a config dictionary (langchain_core.runnables.RunnableConfig) and returns an instance of langgraph.graph.state.StateGraph or langgraph.graph.state.CompiledStateGraph. See how to rebuild a graph at runtime for more details.
auth(Added in v0.0.11) Auth configuration containing the path to your authentication handler. Example: ./your_package/auth.py:auth, where auth is an instance of langgraph_sdk.Auth. See authentication guide for details.
base_imageOptional. Base image to use for the LangGraph API server. Defaults to langchain/langgraph-api or langchain/langgraphjs-api. Use this to pin your builds to a particular version of the langgraph API, such as "langchain/langgraph-server:0.2". See https://hub.docker.com/r/langchain/langgraph-server/tags for more details. (added in langgraph-cli==0.2.8)
image_distroOptional. Linux distribution for the base image. Must be one of "debian", "wolfi", "bookworm", or "bullseye". If omitted, defaults to "debian". Available in langgraph-cli>=0.2.11.
envPath to .env file or a mapping from environment variable to its value.
storeConfiguration for adding semantic search and/or time-to-live (TTL) to the BaseStore. Contains the following fields:
  • index (optional): Configuration for semantic search indexing with fields embed, dims, and optional fields.
  • ttl (optional): Configuration for item expiration. An object with optional fields: refresh_on_read (boolean, defaults to true), default_ttl (float, lifespan in minutes; applied to newly created items only; existing items are unchanged; defaults to no expiration), and sweep_interval_minutes (integer, how often to check for expired items, defaults to no sweeping).
uiOptional. Named definitions of UI components emitted by the agent, each pointing to a JS/TS file. (added in langgraph-cli==0.1.84)
python_version3.11, 3.12, or 3.13. Defaults to 3.11.
node_versionSpecify node_version: 20 to use LangGraph.js.
pip_config_filePath to pip config file.
pip_installer(Added in v0.3) Optional. Python package installer selector. It can be set to "auto", "pip", or "uv". From version 0.3 onward the default strategy is to run uv pip, which typically delivers faster builds while remaining a drop-in replacement. In the uncommon situation where uv cannot handle your dependency graph or the structure of your pyproject.toml, specify "pip" here to revert to the earlier behaviour.
keep_pkg_tools(Added in v0.3.4) Optional. Control whether to retain Python packaging tools (pip, setuptools, wheel) in the final image. Accepted values:
  • true : Keep all three tools (skip uninstall).
  • false / omitted : Uninstall all three tools (default behaviour).
  • list[str] : Names of tools to retain. Each value must be one of “pip”, “setuptools”, “wheel”.
. By default, all three tools are uninstalled.
dockerfile_linesArray of additional lines to add to Dockerfile following the import from parent image.
checkpointerConfiguration for the checkpointer. Supports:
  • ttl (optional): Object with strategy, sweep_interval_minutes, default_ttl controlling checkpoint expiry.
  • serde (optional, 0.5+): Object with allowed_json_modules and pickle_fallback to tune deserialization behavior.
httpHTTP server configuration with the following fields:
  • app: Path to custom Starlette/FastAPI app (e.g., "./src/agent/webapp.py:app"). See custom routes guide.
  • cors: CORS configuration with fields such as allow_origins, allow_methods, allow_headers, allow_credentials, allow_origin_regex, expose_headers, and max_age.
  • configurable_headers: Define which request headers to expose as configurable values via includes / excludes patterns.
  • logging_headers: Mirror of configurable_headers for excluding sensitive headers from logs.
  • middleware_order: Choose how custom middleware and auth interact. auth_first runs authentication hooks before custom middleware, while middleware_first (default) runs your middleware first.
  • enable_custom_route_auth: Apply auth checks to routes added through app.
  • disable_assistants, disable_mcp, disable_meta, disable_runs, disable_store, disable_threads, disable_ui, disable_webhooks: Disable built-in routes or hooks.
  • mount_prefix: Prefix for mounted routes (e.g., “/my-deployment/api”).
api_version(Added in v0.3.7) Which semantic version of the LangGraph API server to use (e.g., "0.3"). Defaults to latest. Check the server changelog for details on each release.

Examples

  • Python
  • JS

Basic configuration

{
  "$schema": "https://langgra.ph/schema.json",
  "dependencies": ["."],
  "graphs": {
    "chat": "chat.graph:graph"
  }
}

Using Wolfi base images

You can specify the Linux distribution for your base image using the image_distro field. Valid options are debian, wolfi, bookworm, or bullseye. Wolfi is the recommended option as it provides smaller and more secure images. This is available in langgraph-cli>=0.2.11.
{
  "$schema": "https://langgra.ph/schema.json",
  "dependencies": ["."],
  "graphs": {
    "chat": "chat.graph:graph"
  },
  "image_distro": "wolfi"
}

Adding semantic search to the store

All deployments come with a DB-backed BaseStore. Adding an “index” configuration to your langgraph.json will enable semantic search within the BaseStore of your deployment.The index.fields configuration determines which parts of your documents to embed:
  • If omitted or set to ["$"], the entire document will be embedded
  • To embed specific fields, use JSON path notation: ["metadata.title", "content.text"]
  • Documents missing specified fields will still be stored but won’t have embeddings for those fields
  • You can still override which fields to embed on a specific item at put time using the index parameter
{
  "dependencies": ["."],
  "graphs": {
    "memory_agent": "./agent/graph.py:graph"
  },
  "store": {
    "index": {
      "embed": "openai:text-embedding-3-small",
      "dims": 1536,
      "fields": ["$"]
    }
  }
}
Common model dimensions
  • openai:text-embedding-3-large: 3072
  • openai:text-embedding-3-small: 1536
  • openai:text-embedding-ada-002: 1536
  • cohere:embed-english-v3.0: 1024
  • cohere:embed-english-light-v3.0: 384
  • cohere:embed-multilingual-v3.0: 1024
  • cohere:embed-multilingual-light-v3.0: 384

Semantic search with a custom embedding function

If you want to use semantic search with a custom embedding function, you can pass a path to a custom embedding function:
{
  "dependencies": ["."],
  "graphs": {
    "memory_agent": "./agent/graph.py:graph"
  },
  "store": {
    "index": {
      "embed": "./embeddings.py:embed_texts",
      "dims": 768,
      "fields": ["text", "summary"]
    }
  }
}
The embed field in store configuration can reference a custom function that takes a list of strings and returns a list of embeddings. Example implementation:
# embeddings.py
def embed_texts(texts: list[str]) -> list[list[float]]:
    """Custom embedding function for semantic search."""
    # Implementation using your preferred embedding model
    return [[0.1, 0.2, ...] for _ in texts]  # dims-dimensional vectors

Adding custom authentication

{
  "$schema": "https://langgra.ph/schema.json",
  "dependencies": ["."],
  "graphs": {
    "chat": "chat.graph:graph"
  },
  "auth": {
    "path": "./auth.py:auth",
    "openapi": {
      "securitySchemes": {
        "apiKeyAuth": {
          "type": "apiKey",
          "in": "header",
          "name": "X-API-Key"
        }
      },
      "security": [{ "apiKeyAuth": [] }]
    },
    "disable_studio_auth": false
  }
}
有关详细说明,请参阅身份验证概念指南,并参考设置自定义身份验证以获取完整的实践流程。

配置存储项的存活时间(TTL)

您可以使用 store.ttl 键为 BaseStore 中的项/记忆配置默认的数据过期时间。这将决定项目在最后一次访问后保留多长时间(读取操作可能会基于 refresh_on_read 刷新计时器)。请注意,这些默认值可以在每次调用时通过修改 getsearch 等方法中的相应参数来覆盖。ttl 配置是一个包含可选字段的对象:
  • refresh_on_read:如果为 true(默认值),通过 getsearch 访问项目会重置其过期计时器。设置为 false 时,仅在写入(put)时刷新 TTL。
  • default_ttl:项目的默认寿命(单位:分钟)。仅适用于新创建的项目;现有项目不会被修改。如果未设置,项目默认不会过期。
  • sweep_interval_minutes:系统运行后台进程以删除过期项目的频率(单位:分钟)。如果未设置,则不会自动进行清理。
下面示例启用了 7 天(10080 分钟)的 TTL,会在读取时刷新,并且每小时清理一次:
{
  "$schema": "https://langgra.ph/schema.json",
  "dependencies": ["."],
  "graphs": {
    "memory_agent": "./agent/graph.py:graph"
  },
  "store": {
    "ttl": {
      "refresh_on_read": true,
      "sweep_interval_minutes": 60,
      "default_ttl": 10080
    }
  }
}

配置检查点存活时间(TTL)

您可以使用 checkpointer 键为检查点配置存活时间。这决定了检查点数据保留多长时间(例如,删除)。支持两个可选子对象:
  • ttl:包含 strategysweep_interval_minutesdefault_ttl,共同设置检查点过期。
  • serde (Agent server 0.5+) :让您控制检查点负载的反序列化行为。
下面示例设置默认 TTL 为 30 天(43200 分钟):
{
  "$schema": "https://langgra.ph/schema.json",
  "dependencies": ["."],
  "graphs": {
    "chat": "chat.graph:graph"
  },
  "checkpointer": {
    "ttl": {
      "strategy": "delete",
      "sweep_interval_minutes": 10,
      "default_ttl": 43200
    }
  }
}
在这个示例中,检查点超过 30 天的将被删除,并且每 10 分钟运行一次检查。

配置检查点 serde

checkpointer.serde 对象形状反序列化:
  • allowed_json_modules 定义了您希望服务器能够从 “json” 模式下保存的负载中反序列化的自定义 Python 对象的允许列表。这是一个 [path, to, module, file, symbol] 序列的列表。如果省略,则只允许 LangChain 安全默认值。您可以不安全地设置为 true 以允许任何模块被反序列化。
  • pickle_fallback:JSON 解码失败时是否回退到 pickle 反序列化。
{
  "checkpointer": {
    "serde": {
      "allowed_json_modules": [
        ["my_agent", "auth", "SessionState"]
      ]
    }
  }
}

自定义 HTTP 中间件和头

http 块让您可以微调请求处理:
  • middleware_order:选择 "auth_first" 在您的中间件之前运行身份验证,或 "middleware_first"(默认)反转顺序。
  • enable_custom_route_auth:扩展身份验证以通过 http.app 挂载的路由。
  • configurable_headers / logging_headers:每个都接受一个包含可选 includesexcludes 数组的对象;通配符受支持,排除项先于包含项。
  • cors:除了 allow_originsallow_methodsallow_headers 外,您还可以设置 allow_credentialsallow_origin_regexexpose_headersmax_age 进行更详细的浏览器控制。

固定 API 版本

(Added in v0.3.7)您可以通过使用 api_version 键来固定 Agent Server 的 API 版本。这很有用,如果您希望服务器使用特定版本的 API。 默认情况下,Cloud 部署使用服务器最新稳定版本。这可以通过将 api_version 键设置为特定版本来进行固定。
{
  "$schema": "https://langgra.ph/schema.json",
  "dependencies": ["."],
  "graphs": {
    "chat": "chat.graph:graph"
  },
  "api_version": "0.2"
}

Commands

Usage
  • Python
  • JS
The base command for the LangGraph CLI is langgraph.
langgraph [OPTIONS] COMMAND [ARGS]

dev

  • Python
  • JS
Run LangGraph API server in development mode with hot reloading and debugging capabilities. This lightweight server requires no Docker installation and is suitable for development and testing. State is persisted to a local directory.
Currently, the CLI only supports Python >= 3.11.
InstallationThis command requires the “inmem” extra to be installed:
pip install -U "langgraph-cli[inmem]"
Usage
langgraph dev [OPTIONS]
Options
OptionDefaultDescription
-c, --config FILElanggraph.jsonPath to configuration file declaring dependencies, graphs and environment variables
--host TEXT127.0.0.1Host to bind the server to
--port INTEGER2024Port to bind the server to
--no-reloadDisable auto-reload
--n-jobs-per-worker INTEGERNumber of jobs per worker. Default is 10
--debug-port INTEGERPort for debugger to listen on
--wait-for-clientFalseWait for a debugger client to connect to the debug port before starting the server
--no-browserSkip automatically opening the browser when the server starts
--studio-url TEXTURL of the Studio instance to connect to. Defaults to https://smith.langchain.com
--allow-blockingFalseDo not raise errors for synchronous I/O blocking operations in your code (added in 0.2.6)
--tunnelFalseExpose the local server via a public tunnel (Cloudflare) for remote frontend access. This avoids issues with browsers like Safari or networks blocking localhost connections
--helpDisplay command documentation

build

  • Python
  • JS
Build LangSmith API server Docker image.Usage
langgraph build [OPTIONS]
Options
OptionDefaultDescription
--platform TEXTTarget platform(s) to build the Docker image for. Example: langgraph build --platform linux/amd64,linux/arm64
-t, --tag TEXTRequired. Tag for the Docker image. Example: langgraph build -t my-image
--pull / --no-pull--pullBuild with latest remote Docker image. Use --no-pull for running the LangSmith API server with locally built images.
-c, --config FILElanggraph.jsonPath to configuration file declaring dependencies, graphs and environment variables.
--build-command TEXT*Build command to run. Runs from the directory where your langgraph.json file lives. Example: langgraph build --build-command "yarn run turbo build"
--install-command TEXT*Install command to run. Runs from the directory where you call langgraph build from. Example: langgraph build --install-command "yarn install"
--helpDisplay command documentation.
*Only supported for JS deployments, will have no impact on Python deployments.

up

  • Python
  • JS
Start LangGraph API server. For local testing, requires a LangSmith API key with access to LangSmith. Requires a license key for production use.Usage
langgraph up [OPTIONS]
Options
OptionDefaultDescription
--waitWait for services to start before returning. Implies —detach
--base-image TEXTlangchain/langgraph-apiBase image to use for the LangGraph API server. Pin to specific versions using version tags.
--image TEXTDocker image to use for the langgraph-api service. If specified, skips building and uses this image directly.
--postgres-uri TEXTLocal databasePostgres URI to use for the database.
--watchRestart on file changes
--debugger-base-url TEXThttp://127.0.0.1:[PORT]URL used by the debugger to access LangGraph API.
--debugger-port INTEGERPull the debugger image locally and serve the UI on specified port
--verboseShow more output from the server logs.
-c, --config FILElanggraph.jsonPath to configuration file declaring dependencies, graphs and environment variables.
-d, --docker-compose FILEPath to docker-compose.yml file with additional services to launch.
-p, --port INTEGER8123Port to expose. Example: langgraph up --port 8000
--pull / --no-pullpullPull latest images. Use --no-pull for running the server with locally-built images. Example: langgraph up --no-pull
--recreate / --no-recreateno-recreateRecreate containers even if their configuration and image haven’t changed
--helpDisplay command documentation.

dockerfile

  • Python
  • JS
Generate a Dockerfile for building a LangSmith API server Docker image.Usage
langgraph dockerfile [OPTIONS] SAVE_PATH
Options
OptionDefaultDescription
-c, --config FILElanggraph.jsonPath to the configuration file declaring dependencies, graphs and environment variables.
--helpShow this message and exit.
Example:
langgraph dockerfile -c langgraph.json Dockerfile
This generates a Dockerfile that looks similar to:
FROM langchain/langgraph-api:3.11

ADD ./pipconf.txt /pipconfig.txt

RUN PIP_CONFIG_FILE=/pipconfig.txt PYTHONDONTWRITEBYTECODE=1 pip install --no-cache-dir -c /api/constraints.txt langchain_community langchain_anthropic langchain_openai wikipedia scikit-learn

ADD ./graphs /deps/__outer_graphs/src
RUN set -ex && \
    for line in '[project]' \
                'name = "graphs"' \
                'version = "0.1"' \
                '[tool.setuptools.package-data]' \
                '"*" = ["**/*"]'; do \
        echo "$line" >> /deps/__outer_graphs/pyproject.toml; \
    done

RUN PIP_CONFIG_FILE=/pipconfig.txt PYTHONDONTWRITEBYTECODE=1 pip install --no-cache-dir -c /api/constraints.txt -e /deps/*

ENV LANGSERVE_GRAPHS='{"agent": "/deps/__outer_graphs/src/agent.py:graph", "storm": "/deps/__outer_graphs/src/storm.py:graph"}'
The langgraph dockerfile command translates all the configuration in your langgraph.json file into Dockerfile commands. When using this command, you will have to re-run it whenever you update your langgraph.json file. Otherwise, your changes will not be reflected when you build or run the dockerfile.

Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.