LangGraph CLI and the Agent Server
Overview
Throughout this course, you have executed LangGraph applications directly from Python using methods such as graph.invoke(), graph.ainvoke(), and graph.stream().
These methods are excellent for development, experimentation, and testing. However, a production agent must typically serve requests from applications running outside its Python process.
Consider a customer support agent that must serve:
- A React customer support interface.
- An internal administrative dashboard.
- A mobile application.
- Automated workflows running in the background.
- Multiple customers with independent conversation histories.
Simply compiling a graph does not provide an HTTP server, authentication, background workers, persistent conversation endpoints, or remote execution management.
You could implement these capabilities yourself. Alternatively, you can deploy your graph using LangSmith Agent Server, a purpose-built runtime for serving agentic applications.
The LangGraph CLI provides the development and deployment tooling for this runtime.
The architecture changes from direct Python execution to network-based execution.
The graph still controls reasoning, tools, branching, state transitions, and agent behavior. Agent Server controls how that graph is exposed, executed, and managed as a service.
The previous lesson established a production project structure. This lesson turns that structure into a running API that the next lesson will connect to user interfaces.
The LangGraph CLI
The LangGraph CLI is a command-line interface for building and running Agent Server applications.
It is distributed separately from the core langgraph Python package because graph orchestration and application deployment are different responsibilities.
Installing the CLI
Create a Python 3.11 or newer virtual environment.
python -m venv .venv
source .venv/bin/activate
python -m pip install -U pip
pip install -U "langgraph-cli[inmem]"
pip install "langgraph>=1,<2" "langchain>=1,<2"
pip install langchain-openai langgraph-sdk httpxThe inmem extra installs the components required to run the lightweight development server without Docker.
Verify the installation:
langgraph --help
langgraph dev --help
langgraph deploy --helpThe CLI, SDK, Agent Server, and core LangGraph library have independent release cycles. Their version numbers do not necessarily match.
Important CLI commands
| Command | Purpose | Typical usage |
|---|---|---|
langgraph new |
Scaffold an application | Starting a new project |
langgraph dev |
Start a lightweight server | Daily development |
langgraph up |
Start a Docker-based server | Production-like testing |
langgraph build |
Build a server container image | Packaging releases |
langgraph dockerfile |
Generate a Dockerfile | Custom container builds |
langgraph deploy |
Deploy an Agent Server | LangSmith deployment |
For example:
langgraph new support-agent --template new-langgraph-project-pythonThis generates a starter project.
For an existing application, you do not need to generate another template. You can create its configuration file and run the CLI from the project directory.
The complete command options are maintained in the LangGraph CLI reference.
Preparing an Application for Agent Server
We will build a small customer support application exposing two graphs:
diagnostic: A deterministic graph for testing infrastructure and persistence without LLM costs.support: An LLM-powered customer support agent with a policy lookup tool.
Using both graphs helps distinguish infrastructure failures from model-related failures.
Project structure
Create the following files:
support-agent/
├── graph.py
├── langgraph.json
├── requirements.txt
├── .env
├── .gitignore
└── client.pyIn requirements.txt, declare the application dependencies:
langgraph>=1,<2
langchain>=1,<2
langchain-openaiThese constraints select the major versions used in this course. In production, resolve and lock the exact dependency versions that pass your integration tests.
Creating the graphs
The following complete graph.py file exports a deterministic graph and a tool-calling agent.
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain.messages import AIMessage
from langchain.tools import tool
from langgraph.graph import StateGraph, MessagesState, START, END
def acknowledge(state: MessagesState):
latest_message = state["messages"][-1]
return {
"messages": [
AIMessage(
content=f"Received: {latest_message.content}"
)
]
}
diagnostic_builder = StateGraph(MessagesState)
diagnostic_builder.add_node("acknowledge", acknowledge)
diagnostic_builder.add_edge(START, "acknowledge")
diagnostic_builder.add_edge("acknowledge", END)
diagnostic_graph = diagnostic_builder.compile()
@tool
def lookup_policy(topic: str) -> str:
"""Look up the shipping, billing, or returns policy."""
policies = {
"shipping": "Standard shipping takes 3-5 business days.",
"billing": "Invoices are available in the customer dashboard.",
"returns": "Unused products may be returned within 30 days.",
}
return policies.get(
topic.strip().lower(),
"No matching policy was found."
)
model = init_chat_model("openai:gpt-5.4-mini")
support_graph = create_agent(
model=model,
tools=[lookup_policy],
system_prompt=(
"You are a customer support assistant. "
"Use the policy lookup tool for policy questions. "
"Never invent company policies."
),
)The diagnostic graph returns an acknowledgment. The support agent can select a tool, interpret its result, and generate a customer-facing response.
For example, asking about returns should produce a response explaining the 30-day return policy.
Notice that neither graph explicitly installs a checkpointer or store.
When executing graphs directly, you may configure an InMemorySaver, PostgresSaver, or another persistence backend. With Agent Server, the runtime injects its configured persistence components.
This allows the server to manage checkpoints and thread operations consistently.
Registering graphs with langgraph.json
Create langgraph.json:
{
"dependencies": ["."],
"graphs": {
"diagnostic": "./graph.py:diagnostic_graph",
"support": "./graph.py:support_graph"
},
"env": ".env"
}Each configuration field has a specific responsibility:
dependencies: Identifies application dependencies. The current directory containsrequirements.txt.graphs: Maps externally accessible graph identifiers to Python graph implementations.env: Identifies the environment configuration file.
The expression ./graph.py:support_graph instructs the server to load the support_graph object from graph.py.
The key support becomes an externally accessible graph identifier. Clients can use it without knowing the Python module structure.
You can register multiple independent graphs in one Agent Server application.
See the application structure documentation for additional configuration patterns.
Environment configuration
Create .env:
OPENAI_API_KEY=your_openai_api_key
LANGSMITH_API_KEY=your_langsmith_api_key
LANGSMITH_TRACING=true
LANGSMITH_PROJECT=support-agent-devCreate .gitignore:
.env
.venv/
.langgraph_api/
__pycache__/
*.pycProvider credentials remain on the server. Remote clients do not need access to the OpenAI API key.
Note: The diagnostic graph deliberately avoids model calls, making it useful for repeatable infrastructure checks. The support graph requires valid provider credentials and access to the specified model. The examples follow the documented APIs but require execution in your own environment to verify installation and deployment compatibility.
The Local Development Server
Start the server from the project root:
langgraph devYou should see startup information containing URLs similar to:
API: http://127.0.0.1:2024
Docs: http://127.0.0.1:2024/docs
Studio Web UI: https://smith.langchain.com/studio/...Your graph application is now available over HTTP.
Unlike graph.invoke(), which executes inside the calling Python process, Agent Server receives requests from external clients and executes graphs through its runtime.
What happens during startup?
The development server:
- Reads
langgraph.json. - Loads environment variables.
- Imports the registered graph implementations.
- Initializes local runtime and persistence services.
- Exposes the Agent Server HTTP endpoints.
- Makes the registered graphs available for execution.
The server automatically reloads when application code changes.
You can customize its startup behavior:
langgraph dev --port 8000 --no-browserOr disable automatic reloading:
langgraph dev --no-reloadUse the default port 2024 for the remaining examples.
Exploring LangSmith Studio
LangSmith Studio provides a graphical interface for interacting with running graphs.
Open the Studio URL printed by the CLI.
Select the diagnostic graph and submit an input message. You can inspect the graph structure, node execution, intermediate state, and final output.
Switch to the support graph to inspect an agent invoking its policy lookup tool.
Studio is particularly useful when debugging conditional edges, tool calls, interrupts, and unexpected state transitions.
It is a development interface, not the customer-facing application you will eventually build.
Development server versus production-like server
| Capability | langgraph dev |
langgraph up |
|---|---|---|
| Docker required | No | Yes |
| Default port | 2024 | 8123 |
| Persistence | Local development storage | PostgreSQL |
| Redis infrastructure | Not required | Included in the local stack |
| Hot reloading | Enabled by default | Optional |
| Resource consumption | Lower | Higher |
| Production-like testing | Limited | Recommended |
The development server maintains state using lightweight local storage, including persistence to a local directory in current releases. It should not be treated as a production database or backup mechanism.
With Docker running, start the production-like environment:
langgraph upThis provisions the containerized Agent Server and its supporting services.
Use the development server for rapid iteration and the Docker-based environment to validate infrastructure behavior before deployment.
Refer to the local development and testing guide.
What the Agent Server Provides
Agent Server introduces several resources that are essential to understanding its API.
Graphs, assistants, threads, and runs
| Resource | Responsibility | Example |
|---|---|---|
| Graph | Executable agent workflow | Customer support graph |
| Assistant | Configured instance of a graph | English support assistant |
| Thread | Persistent execution context | Customer conversation |
| Run | Individual execution request | Answer a billing question |
| Checkpoint | Recorded execution state | State after a tool call |
| Store | Long-term application memory | Customer preferences |
A graph defines what an agent does.
An assistant identifies a graph and its configuration. Multiple assistants can use the same underlying graph with different runtime context values.
A thread preserves state across executions. A run represents one execution against that state.
For example, a customer might send three messages during one support conversation. The application can create one thread and execute three runs against it.
The following diagram illustrates the relationship.
A thread ID is not the same as a user ID. One customer may own several threads, and your application must enforce the relationship between authenticated users and their threads.
Execution infrastructure
When a client submits a request, Agent Server coordinates the execution lifecycle.
A worker executes the graph, updates persistent state, and reports progress. The HTTP client can wait for completion, consume a stream, or retrieve results later.
Agent Server also provides capabilities such as:
- Background run execution and cancellation.
- Checkpoint inspection and conversation history.
- Human-in-the-loop execution and resumption.
- Concurrent request handling.
- Scheduled runs and completion webhooks.
- Configurable authentication and authorization.
- Long-term memory storage.
These capabilities reduce the amount of infrastructure code required around an agent.
PostgreSQL and Redis
In the standard production architecture, PostgreSQL and Redis serve different purposes.
PostgreSQL stores durable application resources, checkpoints, and long-term memory data by default.
Redis supports communication between API processes and workers, including worker notifications, cancellation signals, and live streaming coordination.
Redis is not the primary database for customer conversations.
This separation allows the application to coordinate distributed execution while preserving important state independently of individual worker processes.
Durable checkpointing also helps recover interrupted execution. However, it does not guarantee exactly-once execution of external side effects.
For example, a payment tool or email tool should implement its own idempotency protection to prevent duplicate actions during recovery or retries.
The Agent Server runtime documentation describes these infrastructure responsibilities in greater detail.
Calling Agent Server Through REST
Before introducing the SDK, examine the underlying HTTP API.
Open:
http://127.0.0.1:2024/docsThe interactive API documentation exposes request schemas and available operations.
The following complete Python example uses httpx to create a thread and execute a graph through HTTP.
Save it as rest_client.py.
import httpx
BASE_URL = "http://127.0.0.1:2024"
with httpx.Client(
base_url=BASE_URL,
timeout=60.0
) as client:
response = client.post("/threads", json={})
response.raise_for_status()
thread_id = response.json()["thread_id"]
response = client.post(
f"/threads/{thread_id}/runs/wait",
json={
"assistant_id": "diagnostic",
"input": {
"messages": [
{
"role": "user",
"content": "Check billing"
}
]
}
}
)
response.raise_for_status()
result = response.json()
print("Thread:", thread_id)
print("Response:", result["messages"][-1]["content"])Run:
python rest_client.pyExpected output:
Thread: <generated-thread-uuid>
Response: Received: Check billingThe request contains JSON rather than Python message objects.
Agent Server deserializes the input into the graph’s expected state representation, executes the graph, and serializes its output for the client.
This is why a frontend written in JavaScript, Java, or another language can interact with a Python-based LangGraph application.
Calling Agent Server with the SDK
The LangGraph SDK wraps the HTTP API in convenient Python and JavaScript interfaces.
Install the Python SDK if it is not already available:
pip install -U langgraph-sdkThe asynchronous client is created using get_client().
A synchronous alternative is available through get_sync_client().
Executing multiple runs on one thread
The following complete client.py demonstrates persistent conversation state and supports both local and remote server URLs.
import asyncio
import os
from langgraph_sdk import get_client
client = get_client(
url=os.getenv(
"AGENT_SERVER_URL",
"http://127.0.0.1:2024"
),
api_key=os.getenv("AGENT_SERVER_API_KEY"),
)
async def main():
thread = await client.threads.create()
thread_id = thread["thread_id"]
for question in [
"Check billing",
"Check shipping"
]:
result = await client.runs.wait(
thread_id,
"diagnostic",
input={
"messages": [
{
"role": "user",
"content": question
}
]
},
)
print(result["messages"][-1]["content"])
snapshot = await client.threads.get_state(thread_id)
messages = snapshot["values"]["messages"]
print("Total messages:", len(messages))
print("Thread ID:", thread_id)
if __name__ == "__main__":
asyncio.run(main())Expected output:
Received: Check billing
Received: Check shipping
Total messages: 4
Thread ID: <generated-thread-uuid>The state contains four messages because MessagesState uses the add_messages reducer.
Each run contributes one human message and one AI message. The existing thread state is loaded before the next execution.
You do not need to transmit the entire conversation history with every request.
If you create a new thread for every message, this continuity disappears.
Choosing an execution method
| SDK method | Behavior | Best suited for |
|---|---|---|
runs.wait() |
Waits for the result | Short request-response operations |
runs.stream() |
Delivers incremental events | Interactive chat interfaces |
runs.create() |
Submits a background run | Long-running workflows |
runs.join() |
Waits for an existing run | Background job coordination |
runs.get() |
Retrieves run information | Status checking and debugging |
threads.get_state() |
Retrieves thread state | Conversation restoration |
Here, waiting for a result does not mean the graph executes inside your client process. The remote worker still performs the computation.
Streaming graph execution
The following example runs the support agent and streams node updates and model message chunks.
import asyncio
from langgraph_sdk import get_client
client = get_client(url="http://127.0.0.1:2024")
async def main():
thread = await client.threads.create()
async for event in client.runs.stream(
thread["thread_id"],
"support",
input={
"messages": [
{
"role": "user",
"content": "What is your returns policy?"
}
]
},
stream_mode=["updates", "messages-tuple"],
config={"recursion_limit": 25},
):
if event.event == "messages":
message, metadata = event.data
content = message.get("content")
if isinstance(content, str) and content:
print(content, end="", flush=True)
elif event.event == "updates":
print("\nNode update:", list(event.data))
print()
if __name__ == "__main__":
asyncio.run(main())The output may contain model and tool node updates, followed by streamed text explaining the return policy.
The exact wording and chunk boundaries vary between executions.
Remote SDK streaming differs from local graph streaming:
- Local
graph.stream(..., version="v2")exposes dictionary-based stream chunks. - Remote
client.runs.stream()exposes SDK events throughevent.eventandevent.data.
The remote messages-tuple mode delivers message chunks together with execution metadata. Structured content blocks require additional rendering logic in a production frontend.
See the Agent Server streaming API.
Background execution
A long-running research or document-processing agent should not necessarily require an HTTP connection to remain open throughout execution.
The following example submits a run and subsequently retrieves its status.
import asyncio
from langgraph_sdk import get_client
client = get_client(url="http://127.0.0.1:2024")
async def main():
thread = await client.threads.create()
thread_id = thread["thread_id"]
run = await client.runs.create(
thread_id,
"diagnostic",
input={
"messages": [
{
"role": "user",
"content": "Process support ticket"
}
]
},
)
run_id = run["run_id"]
print("Submitted:", run_id)
await client.runs.join(thread_id, run_id)
completed = await client.runs.get(thread_id, run_id)
print("Status:", completed["status"])
if completed["status"] == "success":
state = await client.threads.get_state(thread_id)
print(state["values"]["messages"][-1]["content"])
if __name__ == "__main__":
asyncio.run(main())Expected output:
Submitted: <generated-run-uuid>
Status: success
Received: Process support ticketA real application could persist the run ID, return an acknowledgment immediately, and retrieve the result later instead of joining immediately.
For one-off requests that do not require persistent conversation history, pass None instead of a thread ID to runs.wait() or runs.stream().
Deploying to LangSmith
Once your application works locally, deploy it to LangSmith Cloud.
LangSmith provides managed Agent Server hosting, infrastructure provisioning, deployment revisions, and integrated observability.
Pre-deployment validation
Before deploying, verify that:
- Every registered graph loads successfully.
- Dependencies install in a clean environment.
- Required secrets are available.
- Stateful and stateless requests work.
- Tool failures are handled appropriately.
- Recursion limits and execution budgets are configured.
- Authentication and data access requirements are understood.
Run a production-like validation using Docker:
langgraph up --recreateYou can also build a deployable image:
langgraph build -t support-agent:v1Building an image does not automatically deploy it or provision cloud infrastructure.
Deploying through the CLI
The current CLI includes the langgraph deploy command, documented as beta.
An eligible LangSmith account, deployment permissions, and a valid LangSmith API key are required. LangSmith Cloud currently documents deployment access for Plus plans and above.
From the project root:
langgraph deploy --name support-agentTo request a dedicated deployment:
langgraph deploy \
--name support-agent \
--agent-server-type dedicatedDepending on the environment, the CLI can build locally with Docker or use a remote cloud build.
Serverless deployments suit workloads that can tolerate startup delays. Dedicated deployments suit workloads requiring always-available capacity.
Deploying through the LangSmith interface
Alternatively, use a GitHub-based deployment:
- Push the project to a GitHub repository without committing
.env. - Open LangSmith and navigate to Agent Servers.
- Create an Agent Server and authorize repository access if required.
- Select the repository and Git branch or tag.
- Specify the path to
langgraph.json. - Choose the deployment type.
- Configure environment variables and provider secrets.
- Submit the deployment and inspect its build and runtime status.
- Copy the deployment’s API URL after provisioning succeeds.
Use the LangSmith cloud deployment guide for the current interface and CLI options.
Calling the deployed agent
Your existing SDK client can connect to the cloud deployment without changing its graph execution logic.
Set the deployment URL and an appropriately authorized API key in the client process environment:
export AGENT_SERVER_URL="https://your-deployment-url"
export AGENT_SERVER_API_KEY="your-authorized-api-key"
python client.pyThe same persistence test should now execute against the remote deployment.
In production, your browser application should not contain a privileged LangSmith API key. Use a trusted backend or an appropriate user authentication mechanism.
Tip: Use separate development and production deployments. Test new graph implementations against staging threads before releasing changes that could affect existing checkpoints or active conversations.
When to Use Agent Server Versus Your Own API
Agent Server is particularly valuable when your application requires persistent conversations, streaming, long-running jobs, interrupts, and checkpoint recovery.
A custom FastAPI application may be preferable when the agent is only one small component of a larger backend and you already operate suitable execution infrastructure.
| Requirement | Agent Server | Custom API |
|---|---|---|
| Persistent execution | Integrated | Implement or integrate |
| Background execution | Integrated | Configure workers |
| Conversation endpoints | Provided | Design endpoints |
| Agent-specific streaming | Provided | Implement streaming |
| Domain-specific API contracts | Customizable | Full control |
| Infrastructure ownership | Managed or self-hosted | Your responsibility |
| Business authentication | Requires configuration | Full implementation control |
These approaches are not mutually exclusive.
A common architecture places a business API in front of Agent Server. The business API authenticates customers, validates permissions, handles billing, and submits authorized execution requests. Agent Server handles graph execution and persistence.
This keeps business rules separate from orchestration infrastructure.
Common Mistakes and Production Best Practices
Avoid these common deployment mistakes:
| Mistake | Correct approach |
|---|---|
| Adding an independent checkpointer to a deployed graph | Use server-managed persistence |
| Creating a new thread for every message | Reuse the conversation’s thread ID |
| Treating thread IDs as authorization credentials | Validate authenticated resource ownership |
| Using blocking network calls in async nodes | Prefer asynchronous clients and model methods |
| Assuming HTTP timeouts cancel remote runs | Inspect and manage the remote run explicitly |
| Retrying submissions without checking existing runs | Use appropriate deduplication and idempotency |
| Publishing provider credentials in frontend code | Keep secrets in trusted server environments |
| Running the development server publicly | Use a properly secured deployment |
| Allowing unlimited agent iterations | Configure recursion and resource budgets |
An important operational practice is to distinguish graph failures from infrastructure failures.
If the diagnostic graph succeeds but the support graph fails, inspect provider authentication, model availability, tool behavior, and graph logic.
If both fail, investigate server startup, networking, dependencies, authentication, and runtime infrastructure.
Use LangSmith traces to inspect individual executions and deployment logs to investigate server-level failures. Avoid recording sensitive customer information unnecessarily.
Connecting to the Next Lesson
Agent Server establishes a standardized execution layer that external applications can consume.
In the next lesson, Serving graphs with FastAPI, Streamlit or React, you will build application-facing interfaces around this layer.
FastAPI will demonstrate business-specific endpoints and backend integration. Streamlit will provide a Python-based interactive interface, while React will demonstrate a frontend communicating with agent execution services.
These components form the foundation of the chapter’s hands-on project: deploying a complete LangGraph AI agent as an API with a functional user interface.
Build an Agent Server API Client
Build a Python client that connects to the locally running Agent Server and creates two independent conversation threads using the diagnostic graph developed in this lesson. Execute two runs on the first thread and one run on the second thread, then retrieve both thread states. Verify that conversation history persists within a thread and remains isolated between threads.
import asyncio
import os
from langgraph_sdk import get_client
SERVER_URL = os.getenv(
"AGENT_SERVER_URL",
"http://127.0.0.1:2024"
)
ASSISTANT_ID = "diagnostic"
client = get_client(url=SERVER_URL)
async def main():
# TODO 1: Create two independent threads.
# TODO 2: Execute two runs on the first thread.
# TODO 3: Execute one run on the second thread.
# TODO 4: Retrieve both thread states.
# TODO 5: Verify message counts and thread isolation.
pass
if __name__ == "__main__":
asyncio.run(main())import asyncio
import os
from langgraph_sdk import get_client
SERVER_URL = os.getenv(
"AGENT_SERVER_URL",
"http://127.0.0.1:2024"
)
ASSISTANT_ID = "diagnostic"
client = get_client(url=SERVER_URL)
async def send_message(thread_id: str, text: str):
return await client.runs.wait(
thread_id,
ASSISTANT_ID,
input={
"messages": [
{"role": "user", "content": text}
]
},
)
async def main():
first = await client.threads.create()
second = await client.threads.create()
first_id = first["thread_id"]
second_id = second["thread_id"]
await send_message(first_id, "Check billing")
await send_message(first_id, "Check shipping")
await send_message(second_id, "Check returns")
first_state = await client.threads.get_state(first_id)
second_state = await client.threads.get_state(second_id)
first_messages = first_state["values"]["messages"]
second_messages = second_state["values"]["messages"]
assert first_id != second_id
assert len(first_messages) == 4
assert len(second_messages) == 2
assert first_messages[0]["content"] == "Check billing"
assert first_messages[2]["content"] == "Check shipping"
assert second_messages[0]["content"] == "Check returns"
assert all(
message["content"] != "Check returns"
for message in first_messages
)
assert all(
message["content"] != "Check billing"
for message in second_messages
)
print("Thread A:", first_id)
print("Thread A messages:", len(first_messages))
print("Thread B:", second_id)
print("Thread B messages:", len(second_messages))
print("All persistence and isolation checks passed.")
if __name__ == "__main__":
asyncio.run(main())Summary
- The LangGraph CLI provides commands for developing, testing, packaging, and deploying LangGraph applications.
- The langgraph.json configuration file registers graph implementations, application dependencies, and runtime environment settings.
- The local development server provides HTTP endpoints, hot reloading, local persistence, and integration with LangSmith Studio.
- Agent Server manages assistants, threads, runs, checkpointing, background execution, and streaming through a standardized API.
- The LangGraph SDK enables remote graph execution without importing graph implementation code into the client application.
- Production Agent Server deployments use PostgreSQL for durable resource storage and Redis for worker coordination.
- LangSmith Cloud simplifies agent deployment and infrastructure management while custom APIs provide greater control over application-specific requirements.