Compare commits

...
18 Commits
Author SHA1 Message Date
Isaac FranciscoandGitHub ada5d2ecb1 feat(cli): bump version (#6086)
version bump for: https://github.com/langchain-ai/langgraph/pull/6085
2025-09-05 15:52:30 -07:00
Isaac FranciscoandGitHub eaeafe54ab feat(cli): support prereleases (#6085)
We previously errored when a user had prerelease dependencies, this PR
passes the `--prereleases=allow` flag to our `uv pip install` call.

This PR also adds a test to verify that said deployments will build and
run as expected.
2025-09-05 15:45:48 -07:00
William FHandGitHub f761116de7 chore(sdk-py): Clean up docstring for get_client (#6084)
Main thing here is to call out the ASGITransport behavior
2025-09-05 13:43:31 -07:00
Nuno CamposandGitHub 36cf353d19 fix: Unwrap Required/NotRequired special forms before resolving channel/reducer annotations (#6080) 2025-09-05 10:27:10 +01:00
d503c0bf33 WIP: monorepo support in CLI (#6028)
This PR introduces the `--build-command` and `--install-command`
arguments to `langgraph build`.

`--install-command` is a custom install command. If passed, it will be
run from wherever the `langgraph build` call was made, i.e. NOT where
the langgraph.json file lives (except if these are the same place). This
will override the detected install command that we previously used.

`--build-command` is a custom build command. This will run from wherever
the langgraph.json file lives, and will be done after the install has
been run.

You don't need to provide both. Just providing one will make the install
(detected or supplied) run in the directory from where `langgraph build
was called` and then have the build command (if one exists) run in the
directory where langgraph.json exists.

I think we should probably allow configuring the directories from which
these commands get run, but I don't think this needs to be part of the
MVP.

---------

Co-authored-by: William FH <13333726+hinthornw@users.noreply.github.com>
2025-09-04 12:29:11 -07:00
William FHandGitHub 25ba4c3bda feat(sdk-py): Specify ttl on thread creation and update (#6075) 2025-09-03 18:48:57 -07:00
dfc1c59ebf chore(docs): Update OpenAPI spec from LangGraph API v0.4.11 (#6074)
This PR updates the OpenAPI specification with changes detected from the
LangGraph API server.

**Changes detected as of LangGraph API version 0.4.11**

This update was automatically generated by the sync workflow in the
langgraph-api repository.

Co-authored-by: hinthornw <hinthornw@users.noreply.github.com>
2025-09-03 18:37:39 -07:00
William FHandGitHub 6f4c5fefee feat(sdk-py): Support ids filtering in threads search (#6067) 2025-09-02 17:49:11 -07:00
7cf230defa chore(docs): Update OpenAPI spec from LangGraph API v0.4.9 (#6066)
This PR updates the OpenAPI specification with changes detected from the
LangGraph API server.

**Changes detected as of LangGraph API version 0.4.9**

This update was automatically generated by the sync workflow in the
langgraph-api repository.

Co-authored-by: hinthornw <hinthornw@users.noreply.github.com>
2025-09-02 17:04:30 -07:00
5db65e0281 chore(docs): Update OpenAPI spec from LangGraph API v0.4.8 (#6065)
This PR updates the OpenAPI specification with changes detected from the
LangGraph API server.

**Changes detected as of LangGraph API version 0.4.8**

This update was automatically generated by the sync workflow in the
langgraph-api repository.

Co-authored-by: hinthornw <hinthornw@users.noreply.github.com>
2025-09-02 15:25:52 -07:00
b08c2e092f chore(docs): Update OpenAPI spec from LangGraph API v0.4.8 (#6048)
This PR updates the OpenAPI specification with changes detected from the
LangGraph API server.

**Changes detected as of LangGraph API version 0.4.8**

This update was automatically generated by the sync workflow in the
langgraph-api repository.

Co-authored-by: hinthornw <hinthornw@users.noreply.github.com>
2025-09-02 10:10:12 -07:00
Sydney RunkleandGitHub 120ae38c12 chore(docs): fix runtime context link (#6043) 2025-08-29 13:45:39 -04:00
Isaac FranciscoandGitHub 22942d4eec release(sdk-py): 0.2.4 (#6038) 2025-08-28 23:34:33 +00:00
Isaac FranciscoandGitHub 1756ce1dd2 feat(sdk-py): add endpoint for thread streaming (#6009)
SDK support for:
https://github.com/langchain-ai/langgraph-api/pull/1217/
2025-08-28 16:12:04 +00:00
Isaac FranciscoandGitHub 0b4638269b feat(sdk-py): add durability flag (#5963) 2025-08-27 19:21:25 +00:00
Isaac FranciscoandGitHub 1ebdb1ba31 chore: Update schema for new config allowed in LGP (#5875) 2025-08-27 11:20:06 -07:00
hari-dhanushkodiandGitHub f3423c052e fix(docs): add revision queuing docs (#5997) 2025-08-27 07:47:45 -07:00
b63572ee16 chore: Update OpenAPI spec from LangGraph API v0.4.0 (#6011)
This PR updates the OpenAPI specification with changes detected from the
LangGraph API server.

**Changes detected as of LangGraph API version 0.4.0**

This update was automatically generated by the sync workflow in the
langgraph-api repository.

Co-authored-by: hinthornw <hinthornw@users.noreply.github.com>
2025-08-26 20:51:30 -07:00
47 changed files with 3640 additions and 144 deletions
+24
View File
@@ -87,3 +87,27 @@ jobs:
working-directory: libs/cli/js-examples
run: |
langgraph build -t langgraph-test-e
- name: Build JS monorepo service
if: steps.changed-files.outputs.all
working-directory: libs/cli/js-monorepo-example
run: |
langgraph build -t langgraph-test-f -c apps/agent/langgraph.json --build-command "yarn run turbo build" --install-command "yarn install"
- name: Build Python monorepo service
if: steps.changed-files.outputs.all
working-directory: libs/cli/python-monorepo-example
run: |
langgraph build -t langgraph-test-g -c apps/agent/langgraph.json
cp apps/agent/.env.example apps/agent/.env
if [ -n "${{ secrets.LANGSMITH_API_KEY }}" ]; then echo "LANGSMITH_API_KEY=${{ secrets.LANGSMITH_API_KEY }}" >> apps/agent/.env; fi
timeout 60 python ../../../.github/scripts/run_langgraph_cli_test.py -t langgraph-test-g -c apps/agent/langgraph.json
- name: Build and test prerelease reqs service
if: steps.changed-files.outputs.all
working-directory: libs/cli/examples/graph_prerelease_reqs
run: |
langgraph build -t langgraph-test-h
cp ../.env.example .env
if [ -n "${{ secrets.LANGSMITH_API_KEY }}" ]; then echo "LANGSMITH_API_KEY=${{ secrets.LANGSMITH_API_KEY }}" >> .env; fi
timeout 60 python ../../../../.github/scripts/run_langgraph_cli_test.py -t langgraph-test-h
+2 -2
View File
@@ -99,8 +99,8 @@ Starting from the `LangGraph Platform` view...
1. In the top-right corner, select the gear icon (`Deployment Settings`).
1. Update the `Git Branch` to the desired branch.
1. Check/uncheck checkbox to `Automatically update deployment on push to branch`.
1. Branch creation/deletion and tag creation/deletion events will not trigger an update. Only pushes to an existing branch will trigger an update.
1. Pushes in quick succession to a branch will not trigger subsequent updates. In the future, this functionality may be changed/improved.
1. Branch creation/deletion and tag creation/deletion events will not trigger an update. Only pushes to an existing branch will trigger an update.
1. Pushes in quick succession to a branch will queue subsequent updates. Once a build completes, the most recent commit will begin building and the other queued builds will be skipped.
## Add or Remove GitHub Repositories
+331 -1
View File
@@ -29,6 +29,10 @@
"name": "Store",
"description": "Store is an API for managing persistent key-value store (long-term memory) that is available from any thread."
},
{
"name": "A2A",
"description": "Agent-to-Agent Protocol related endpoints for exposing assistants as A2A-compliant agents."
},
{
"name": "MCP",
"description": "Model Context Protocol related endpoints for exposing an agent as an MCP server."
@@ -1520,6 +1524,96 @@
}
}
},
"/threads/{thread_id}/stream": {
"get": {
"tags": [
"Threads"
],
"summary": "Join Thread Stream",
"description": "This endpoint streams output in real-time from a thread. The stream will include the output of each run executed sequentially on the thread and will remain open indefinitely. It is the responsibility of the calling client to close the connection.",
"operationId": "join_thread_stream_threads__thread_id__stream_get",
"parameters": [
{
"description": "The ID of the thread.",
"required": true,
"schema": {
"type": "string",
"format": "uuid",
"title": "Thread Id",
"description": "The ID of the thread."
},
"name": "thread_id",
"in": "path"
},
{
"required": false,
"schema": {
"type": "string",
"title": "Last Event ID",
"description": "The ID of the last event received. Used to resume streaming from a specific point. Pass '-' to resume from the beginning."
},
"name": "Last-Event-ID",
"in": "header"
},
{
"required": false,
"schema": {
"anyOf": [
{
"type": "string",
"enum": ["lifecycle", "run_modes", "state_update"]
},
{
"type": "array",
"items": {
"type": "string",
"enum": ["lifecycle", "run_modes", "state_update"]
}
}
],
"default": ["run_modes"],
"title": "Stream Modes",
"description": "Stream modes to control which events are returned. 'lifecycle' returns only run start/end events, 'run_modes' returns all run events (default behavior), 'state_update' returns only state update events."
},
"name": "stream_modes",
"in": "query"
}
],
"responses": {
"200": {
"description": "Success",
"content": {
"text/event-stream": {
"schema": {
"type": "string",
"description": "The server will send a stream of events in SSE format.\n\n**Example event**:\n\nid: 1\n\nevent: message\n\ndata: {}"
}
}
}
},
"404": {
"description": "Not Found",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
}
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
}
}
}
}
},
"/threads/{thread_id}/runs": {
"get": {
"tags": [
@@ -3092,6 +3186,195 @@
}
}
},
"/a2a/{assistant_id}": {
"post": {
"operationId": "post_a2a",
"summary": "A2A Post",
"description": "Communicate with an assistant using the Agent-to-Agent Protocol.\nSends a JSON-RPC 2.0 message to the assistant.\n\n- **Request**: Provide an object with `jsonrpc`, `id`, `method`, and optional `params`.\n- **Response**: Returns a JSON-RPC response with task information or error.\n\n**Supported Methods:**\n- `message/send`: Send a message to the assistant\n- `tasks/get`: Get the status and result of a task\n\n**Notes:**\n- Supports threaded conversations via thread context\n- Messages can contain text and data parts\n- Tasks run asynchronously and return completion status\n",
"parameters": [
{
"name": "assistant_id",
"in": "path",
"required": true,
"schema": {
"type": "string",
"format": "uuid"
},
"description": "The ID of the assistant to communicate with"
},
{
"name": "Accept",
"in": "header",
"required": true,
"schema": {
"type": "string",
"enum": ["application/json"]
},
"description": "Must be application/json"
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"jsonrpc": {
"type": "string",
"enum": ["2.0"],
"description": "JSON-RPC version"
},
"id": {
"type": "string",
"description": "Request identifier"
},
"method": {
"type": "string",
"enum": ["message/send", "tasks/get"],
"description": "The method to invoke"
},
"params": {
"type": "object",
"description": "Method parameters",
"oneOf": [
{
"title": "Message Send Parameters",
"properties": {
"message": {
"type": "object",
"properties": {
"role": {
"type": "string",
"enum": ["user", "assistant"],
"description": "Message role"
},
"parts": {
"type": "array",
"items": {
"oneOf": [
{
"title": "Text Part",
"type": "object",
"properties": {
"kind": {
"type": "string",
"enum": ["text"]
},
"text": {
"type": "string"
}
},
"required": ["kind", "text"]
},
{
"title": "Data Part",
"type": "object",
"properties": {
"kind": {
"type": "string",
"enum": ["data"]
},
"data": {
"type": "object"
}
},
"required": ["kind", "data"]
}
]
},
"description": "Message parts"
},
"messageId": {
"type": "string",
"description": "Unique message identifier"
}
},
"required": ["role", "parts", "messageId"]
},
"thread": {
"type": "object",
"properties": {
"threadId": {
"type": "string",
"description": "Thread identifier for conversation context"
}
},
"description": "Optional thread context"
}
},
"required": ["message"]
},
{
"title": "Task Get Parameters",
"properties": {
"taskId": {
"type": "string",
"description": "Task identifier to retrieve"
}
},
"required": ["taskId"]
}
]
}
},
"required": ["jsonrpc", "id", "method"]
}
}
}
},
"responses": {
"200": {
"description": "JSON-RPC response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"jsonrpc": {
"type": "string",
"enum": ["2.0"]
},
"id": {
"type": "string"
},
"result": {
"type": "object",
"description": "Success result containing task information or task details"
},
"error": {
"type": "object",
"properties": {
"code": {
"type": "integer"
},
"message": {
"type": "string"
}
},
"description": "Error information if request failed"
}
},
"required": ["jsonrpc", "id"]
}
}
}
},
"400": {
"description": "Bad request - invalid JSON-RPC or missing Accept header"
},
"404": {
"description": "Assistant not found"
},
"500": {
"description": "Internal server error"
}
},
"tags": [
"A2A"
]
}
},
"/mcp/": {
"post": {
"operationId": "post_mcp",
@@ -4346,6 +4629,17 @@
"title": "Checkpoint During",
"description": "Whether to checkpoint during the run.",
"default": false
},
"durability": {
"type": "string",
"enum": [
"sync",
"async",
"exit"
],
"title": "Durability",
"description": "Durability level for the run. Must be one of 'sync', 'async', or 'exit'.",
"default": "async"
}
},
"type": "object",
@@ -4582,6 +4876,17 @@
"title": "Checkpoint During",
"description": "Whether to checkpoint during the run.",
"default": false
},
"durability": {
"type": "string",
"enum": [
"sync",
"async",
"exit"
],
"title": "Durability",
"description": "Durability level for the run. Must be one of 'sync', 'async', or 'exit'.",
"default": "async"
}
},
"type": "object",
@@ -4710,6 +5015,12 @@
},
"ThreadSearchRequest": {
"properties": {
"ids": {
"type": "array",
"items": {"type": "string", "format": "uuid"},
"title": "Ids",
"description": "List of thread IDs to include. Others are excluded."
},
"metadata": {
"type": "object",
"title": "Metadata",
@@ -4950,11 +5261,30 @@
"type": "object",
"title": "Metadata",
"description": "Metadata to merge with existing thread metadata."
},
"ttl": {
"type": "object",
"title": "TTL",
"description": "The time-to-live for the thread.",
"properties": {
"strategy": {
"type": "string",
"enum": [
"delete"
],
"description": "The TTL strategy. 'delete' removes the entire thread.",
"default": "delete"
},
"ttl": {
"type": "number",
"description": "The time-to-live in minutes from now until thread should be swept."
}
}
}
},
"type": "object",
"title": "ThreadPatch",
"description": "Payload for creating a thread."
"description": "Payload for updating a thread."
},
"ThreadStateCheckpointRequest": {
"properties": {
+3 -3
View File
@@ -483,19 +483,19 @@ The LangGraph CLI requires a JSON configuration file that follows this [schema](
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
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; \
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"}'
ENV LANGSERVE_GRAPHS='{"agent": "/deps/outer-graphs/src/agent.py:graph", "storm": "/deps/outer-graphs/src/storm.py:graph"}'
```
???+ note "Updating your langgraph.json file"
+1 -1
View File
@@ -1040,7 +1040,7 @@ def node_a(state: State, runtime: Runtime[ContextSchema]):
...
```
See [this guide](../how-tos/graph-api.ipynb#add-runtime-configuration) for a full breakdown on configuration.
See [this guide](../how-tos/graph-api.md#add-runtime-configuration) for a full breakdown on configuration.
:::
:::js
@@ -0,0 +1,95 @@
from collections.abc import Sequence
from typing import Annotated, Literal, TypedDict
from langchain.chat_models import init_chat_model
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_core.messages import BaseMessage
from langchain_openai import ChatOpenAI
from langgraph.graph import END, StateGraph, add_messages
from langgraph.prebuilt import ToolNode
tools = [TavilySearchResults(max_results=1)]
model_anth = init_chat_model("claude-3-7-sonnet-20250219", model_provider="anthropic")
model_oai = ChatOpenAI(temperature=0)
model_anth = model_anth.bind_tools(tools)
model_oai = model_oai.bind_tools(tools)
class AgentState(TypedDict):
messages: Annotated[Sequence[BaseMessage], add_messages]
# Define the function that determines whether to continue or not
def should_continue(state):
messages = state["messages"]
last_message = messages[-1]
# If there are no tool calls, then we finish
if not last_message.tool_calls:
return "end"
# Otherwise if there is, we continue
else:
return "continue"
# Define the function that calls the model
def call_model(state, config):
if config["configurable"].get("model", "anthropic") == "anthropic":
model = model_anth
else:
model = model_oai
messages = state["messages"]
response = model.invoke(messages)
# We return a list, because this will get added to the existing list
return {"messages": [response]}
# Define the function to execute tools
tool_node = ToolNode(tools)
class ContextSchema(TypedDict):
model: Literal["anthropic", "openai"]
# Define a new graph
workflow = StateGraph(AgentState, context_schema=ContextSchema)
# Define the two nodes we will cycle between
workflow.add_node("agent", call_model)
workflow.add_node("action", tool_node)
# Set the entrypoint as `agent`
# This means that this node is the first one called
workflow.set_entry_point("agent")
# We now add a conditional edge
workflow.add_conditional_edges(
# First, we define the start node. We use `agent`.
# This means these are the edges taken after the `agent` node is called.
"agent",
# Next, we pass in the function that will determine which node is called next.
should_continue,
# Finally we pass in a mapping.
# The keys are strings, and the values are other nodes.
# END is a special node marking that the graph should finish.
# What will happen is we will call `should_continue`, and then the output of that
# will be matched against the keys in this mapping.
# Based on which one it matches, that node will then be called.
{
# If `tools`, then we call the tool node.
"continue": "action",
# Otherwise we finish.
"end": END,
},
)
# We now add a normal edge from `tools` to `agent`.
# This means that after `tools` is called, `agent` node is called next.
workflow.add_edge("action", "agent")
# Finally, we compile it!
# This compiles it into a LangChain Runnable,
# meaning you can use it as you would any other runnable
graph = workflow.compile()
@@ -0,0 +1,11 @@
{
"python_version": "3.12",
"dependencies": [
"."
],
"graphs": {
"agent": "./agent.py:graph"
},
"env": "../.env"
}
@@ -0,0 +1,6 @@
requests
langchain_anthropic
langchain_openai
langchain_community
langchain
langgraph==1.0.0a2
@@ -0,0 +1,62 @@
module.exports = {
extends: [
"eslint:recommended",
"prettier",
"plugin:@typescript-eslint/recommended",
],
parserOptions: {
ecmaVersion: 12,
parser: "@typescript-eslint/parser",
project: "./tsconfig.json",
sourceType: "module",
},
plugins: ["import", "@typescript-eslint", "no-instanceof"],
ignorePatterns: [
".eslintrc.cjs",
"scripts",
"src/utils/lodash/*",
"node_modules",
"dist",
"dist-cjs",
"*.js",
"*.cjs",
"*.d.ts",
],
rules: {
"no-process-env": 2,
"no-instanceof/no-instanceof": 2,
"@typescript-eslint/explicit-module-boundary-types": 0,
"@typescript-eslint/no-empty-function": 0,
"@typescript-eslint/no-shadow": 0,
"@typescript-eslint/no-empty-interface": 0,
"@typescript-eslint/no-use-before-define": ["error", "nofunc"],
"@typescript-eslint/no-unused-vars": ["warn", { args: "none" }],
"@typescript-eslint/no-floating-promises": "error",
"@typescript-eslint/no-misused-promises": "error",
camelcase: 0,
"class-methods-use-this": 0,
"import/extensions": [2, "ignorePackages"],
"import/no-extraneous-dependencies": [
"error",
{ devDependencies: ["**/*.test.ts"] },
],
"import/no-unresolved": 0,
"import/prefer-default-export": 0,
"keyword-spacing": "error",
"max-classes-per-file": 0,
"max-len": 0,
"no-await-in-loop": 0,
"no-bitwise": 0,
"no-console": 0,
"no-restricted-syntax": 0,
"no-shadow": 0,
"no-continue": 0,
"no-underscore-dangle": 0,
"no-use-before-define": 0,
"no-useless-constructor": 0,
"no-return-await": 0,
"consistent-return": 0,
"no-else-return": 0,
"new-cap": ["error", { properties: false, capIsNew: false }],
},
};
@@ -0,0 +1,7 @@
{
"node_version": "20",
"graphs": {
"agent": "./src/graph.ts:graph"
},
"env": "../../.env"
}
@@ -0,0 +1,18 @@
{
"name": "@js-monorepo-example/agent",
"version": "0.0.1",
"type": "module",
"main": "src/graph.ts",
"scripts": {
"build": "tsc",
"clean": "rm -rf dist"
},
"dependencies": {
"@js-monorepo-example/shared": "*",
"@langchain/core": "^0.3.2",
"@langchain/langgraph": "^0.2.5"
},
"devDependencies": {
"typescript": "^5.3.3"
}
}
@@ -0,0 +1,47 @@
/**
* Simple LangGraph.js example for monorepo testing
*/
import { StateGraph } from "@langchain/langgraph";
import { RunnableConfig } from "@langchain/core/runnables";
import { StateAnnotation } from "./state.js";
import { getGreeting } from "@js-monorepo-example/shared";
/**
* Simple node that uses the shared library
*/
const callModel = async (
state: typeof StateAnnotation.State,
_config: RunnableConfig,
): Promise<typeof StateAnnotation.Update> => {
// Use functions from the shared library
const greeting = getGreeting();
return {
messages: [
{
role: "assistant",
content: `${greeting}`,
},
],
};
};
/**
* Simple routing function
*/
export const route = (
state: typeof StateAnnotation.State,
): "__end__" | "callModel" => {
if (state.messages.length > 0) {
return "__end__";
}
return "callModel";
};
// Create the graph
const builder = new StateGraph(StateAnnotation)
.addNode("callModel", callModel)
.addEdge("__start__", "callModel")
.addConditionalEdges("callModel", route);
export const graph = builder.compile();
@@ -0,0 +1,15 @@
import { BaseMessage, BaseMessageLike } from "@langchain/core/messages";
import { Annotation, messagesStateReducer } from "@langchain/langgraph";
/**
* Simple state annotation for the agent
*/
export const StateAnnotation = Annotation.Root({
/**
* Messages track the primary execution state of the agent.
*/
messages: Annotation<BaseMessage[], BaseMessageLike[]>({
reducer: messagesStateReducer,
default: () => [],
}),
});
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
@@ -0,0 +1,14 @@
{
"name": "@js-monorepo-example/shared",
"version": "0.0.1",
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc",
"clean": "rm -rf dist"
},
"devDependencies": {
"typescript": "^5.3.3"
}
}
@@ -0,0 +1,6 @@
/**
* Simple utility functions for monorepo testing
*/
export function getGreeting(): string {
return "Hello from shared library!";
}
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
+34
View File
@@ -0,0 +1,34 @@
{
"name": "js-monorepo-example",
"version": "0.0.1",
"packageManager": "yarn@1.22.22",
"description": "A simple monorepo example for LangGraph integration testing.",
"private": true,
"workspaces": [
"libs/*",
"apps/*"
],
"type": "module",
"scripts": {
"build": "turbo build",
"clean": "turbo clean",
"test": "turbo test",
"format": "prettier --write .",
"lint": "eslint 'apps/**/*.ts' 'libs/**/*.ts'"
},
"devDependencies": {
"turbo": "^2.5.0",
"typescript": "^5.3.3",
"@tsconfig/recommended": "^1.0.7",
"@eslint/eslintrc": "^3.1.0",
"@eslint/js": "^9.9.1",
"eslint": "^8.41.0",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-no-instanceof": "^1.0.1",
"eslint-plugin-prettier": "^4.2.1",
"@typescript-eslint/eslint-plugin": "^5.59.8",
"@typescript-eslint/parser": "^5.59.8",
"prettier": "^3.3.3"
}
}
@@ -0,0 +1,16 @@
{
"extends": "@tsconfig/recommended",
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"skipLibCheck": true,
"strict": true,
"declaration": true,
"outDir": "./dist"
},
"include": ["apps/**/*", "libs/**/*"],
"exclude": ["node_modules", "dist"]
}
+15
View File
@@ -0,0 +1,15 @@
{
"$schema": "https://turbo.build/schema.json",
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**"]
},
"clean": {
"dependsOn": ["^clean"]
},
"test": {
"dependsOn": ["^test"]
}
}
}
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1 +1 @@
__version__ = "0.4.0"
__version__ = "0.4.2"
+33 -3
View File
@@ -303,6 +303,8 @@ def _build(
pull: bool,
tag: str,
passthrough: Sequence[str] = (),
install_command: Optional[str] = None,
build_command: Optional[str] = None,
):
# pull latest images
if pull:
@@ -322,22 +324,38 @@ def _build(
"-t",
tag,
]
# determine build context: use current directory for JS projects, config parent for Python
is_js_project = config_json.get("node_version") and not config_json.get(
"python_version"
)
# build/install commands only apply to JS projects for now
# without install/build command, JS projects will follow the old behavior
if is_js_project and (build_command or install_command):
build_context = str(pathlib.Path.cwd())
else:
build_context = str(config.parent)
# apply config
stdin, additional_contexts = langgraph_cli.config.config_to_docker(
config, config_json, base_image, api_version
config,
config_json,
base_image,
api_version,
install_command,
build_command,
build_context,
)
# add additional_contexts
if additional_contexts:
for k, v in additional_contexts.items():
args.extend(["--build-context", f"{k}={v}"])
# run docker build
runner.run(
subp_exec(
"docker",
"build",
*args,
*passthrough,
str(config.parent),
build_context,
input=stdin,
verbose=True,
)
@@ -366,6 +384,14 @@ def _build(
"\n --base-image langchain/langgraph-server:0.2 # Pin to a minor version (Python)",
)
@OPT_API_VERSION
@click.option(
"--install-command",
help="Custom install command to run from the build context root. If not provided, auto-detects based on package manager files.",
)
@click.option(
"--build-command",
help="Custom build command to run from the langgraph.json directory. If not provided, uses default build process.",
)
@click.argument("docker_build_args", nargs=-1, type=click.UNPROCESSED)
@cli.command(
help="📦 Build LangGraph API server Docker image.",
@@ -381,6 +407,8 @@ def build(
api_version: Optional[str],
pull: bool,
tag: str,
install_command: Optional[str],
build_command: Optional[str],
):
with Runner() as runner, Progress(message="Pulling...") as set:
if shutil.which("docker") is None:
@@ -397,6 +425,8 @@ def build(
pull,
tag,
docker_build_args,
install_command,
build_command,
)
+75 -13
View File
@@ -357,6 +357,8 @@ class HttpConfig(TypedDict, total=False):
You can include or exclude headers as configurable values to condition your
agent's behavior or permissions on a request's headers."""
logging_headers: Optional[ConfigurableHeaderConfig]
"""Optional. Defines which headers are excluded from logging."""
class Config(TypedDict, total=False):
@@ -911,10 +913,10 @@ def _assemble_local_deps(config_path: pathlib.Path, config: Config) -> LocalDeps
"Rename the directory to use it as flat-layout package."
)
check_reserved(resolved.name, local_dep)
container_path = f"/deps/__outer_{resolved.name}/{resolved.name}"
container_path = f"/deps/outer-{resolved.name}/{resolved.name}"
else:
# src layout
container_path = f"/deps/__outer_{resolved.name}/src"
container_path = f"/deps/outer-{resolved.name}/src"
for file in files:
rfile = resolved / file
if (
@@ -1254,7 +1256,7 @@ def python_config_to_docker(
else:
pip_installer = "pip"
if pip_installer == "uv":
install_cmd = "uv pip install --system"
install_cmd = "uv pip install --system --prerelease=allow"
elif pip_installer == "pip":
install_cmd = "pip install"
else:
@@ -1284,7 +1286,7 @@ def python_config_to_docker(
if local_deps.pip_reqs:
pip_reqs_str = os.linesep.join(
(
f"COPY --from=__outer_{reqpath.name} requirements.txt {destpath}"
f"COPY --from=outer-{reqpath.name} requirements.txt {destpath}"
if reqpath.parent in local_deps.additional_contexts
else f"ADD {reqpath.relative_to(config_path.parent)} {destpath}"
)
@@ -1303,7 +1305,7 @@ def python_config_to_docker(
faux_pkgs_str = f"{os.linesep}{os.linesep}".join(
(
f"""# -- Adding non-package dependency {fullpath.name} --
COPY --from=__outer_{fullpath.name} . {destpath}"""
COPY --from=outer-{fullpath.name} . {destpath}"""
if fullpath in local_deps.additional_contexts
else f"""# -- Adding non-package dependency {fullpath.name} --
ADD {relpath} {destpath}"""
@@ -1318,7 +1320,7 @@ RUN set -ex && \\
'[build-system]' \\
'requires = ["setuptools>=61"]' \\
'build-backend = "setuptools.build_meta"'; do \\
echo "$line" >> /deps/__outer_{fullpath.name}/pyproject.toml; \\
echo "$line" >> /deps/outer-{fullpath.name}/pyproject.toml; \\
done
# -- End of non-package dependency {fullpath.name} --"""
for fullpath, (relpath, destpath) in local_deps.faux_pkgs.items()
@@ -1421,7 +1423,7 @@ ADD {relpath} /deps/{name}
if p in local_deps.real_pkgs:
name = local_deps.real_pkgs[p][1]
elif p in local_deps.faux_pkgs:
name = f"__outer_{p.name}"
name = f"outer-{p.name}"
else:
raise RuntimeError(f"Unknown additional context: {p}")
additional_contexts[name] = str(p)
@@ -1434,9 +1436,28 @@ def node_config_to_docker(
config: Config,
base_image: str,
api_version: Optional[str] = None,
install_command: Optional[str] = None,
build_command: Optional[str] = None,
build_context: Optional[str] = None,
) -> tuple[str, dict[str, str]]:
faux_path = f"/deps/{config_path.parent.name}"
install_cmd = _get_node_pm_install_cmd(config_path, config)
# Calculate paths for monorepo support
if build_context:
relative_workdir = _calculate_relative_workdir(config_path, build_context)
container_name = pathlib.Path(build_context).name
if relative_workdir:
faux_path = f"/deps/{container_name}/{relative_workdir}"
else:
faux_path = f"/deps/{container_name}"
else:
# Backward compatibility: use the original behavior
faux_path = f"/deps/{config_path.parent.name}"
# Use custom install command or auto-detect
if install_command:
install_cmd = install_command
else:
install_cmd = _get_node_pm_install_cmd(config_path, config)
image_str = docker_tag(config, base_image, api_version)
env_vars: list[str] = []
@@ -1463,20 +1484,35 @@ def node_config_to_docker(
env_vars.append(f"ENV LANGSERVE_GRAPHS='{json.dumps(config['graphs'])}'")
# For monorepo support, we need to handle install and build commands differently
if build_context:
# Monorepo case: install from root, build from config directory
container_root = f"/deps/{pathlib.Path(build_context).name}"
install_step = f"RUN cd {container_root} && {install_cmd}"
if build_command:
build_step = f"RUN cd {faux_path} && {build_command}"
else:
build_step = 'RUN (test ! -f /api/langgraph_api/js/build.mts && echo "Prebuild script not found, skipping") || tsx /api/langgraph_api/js/build.mts'
else:
# Original behavior: everything happens in the same directory
install_step = f"RUN cd {faux_path} && {install_cmd}"
build_step = 'RUN (test ! -f /api/langgraph_api/js/build.mts && echo "Prebuild script not found, skipping") || tsx /api/langgraph_api/js/build.mts'
docker_file_contents = [
f"FROM {image_str}",
"",
os.linesep.join(config["dockerfile_lines"]),
"",
f"ADD . {faux_path}",
f"ADD . {faux_path if not build_context else container_root}",
"",
f"RUN cd {faux_path} && {install_cmd}",
install_step,
"",
os.linesep.join(env_vars),
"",
f"WORKDIR {faux_path}",
"",
'RUN (test ! -f /api/langgraph_api/js/build.mts && echo "Prebuild script not found, skipping") || tsx /api/langgraph_api/js/build.mts',
build_step,
]
return os.linesep.join(docker_file_contents), {}
@@ -1524,16 +1560,42 @@ def docker_tag(
return f"{base_image}:{full_tag}"
def _calculate_relative_workdir(config_path: pathlib.Path, build_context: str) -> str:
"""Calculate the relative path from build context to langgraph.json directory."""
config_dir = config_path.parent.resolve()
build_context_path = pathlib.Path(build_context).resolve()
try:
relative_path = config_dir.relative_to(build_context_path)
return str(relative_path) if str(relative_path) != "." else ""
except ValueError as _:
raise ValueError(
f"Configuration file {config_path} is not under the build context {build_context}. "
f"Please run the command from a directory that contains your langgraph.json file, "
) from None
def config_to_docker(
config_path: pathlib.Path,
config: Config,
base_image: Optional[str] = None,
api_version: Optional[str] = None,
install_command: Optional[str] = None,
build_command: Optional[str] = None,
build_context: Optional[str] = None,
) -> tuple[str, dict[str, str]]:
base_image = base_image or default_base_image(config)
if config.get("node_version") and not config.get("python_version"):
return node_config_to_docker(config_path, config, base_image, api_version)
return node_config_to_docker(
config_path,
config,
base_image,
api_version,
install_command,
build_command,
build_context,
)
return python_config_to_docker(config_path, config, base_image, api_version)
@@ -0,0 +1,7 @@
{
"dependencies": [".", "../../libs/shared", "../../libs/common"],
"graphs": {
"agent": "./src/agent/graph.py:graph"
},
"env": ".env"
}
@@ -0,0 +1,19 @@
[project]
name = "agent"
version = "0.0.1"
description = "Agent for the Python monorepo"
authors = [
{ name = "Developer", email = "dev@example.com" },
]
license = { text = "MIT" }
requires-python = ">=3.11,<4.0"
[build-system]
requires = ["setuptools>=73.0.0", "wheel"]
build-backend = "setuptools.build_meta"
[tool.setuptools]
packages = ["agent"]
[tool.setuptools.package-dir]
"agent" = "src/agent"
@@ -0,0 +1 @@
"""Agent package."""
@@ -0,0 +1,40 @@
"""Simple LangGraph agent for monorepo testing."""
from common import get_common_prefix
from langchain_core.messages import AIMessage
from langgraph.graph import END, START, StateGraph
from shared import get_dummy_message
from agent.state import State
def call_model(state: State) -> dict:
"""Simple node that uses the shared libraries."""
# Use functions from both shared packages
dummy_message = get_dummy_message()
prefix = get_common_prefix()
message = AIMessage(content=f"{prefix} Agent says: {dummy_message}")
return {"messages": [message]}
def should_continue(state: State):
"""Conditional edge - end after first message."""
messages = state["messages"]
if len(messages) > 0:
return END
return "call_model"
# Build the graph
workflow = StateGraph(State)
# Add the node
workflow.add_node("call_model", call_model)
# Add edges
workflow.add_edge(START, "call_model")
workflow.add_conditional_edges("call_model", should_continue)
graph = workflow.compile()
@@ -0,0 +1,13 @@
"""State definition for the agent."""
from collections.abc import Sequence
from typing import Annotated, TypedDict
from langchain_core.messages import BaseMessage
from langgraph.graph.message import add_messages
class State(TypedDict):
"""The state of the agent."""
messages: Annotated[Sequence[BaseMessage], add_messages]
@@ -0,0 +1,5 @@
"""Common helper functions package."""
from .helpers import get_common_prefix
__all__ = ["get_common_prefix"]
@@ -0,0 +1,6 @@
"""Common helper functions."""
def get_common_prefix() -> str:
"""Get a common prefix for messages."""
return "[COMMON]"
@@ -0,0 +1,20 @@
[project]
name = "shared"
version = "0.0.1"
description = "Shared utilities for the Python monorepo"
authors = [
{ name = "Developer", email = "dev@example.com" },
]
license = { text = "MIT" }
requires-python = ">=3.11,<4.0"
dependencies = []
[build-system]
requires = ["setuptools>=73.0.0", "wheel"]
build-backend = "setuptools.build_meta"
[tool.setuptools]
packages = ["shared"]
[tool.setuptools.package-dir]
"shared" = "src/shared"
@@ -0,0 +1,5 @@
"""Shared utilities package."""
from .utils import get_dummy_message
__all__ = ["get_dummy_message"]
@@ -0,0 +1,6 @@
"""Shared utility functions."""
def get_dummy_message() -> str:
"""Get a dummy message for testing."""
return "Hello from shared library!"
@@ -0,0 +1,46 @@
[project]
name = "python-monorepo-example"
version = "0.0.1"
description = "A Python monorepo example with LangGraph agents and shared packages"
authors = [
{ name = "Developer", email = "dev@example.com" },
]
license = { text = "MIT" }
requires-python = ">=3.11,<4.0"
dependencies = [
"langgraph>=0.6.0,<0.7.0",
"langchain-core>=0.2.14",
]
[tool.uv.workspace]
members = ["apps/*", "libs/shared"]
[tool.uv.sources]
shared = { workspace = true }
[project.optional-dependencies]
dev = ["mypy>=1.11.1", "ruff>=0.6.1"]
[build-system]
requires = ["setuptools>=73.0.0", "wheel"]
build-backend = "setuptools.build_meta"
[tool.ruff]
lint.select = [
"E", # pycodestyle
"F", # pyflakes
"I", # isort
"D", # pydocstyle
"UP",
]
lint.ignore = [
"D100", # Missing docstring in public module
"D101", # Missing docstring in public class
"D102", # Missing docstring in public method
"D103", # Missing docstring in public function
"D104", # Missing docstring in public package
"D105", # Missing docstring in magic method
]
[tool.ruff.lint.pydocstyle]
convention = "google"
+11
View File
@@ -576,6 +576,17 @@
"disable_threads": {
"type": "boolean",
"description": "Optional. If True, /threads routes are removed.\n\nDefault is False.\n"
},
"logging_headers": {
"anyOf": [
{
"$ref": "#/$defs/ConfigurableHeaderConfig"
},
{
"type": "null"
}
],
"description": "Optional. Defines which headers are excluded from logging."
}
},
"required": []
+11
View File
@@ -576,6 +576,17 @@
"disable_threads": {
"type": "boolean",
"description": "Optional. If True, /threads routes are removed.\n\nDefault is False.\n"
},
"logging_headers": {
"anyOf": [
{
"$ref": "#/$defs/ConfigurableHeaderConfig"
},
{
"type": "null"
}
],
"description": "Optional. Defines which headers are excluded from logging."
}
},
"required": []
+3 -3
View File
@@ -15,7 +15,7 @@ from langgraph_cli.docker import DEFAULT_POSTGRES_URI, DockerCapabilities, Versi
from langgraph_cli.util import clean_empty_lines
FORMATTED_CLEANUP_LINES = _get_pip_cleanup_lines(
install_cmd="uv pip install --system",
install_cmd="uv pip install --system --prerelease=allow",
to_uninstall=("pip", "setuptools", "wheel"),
pip_installer="uv",
)
@@ -149,7 +149,7 @@ services:
COPY --from=cli_1 . /deps/cli_1
# -- End of local package ../../.. --
# -- Installing all local dependencies --
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --no-cache-dir -c /api/constraints.txt -e /deps/*
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --prerelease=allow --no-cache-dir -c /api/constraints.txt -e /deps/*
# -- End of local dependencies install --
ENV LANGSERVE_GRAPHS='{{"agent": "agent.py:graph"}}'
{textwrap.indent(textwrap.dedent(FORMATTED_CLEANUP_LINES), " ")}
@@ -570,7 +570,7 @@ def test_build_generate_proper_build_context():
catch_exceptions=True,
)
build_context_pattern = re.compile(r"--build-context\s+(\w+)=([^\s]+)")
build_context_pattern = re.compile(r"--build-context\s+([\w-]+)=([^\s]+)")
build_contexts = re.findall(build_context_pattern, result.output)
assert len(build_contexts) == 2, (
+76 -76
View File
@@ -20,7 +20,7 @@ from langgraph_cli.config import (
from langgraph_cli.util import clean_empty_lines
FORMATTED_CLEANUP_LINES = _get_pip_cleanup_lines(
install_cmd="uv pip install --system",
install_cmd="uv pip install --system --prerelease=allow",
to_uninstall=("pip", "setuptools", "wheel"),
pip_installer="uv",
)
@@ -421,14 +421,14 @@ def test_config_to_docker_simple():
expected_docker_stdin = f"""\
FROM langchain/langgraph-api:3.11
# -- Installing local requirements --
COPY --from=__outer_requirements.txt requirements.txt /deps/__outer_graphs_reqs_a/graphs_reqs_a/requirements.txt
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --no-cache-dir -c /api/constraints.txt -r /deps/__outer_graphs_reqs_a/graphs_reqs_a/requirements.txt
COPY --from=outer-requirements.txt requirements.txt /deps/outer-graphs_reqs_a/graphs_reqs_a/requirements.txt
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --prerelease=allow --no-cache-dir -c /api/constraints.txt -r /deps/outer-graphs_reqs_a/graphs_reqs_a/requirements.txt
# -- End of local requirements install --
# -- Adding local package ../../examples --
COPY --from=examples . /deps/examples
# -- End of local package ../../examples --
# -- Adding non-package dependency unit_tests --
ADD . /deps/__outer_unit_tests/unit_tests
ADD . /deps/outer-unit_tests/unit_tests
RUN set -ex && \\
for line in '[project]' \\
'name = "unit_tests"' \\
@@ -438,11 +438,11 @@ RUN set -ex && \\
'[build-system]' \\
'requires = ["setuptools>=61"]' \\
'build-backend = "setuptools.build_meta"'; do \\
echo "$line" >> /deps/__outer_unit_tests/pyproject.toml; \\
echo "$line" >> /deps/outer-unit_tests/pyproject.toml; \\
done
# -- End of non-package dependency unit_tests --
# -- Adding non-package dependency graphs_reqs_a --
COPY --from=__outer_graphs_reqs_a . /deps/__outer_graphs_reqs_a/graphs_reqs_a
COPY --from=outer-graphs_reqs_a . /deps/outer-graphs_reqs_a/graphs_reqs_a
RUN set -ex && \\
for line in '[project]' \\
'name = "graphs_reqs_a"' \\
@@ -452,21 +452,21 @@ RUN set -ex && \\
'[build-system]' \\
'requires = ["setuptools>=61"]' \\
'build-backend = "setuptools.build_meta"'; do \\
echo "$line" >> /deps/__outer_graphs_reqs_a/pyproject.toml; \\
echo "$line" >> /deps/outer-graphs_reqs_a/pyproject.toml; \\
done
# -- End of non-package dependency graphs_reqs_a --
# -- Installing all local dependencies --
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --no-cache-dir -c /api/constraints.txt -e /deps/*
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --prerelease=allow --no-cache-dir -c /api/constraints.txt -e /deps/*
# -- End of local dependencies install --
ENV LANGGRAPH_HTTP='{{"app": "/deps/examples/my_app.py:app"}}'
ENV LANGSERVE_GRAPHS='{{"agent": "/deps/__outer_unit_tests/unit_tests/agent.py:graph"}}'
ENV LANGSERVE_GRAPHS='{{"agent": "/deps/outer-unit_tests/unit_tests/agent.py:graph"}}'
{FORMATTED_CLEANUP_LINES}
WORKDIR /deps/__outer_unit_tests/unit_tests\
WORKDIR /deps/outer-unit_tests/unit_tests\
"""
assert clean_empty_lines(actual_docker_stdin) == expected_docker_stdin
assert additional_contexts == {
"__outer_graphs_reqs_a": str(
"outer-graphs_reqs_a": str(
(pathlib.Path(__file__).parent / "../../examples/graphs_reqs_a").resolve()
),
"examples": str((pathlib.Path(__file__).parent / "../../examples").resolve()),
@@ -484,7 +484,7 @@ def test_config_to_docker_outside_path():
"""\
FROM langchain/langgraph-api:3.11
# -- Adding non-package dependency unit_tests --
ADD . /deps/__outer_unit_tests/unit_tests
ADD . /deps/outer-unit_tests/unit_tests
RUN set -ex && \\
for line in '[project]' \\
'name = "unit_tests"' \\
@@ -494,11 +494,11 @@ RUN set -ex && \\
'[build-system]' \\
'requires = ["setuptools>=61"]' \\
'build-backend = "setuptools.build_meta"'; do \\
echo "$line" >> /deps/__outer_unit_tests/pyproject.toml; \\
echo "$line" >> /deps/outer-unit_tests/pyproject.toml; \\
done
# -- End of non-package dependency unit_tests --
# -- Adding non-package dependency tests --
COPY --from=__outer_tests . /deps/__outer_tests/tests
COPY --from=outer-tests . /deps/outer-tests/tests
RUN set -ex && \\
for line in '[project]' \\
'name = "tests"' \\
@@ -508,22 +508,22 @@ RUN set -ex && \\
'[build-system]' \\
'requires = ["setuptools>=61"]' \\
'build-backend = "setuptools.build_meta"'; do \\
echo "$line" >> /deps/__outer_tests/pyproject.toml; \\
echo "$line" >> /deps/outer-tests/pyproject.toml; \\
done
# -- End of non-package dependency tests --
# -- Installing all local dependencies --
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --no-cache-dir -c /api/constraints.txt -e /deps/*
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --prerelease=allow --no-cache-dir -c /api/constraints.txt -e /deps/*
# -- End of local dependencies install --
ENV LANGSERVE_GRAPHS='{"agent": "/deps/__outer_unit_tests/unit_tests/agent.py:graph"}'
ENV LANGSERVE_GRAPHS='{"agent": "/deps/outer-unit_tests/unit_tests/agent.py:graph"}'
"""
+ FORMATTED_CLEANUP_LINES
+ """
WORKDIR /deps/__outer_unit_tests/unit_tests\
WORKDIR /deps/outer-unit_tests/unit_tests\
"""
)
assert clean_empty_lines(actual_docker_stdin) == expected_docker_stdin
assert additional_contexts == {
"__outer_tests": str(pathlib.Path(__file__).parent.parent.absolute()),
"outer-tests": str(pathlib.Path(__file__).parent.parent.absolute()),
}
@@ -545,7 +545,7 @@ def test_config_to_docker_pipconfig():
FROM langchain/langgraph-api:3.11
ADD pipconfig.txt /pipconfig.txt
# -- Adding non-package dependency unit_tests --
ADD . /deps/__outer_unit_tests/unit_tests
ADD . /deps/outer-unit_tests/unit_tests
RUN set -ex && \\
for line in '[project]' \\
'name = "unit_tests"' \\
@@ -555,17 +555,17 @@ RUN set -ex && \\
'[build-system]' \\
'requires = ["setuptools>=61"]' \\
'build-backend = "setuptools.build_meta"'; do \\
echo "$line" >> /deps/__outer_unit_tests/pyproject.toml; \\
echo "$line" >> /deps/outer-unit_tests/pyproject.toml; \\
done
# -- End of non-package dependency unit_tests --
# -- Installing all local dependencies --
RUN PIP_CONFIG_FILE=/pipconfig.txt PYTHONDONTWRITEBYTECODE=1 uv pip install --system --no-cache-dir -c /api/constraints.txt -e /deps/*
RUN PIP_CONFIG_FILE=/pipconfig.txt PYTHONDONTWRITEBYTECODE=1 uv pip install --system --prerelease=allow --no-cache-dir -c /api/constraints.txt -e /deps/*
# -- End of local dependencies install --
ENV LANGSERVE_GRAPHS='{"agent": "/deps/__outer_unit_tests/unit_tests/agent.py:graph"}'
ENV LANGSERVE_GRAPHS='{"agent": "/deps/outer-unit_tests/unit_tests/agent.py:graph"}'
"""
+ FORMATTED_CLEANUP_LINES
+ """
WORKDIR /deps/__outer_unit_tests/unit_tests\
WORKDIR /deps/outer-unit_tests/unit_tests\
"""
)
assert clean_empty_lines(actual_docker_stdin) == expected_docker_stdin
@@ -607,7 +607,7 @@ def test_config_to_docker_local_deps():
expected_docker_stdin = f"""\
FROM langchain/langgraph-api-custom:3.11
# -- Adding non-package dependency graphs --
ADD ./graphs /deps/__outer_graphs/src
ADD ./graphs /deps/outer-graphs/src
RUN set -ex && \\
for line in '[project]' \\
'name = "graphs"' \\
@@ -617,13 +617,13 @@ RUN set -ex && \\
'[build-system]' \\
'requires = ["setuptools>=61"]' \\
'build-backend = "setuptools.build_meta"'; do \\
echo "$line" >> /deps/__outer_graphs/pyproject.toml; \\
echo "$line" >> /deps/outer-graphs/pyproject.toml; \\
done
# -- End of non-package dependency graphs --
# -- Installing all local dependencies --
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --no-cache-dir -c /api/constraints.txt -e /deps/*
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --prerelease=allow --no-cache-dir -c /api/constraints.txt -e /deps/*
# -- End of local dependencies install --
ENV LANGSERVE_GRAPHS='{{"agent": "/deps/__outer_graphs/src/agent.py:graph"}}'
ENV LANGSERVE_GRAPHS='{{"agent": "/deps/outer-graphs/src/agent.py:graph"}}'
{FORMATTED_CLEANUP_LINES}\
"""
assert clean_empty_lines(actual_docker_stdin) == expected_docker_stdin
@@ -657,7 +657,7 @@ dependencies = ["langchain"]"""
ADD . /deps/unit_tests
# -- End of local package . --
# -- Installing all local dependencies --
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --no-cache-dir -c /api/constraints.txt -e /deps/*
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --prerelease=allow --no-cache-dir -c /api/constraints.txt -e /deps/*
# -- End of local dependencies install --
ENV LANGSERVE_GRAPHS='{"agent": "/deps/unit_tests/graphs/agent.py:graph"}'
"""
@@ -689,9 +689,9 @@ def test_config_to_docker_end_to_end():
ARG meow
ARG foo
ADD pipconfig.txt /pipconfig.txt
RUN PIP_CONFIG_FILE=/pipconfig.txt PYTHONDONTWRITEBYTECODE=1 uv pip install --system --no-cache-dir -c /api/constraints.txt langchain langchain_openai
RUN PIP_CONFIG_FILE=/pipconfig.txt PYTHONDONTWRITEBYTECODE=1 uv pip install --system --prerelease=allow --no-cache-dir -c /api/constraints.txt langchain langchain_openai
# -- Adding non-package dependency graphs --
ADD ./graphs/ /deps/__outer_graphs/src
ADD ./graphs/ /deps/outer-graphs/src
RUN set -ex && \\
for line in '[project]' \\
'name = "graphs"' \\
@@ -701,13 +701,13 @@ RUN set -ex && \\
'[build-system]' \\
'requires = ["setuptools>=61"]' \\
'build-backend = "setuptools.build_meta"'; do \\
echo "$line" >> /deps/__outer_graphs/pyproject.toml; \\
echo "$line" >> /deps/outer-graphs/pyproject.toml; \\
done
# -- End of non-package dependency graphs --
# -- Installing all local dependencies --
RUN PIP_CONFIG_FILE=/pipconfig.txt PYTHONDONTWRITEBYTECODE=1 uv pip install --system --no-cache-dir -c /api/constraints.txt -e /deps/*
RUN PIP_CONFIG_FILE=/pipconfig.txt PYTHONDONTWRITEBYTECODE=1 uv pip install --system --prerelease=allow --no-cache-dir -c /api/constraints.txt -e /deps/*
# -- End of local dependencies install --
ENV LANGSERVE_GRAPHS='{{"agent": "/deps/__outer_graphs/src/agent.py:graph"}}'
ENV LANGSERVE_GRAPHS='{{"agent": "/deps/outer-graphs/src/agent.py:graph"}}'
{FORMATTED_CLEANUP_LINES}"""
assert clean_empty_lines(actual_docker_stdin) == expected_docker_stdin
assert additional_contexts == {}
@@ -797,7 +797,7 @@ def test_config_to_docker_gen_ui_python():
expected_docker_stdin = f"""FROM langchain/langgraph-api:3.11
RUN /storage/install-node.sh
# -- Adding non-package dependency unit_tests --
ADD . /deps/__outer_unit_tests/unit_tests
ADD . /deps/outer-unit_tests/unit_tests
RUN set -ex && \\
for line in '[project]' \\
'name = "unit_tests"' \\
@@ -807,21 +807,21 @@ RUN set -ex && \\
'[build-system]' \\
'requires = ["setuptools>=61"]' \\
'build-backend = "setuptools.build_meta"'; do \\
echo "$line" >> /deps/__outer_unit_tests/pyproject.toml; \\
echo "$line" >> /deps/outer-unit_tests/pyproject.toml; \\
done
# -- End of non-package dependency unit_tests --
# -- Installing all local dependencies --
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --no-cache-dir -c /api/constraints.txt -e /deps/*
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --prerelease=allow --no-cache-dir -c /api/constraints.txt -e /deps/*
# -- End of local dependencies install --
ENV LANGGRAPH_UI='{{"agent": "./graphs/agent.ui.jsx"}}'
ENV LANGGRAPH_UI_CONFIG='{{"shared": ["nuqs"]}}'
ENV LANGSERVE_GRAPHS='{{"agent": "/deps/__outer_unit_tests/unit_tests/agent.py:graph"}}'
ENV LANGSERVE_GRAPHS='{{"agent": "/deps/outer-unit_tests/unit_tests/agent.py:graph"}}'
# -- Installing JS dependencies --
ENV NODE_VERSION=20
RUN cd /deps/__outer_unit_tests/unit_tests && npm i && tsx /api/langgraph_api/js/build.mts
RUN cd /deps/outer-unit_tests/unit_tests && npm i && tsx /api/langgraph_api/js/build.mts
# -- End of JS dependencies install --
{FORMATTED_CLEANUP_LINES}
WORKDIR /deps/__outer_unit_tests/unit_tests"""
WORKDIR /deps/outer-unit_tests/unit_tests"""
assert clean_empty_lines(actual_docker_stdin) == expected_docker_stdin
assert additional_contexts == {}
@@ -843,7 +843,7 @@ def test_config_to_docker_multiplatform():
expected_docker_stdin = f"""FROM langchain/langgraph-api:3.11
RUN /storage/install-node.sh
# -- Adding non-package dependency unit_tests --
ADD . /deps/__outer_unit_tests/unit_tests
ADD . /deps/outer-unit_tests/unit_tests
RUN set -ex && \\
for line in '[project]' \\
'name = "unit_tests"' \\
@@ -853,19 +853,19 @@ RUN set -ex && \\
'[build-system]' \\
'requires = ["setuptools>=61"]' \\
'build-backend = "setuptools.build_meta"'; do \\
echo "$line" >> /deps/__outer_unit_tests/pyproject.toml; \\
echo "$line" >> /deps/outer-unit_tests/pyproject.toml; \\
done
# -- End of non-package dependency unit_tests --
# -- Installing all local dependencies --
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --no-cache-dir -c /api/constraints.txt -e /deps/*
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --prerelease=allow --no-cache-dir -c /api/constraints.txt -e /deps/*
# -- End of local dependencies install --
ENV LANGSERVE_GRAPHS='{{"python": "/deps/__outer_unit_tests/unit_tests/multiplatform/python.py:graph", "js": "/deps/__outer_unit_tests/unit_tests/multiplatform/js.mts:graph"}}'
ENV LANGSERVE_GRAPHS='{{"python": "/deps/outer-unit_tests/unit_tests/multiplatform/python.py:graph", "js": "/deps/outer-unit_tests/unit_tests/multiplatform/js.mts:graph"}}'
# -- Installing JS dependencies --
ENV NODE_VERSION=22
RUN cd /deps/__outer_unit_tests/unit_tests && npm i && tsx /api/langgraph_api/js/build.mts
RUN cd /deps/outer-unit_tests/unit_tests && npm i && tsx /api/langgraph_api/js/build.mts
# -- End of JS dependencies install --
{FORMATTED_CLEANUP_LINES}
WORKDIR /deps/__outer_unit_tests/unit_tests"""
WORKDIR /deps/outer-unit_tests/unit_tests"""
assert clean_empty_lines(actual_docker_stdin) == expected_docker_stdin
assert additional_contexts == {}
@@ -887,7 +887,7 @@ def test_config_to_docker_pip_installer():
docker_auto, _ = config_to_docker(
PATH_TO_CONFIG, config_auto, "langchain/langgraph-api:0.2.47"
)
assert "uv pip install --system" in docker_auto
assert "uv pip install --system --prerelease=allow" in docker_auto
assert "rm /usr/bin/uv /usr/bin/uvx" in docker_auto
# Test explicit pip setting
@@ -895,7 +895,7 @@ def test_config_to_docker_pip_installer():
docker_pip, _ = config_to_docker(
PATH_TO_CONFIG, config_pip, "langchain/langgraph-api:0.2.47"
)
assert "uv pip install --system" not in docker_pip
assert "uv pip install --system --prerelease=allow" not in docker_pip
assert "pip install" in docker_pip
assert "rm /usr/bin/uv" not in docker_pip
@@ -904,7 +904,7 @@ def test_config_to_docker_pip_installer():
docker_uv, _ = config_to_docker(
PATH_TO_CONFIG, config_uv, "langchain/langgraph-api:0.2.47"
)
assert "uv pip install --system" in docker_uv
assert "uv pip install --system --prerelease=allow" in docker_uv
assert "rm /usr/bin/uv /usr/bin/uvx" in docker_uv
# Test auto behavior with older image (should use pip)
@@ -914,7 +914,7 @@ def test_config_to_docker_pip_installer():
docker_auto_old, _ = config_to_docker(
PATH_TO_CONFIG, config_auto_old, "langchain/langgraph-api:0.2.46"
)
assert "uv pip install --system" not in docker_auto_old
assert "uv pip install --system --prerelease=allow" not in docker_auto_old
assert "pip install" in docker_auto_old
assert "rm /usr/bin/uv" not in docker_auto_old
@@ -923,7 +923,7 @@ def test_config_to_docker_pip_installer():
docker_default, _ = config_to_docker(
PATH_TO_CONFIG, config_default, "langchain/langgraph-api:0.2.47"
)
assert "uv pip install --system" in docker_default
assert "uv pip install --system --prerelease=allow" in docker_default
def test_config_retain_build_tools():
@@ -984,7 +984,7 @@ def test_config_to_compose_simple_config():
dockerfile_inline: |
FROM langchain/langgraph-api:3.11
# -- Adding non-package dependency unit_tests --
ADD . /deps/__outer_unit_tests/unit_tests
ADD . /deps/outer-unit_tests/unit_tests
RUN set -ex && \\
for line in '[project]' \\
'name = "unit_tests"' \\
@@ -994,15 +994,15 @@ def test_config_to_compose_simple_config():
'[build-system]' \\
'requires = ["setuptools>=61"]' \\
'build-backend = "setuptools.build_meta"'; do \\
echo "$line" >> /deps/__outer_unit_tests/pyproject.toml; \\
echo "$line" >> /deps/outer-unit_tests/pyproject.toml; \\
done
# -- End of non-package dependency unit_tests --
# -- Installing all local dependencies --
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --no-cache-dir -c /api/constraints.txt -e /deps/*
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --prerelease=allow --no-cache-dir -c /api/constraints.txt -e /deps/*
# -- End of local dependencies install --
ENV LANGSERVE_GRAPHS='{{"agent": "/deps/__outer_unit_tests/unit_tests/agent.py:graph"}}'
ENV LANGSERVE_GRAPHS='{{"agent": "/deps/outer-unit_tests/unit_tests/agent.py:graph"}}'
{textwrap.indent(textwrap.dedent(FORMATTED_CLEANUP_LINES), " ")}
WORKDIR /deps/__outer_unit_tests/unit_tests
WORKDIR /deps/outer-unit_tests/unit_tests
"""
actual_compose_stdin = config_to_compose(
PATH_TO_CONFIG,
@@ -1025,7 +1025,7 @@ def test_config_to_compose_env_vars():
dockerfile_inline: |
FROM langchain/langgraph-api-custom:3.11
# -- Adding non-package dependency unit_tests --
ADD . /deps/__outer_unit_tests/unit_tests
ADD . /deps/outer-unit_tests/unit_tests
RUN set -ex && \\
for line in '[project]' \\
'name = "unit_tests"' \\
@@ -1035,15 +1035,15 @@ def test_config_to_compose_env_vars():
'[build-system]' \\
'requires = ["setuptools>=61"]' \\
'build-backend = "setuptools.build_meta"'; do \\
echo "$line" >> /deps/__outer_unit_tests/pyproject.toml; \\
echo "$line" >> /deps/outer-unit_tests/pyproject.toml; \\
done
# -- End of non-package dependency unit_tests --
# -- Installing all local dependencies --
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --no-cache-dir -c /api/constraints.txt -e /deps/*
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --prerelease=allow --no-cache-dir -c /api/constraints.txt -e /deps/*
# -- End of local dependencies install --
ENV LANGSERVE_GRAPHS='{{"agent": "/deps/__outer_unit_tests/unit_tests/agent.py:graph"}}'
ENV LANGSERVE_GRAPHS='{{"agent": "/deps/outer-unit_tests/unit_tests/agent.py:graph"}}'
{textwrap.indent(textwrap.dedent(FORMATTED_CLEANUP_LINES), " ")}
WORKDIR /deps/__outer_unit_tests/unit_tests
WORKDIR /deps/outer-unit_tests/unit_tests
"""
openai_api_key = "key"
actual_compose_stdin = config_to_compose(
@@ -1070,7 +1070,7 @@ def test_config_to_compose_env_file():
dockerfile_inline: |
FROM langchain/langgraph-api:3.11
# -- Adding non-package dependency unit_tests --
ADD . /deps/__outer_unit_tests/unit_tests
ADD . /deps/outer-unit_tests/unit_tests
RUN set -ex && \\
for line in '[project]' \\
'name = "unit_tests"' \\
@@ -1080,15 +1080,15 @@ def test_config_to_compose_env_file():
'[build-system]' \\
'requires = ["setuptools>=61"]' \\
'build-backend = "setuptools.build_meta"'; do \\
echo "$line" >> /deps/__outer_unit_tests/pyproject.toml; \\
echo "$line" >> /deps/outer-unit_tests/pyproject.toml; \\
done
# -- End of non-package dependency unit_tests --
# -- Installing all local dependencies --
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --no-cache-dir -c /api/constraints.txt -e /deps/*
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --prerelease=allow --no-cache-dir -c /api/constraints.txt -e /deps/*
# -- End of local dependencies install --
ENV LANGSERVE_GRAPHS='{{"agent": "/deps/__outer_unit_tests/unit_tests/agent.py:graph"}}'
ENV LANGSERVE_GRAPHS='{{"agent": "/deps/outer-unit_tests/unit_tests/agent.py:graph"}}'
{textwrap.indent(textwrap.dedent(FORMATTED_CLEANUP_LINES), " ")}
WORKDIR /deps/__outer_unit_tests/unit_tests
WORKDIR /deps/outer-unit_tests/unit_tests
"""
actual_compose_stdin = config_to_compose(
PATH_TO_CONFIG,
@@ -1108,7 +1108,7 @@ def test_config_to_compose_watch():
dockerfile_inline: |
FROM langchain/langgraph-api:3.11
# -- Adding non-package dependency unit_tests --
ADD . /deps/__outer_unit_tests/unit_tests
ADD . /deps/outer-unit_tests/unit_tests
RUN set -ex && \\
for line in '[project]' \\
'name = "unit_tests"' \\
@@ -1118,15 +1118,15 @@ def test_config_to_compose_watch():
'[build-system]' \\
'requires = ["setuptools>=61"]' \\
'build-backend = "setuptools.build_meta"'; do \\
echo "$line" >> /deps/__outer_unit_tests/pyproject.toml; \\
echo "$line" >> /deps/outer-unit_tests/pyproject.toml; \\
done
# -- End of non-package dependency unit_tests --
# -- Installing all local dependencies --
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --no-cache-dir -c /api/constraints.txt -e /deps/*
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --prerelease=allow --no-cache-dir -c /api/constraints.txt -e /deps/*
# -- End of local dependencies install --
ENV LANGSERVE_GRAPHS='{{"agent": "/deps/__outer_unit_tests/unit_tests/agent.py:graph"}}'
ENV LANGSERVE_GRAPHS='{{"agent": "/deps/outer-unit_tests/unit_tests/agent.py:graph"}}'
{textwrap.indent(textwrap.dedent(FORMATTED_CLEANUP_LINES), " ")}
WORKDIR /deps/__outer_unit_tests/unit_tests
WORKDIR /deps/outer-unit_tests/unit_tests
develop:
watch:
@@ -1155,7 +1155,7 @@ def test_config_to_compose_end_to_end():
dockerfile_inline: |
FROM langchain/langgraph-api:3.11
# -- Adding non-package dependency unit_tests --
ADD . /deps/__outer_unit_tests/unit_tests
ADD . /deps/outer-unit_tests/unit_tests
RUN set -ex && \\
for line in '[project]' \\
'name = "unit_tests"' \\
@@ -1165,15 +1165,15 @@ def test_config_to_compose_end_to_end():
'[build-system]' \\
'requires = ["setuptools>=61"]' \\
'build-backend = "setuptools.build_meta"'; do \\
echo "$line" >> /deps/__outer_unit_tests/pyproject.toml; \\
echo "$line" >> /deps/outer-unit_tests/pyproject.toml; \\
done
# -- End of non-package dependency unit_tests --
# -- Installing all local dependencies --
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --no-cache-dir -c /api/constraints.txt -e /deps/*
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --prerelease=allow --no-cache-dir -c /api/constraints.txt -e /deps/*
# -- End of local dependencies install --
ENV LANGSERVE_GRAPHS='{{"agent": "/deps/__outer_unit_tests/unit_tests/agent.py:graph"}}'
ENV LANGSERVE_GRAPHS='{{"agent": "/deps/outer-unit_tests/unit_tests/agent.py:graph"}}'
{textwrap.indent(textwrap.dedent(FORMATTED_CLEANUP_LINES), " ")}
WORKDIR /deps/__outer_unit_tests/unit_tests
WORKDIR /deps/outer-unit_tests/unit_tests
develop:
watch:
+3 -1
View File
@@ -5,7 +5,9 @@
"Bash(python:*)",
"Bash(grep:*)",
"Bash(sed:*)",
"Bash(awk:*)"
"Bash(awk:*)",
"Bash(uv run mypy:*)",
"Bash(uv run:*)"
],
"deny": []
}
+7 -1
View File
@@ -25,7 +25,7 @@ from typing import (
from langchain_core.runnables import Runnable, RunnableConfig
from pydantic import BaseModel, TypeAdapter
from typing_extensions import Self, Unpack, is_typeddict
from typing_extensions import NotRequired, Required, Self, Unpack, is_typeddict
from langgraph._internal._constants import (
INTERRUPT,
@@ -1334,6 +1334,12 @@ def _get_channel(
def _get_channel(
name: str, annotation: Any, *, allow_managed: bool = True
) -> BaseChannel | ManagedValueSpec:
# Strip out Required and NotRequired wrappers
if hasattr(annotation, "__origin__") and annotation.__origin__ in (
Required,
NotRequired,
):
annotation = annotation.__args__[0]
if manager := _is_field_managed_value(name, annotation):
if allow_managed:
return manager
+4 -1
View File
@@ -10,6 +10,7 @@ from langchain_core.runnables import RunnableConfig
from pydantic import BaseModel
from typing_extensions import NotRequired, Required, TypedDict
from langgraph.channels.binop import BinaryOperatorAggregate
from langgraph.graph.state import StateGraph, _get_node_name, _warn_invalid_state_schema
@@ -137,7 +138,7 @@ def test_state_schema_optional_values(total_: bool):
class InputState(SomeParentState, total=total_): # type: ignore
val1: str
val2: Optional[str]
val3: Required[str]
val3: Required[Annotated[dict, operator.or_]]
val4: NotRequired[dict]
val5: Annotated[Required[str], "foo"]
val6: Annotated[NotRequired[str], "bar"]
@@ -159,6 +160,8 @@ def test_state_schema_optional_values(total_: bool):
graph = builder.compile()
json_schema = graph.get_input_jsonschema()
assert isinstance(graph.channels["val3"], BinaryOperatorAggregate)
if total_ is False:
expected_required = set()
expected_optional = {"val2", "val1"}
+1 -1
View File
@@ -1,6 +1,6 @@
from langgraph_sdk.auth import Auth
from langgraph_sdk.client import get_client, get_sync_client
__version__ = "0.2.3"
__version__ = "0.2.6"
__all__ = ["Auth", "get_client", "get_sync_client"]
+20
View File
@@ -400,6 +400,20 @@ class AuthContext(BaseAuthContext):
"""
class ThreadTTL(typing.TypedDict, total=False):
"""Time-to-live configuration for a thread.
Matches the OpenAPI schema where TTL is represented as an object with
an optional strategy and a time value in minutes.
"""
strategy: typing.Literal["delete"]
"""TTL strategy. Currently only 'delete' is supported."""
ttl: int
"""Time-to-live in minutes from now until the thread should be swept."""
class ThreadsCreate(typing.TypedDict, total=False):
"""Parameters for creating a new thread.
@@ -422,6 +436,9 @@ class ThreadsCreate(typing.TypedDict, total=False):
if_exists: OnConflictBehavior
"""Behavior when a thread with the same ID already exists."""
ttl: ThreadTTL
"""Optional TTL configuration for the thread."""
class ThreadsRead(typing.TypedDict, total=False):
"""Parameters for reading thread state or run information.
@@ -489,6 +506,9 @@ class ThreadsSearch(typing.TypedDict, total=False):
offset: int
"""Offset for pagination."""
ids: Sequence[UUID] | None
"""typing.Optional list of thread IDs to filter by."""
thread_id: UUID | None
"""typing.Optional thread ID to filter by."""
+284 -37
View File
@@ -15,6 +15,7 @@ import logging
import os
import re
import sys
import warnings
from collections.abc import AsyncIterator, Iterator, Mapping, Sequence
from types import TracebackType
from typing import (
@@ -45,6 +46,7 @@ from langgraph_sdk.schema import (
CronSelectField,
CronSortBy,
DisconnectMode,
Durability,
GraphSchema,
IfNotExists,
Item,
@@ -69,6 +71,7 @@ from langgraph_sdk.schema import (
ThreadSortBy,
ThreadState,
ThreadStatus,
ThreadStreamMode,
ThreadUpdateStateResponse,
)
from langgraph_sdk.sse import SSEDecoder, aiter_lines_raw, iter_lines_raw
@@ -154,37 +157,63 @@ def get_client(
headers: Mapping[str, str] | None = None,
timeout: TimeoutTypes | None = None,
) -> LangGraphClient:
"""Get a LangGraphClient instance.
"""Create and configure a LangGraphClient.
The client provides programmatic access to a LangGraph Platform deployment. It supports
both remote servers and local in-process connections (when running inside a LangGraph server).
Args:
url: The URL of the LangGraph API.
api_key: The API key. If not provided, it will be read from the environment.
Precedence:
1. explicit argument
2. LANGGRAPH_API_KEY
3. LANGSMITH_API_KEY
4. LANGCHAIN_API_KEY
headers: Optional custom headers
timeout: Optional timeout configuration for the HTTP client.
Accepts an httpx.Timeout instance, a float (seconds), or a tuple of timeouts.
Tuple format is (connect, read, write, pool)
If not provided, defaults to connect=5s, read=300s, write=300s, and pool=5s.
url:
Base URL of the LangGraph API.
If `None`, the client first attempts an in-process connection via ASGI transport.
If that fails, it falls back to `http://localhost:8123`.
api_key:
API key for authentication. If omitted, the client reads from environment
variables in the following order:
1. Function argument
2. `LANGGRAPH_API_KEY`
3. `LANGSMITH_API_KEY`
4. `LANGCHAIN_API_KEY`
headers:
Additional HTTP headers to include in requests. Merged with authentication headers.
timeout:
HTTP timeout configuration. May be:
`httpx.Timeout` instance
float (total seconds)
tuple `(connect, read, write, pool)` in seconds
Defaults: connect=5, read=300, write=300, pool=5.
Returns:
LangGraphClient: The top-level client for accessing AssistantsClient,
ThreadsClient, RunsClient, and CronClient.
LangGraphClient:
A top-level client exposing sub-clients for assistants, threads,
runs, and cron operations.
???+ example "Example"
???+ example "Connect to a remote server:"
```python
from langgraph_sdk import get_client
```python
from langgraph_sdk import get_client
# get top-level LangGraphClient
client = get_client(url="http://localhost:8123")
# get top-level LangGraphClient
client = get_client(url="http://localhost:8123")
# example usage: client.<model>.<method_name>()
assistants = await client.assistants.get(assistant_id="some_uuid")
```
# example usage: client.<model>.<method_name>()
assistants = await client.assistants.get(assistant_id="some_uuid")
```
???+ example "Connect in-process to a running LangGraph server:"
```python
from langgraph_sdk import get_client
client = get_client(url=None)
async def my_node(...):
subagent_result = await client.runs.wait(
thread_id=None,
assistant_id="agent",
input={"messages": [{"role": "user", "content": "Foo"}]},
)
```
"""
transport: httpx.AsyncBaseTransport | None = None
@@ -1176,6 +1205,7 @@ class ThreadsClient:
if_exists: OnConflictBehavior | None = None,
supersteps: Sequence[dict[str, Sequence[dict[str, Any]]]] | None = None,
graph_id: str | None = None,
ttl: int | Mapping[str, Any] | None = None,
headers: Mapping[str, str] | None = None,
params: QueryParamTypes | None = None,
) -> Thread:
@@ -1190,6 +1220,9 @@ class ThreadsClient:
supersteps: Apply a list of supersteps when creating a thread, each containing a sequence of updates.
Each update has `values` or `command` and `as_node`. Used for copying a thread between deployments.
graph_id: Optional graph ID to associate with the thread.
ttl: Optional time-to-live in minutes for the thread. You can pass an
integer (minutes) or a mapping with keys `ttl` and optional
`strategy` (defaults to "delete").
headers: Optional custom headers to include with the request.
params: Optional query parameters to include with the request.
@@ -1231,6 +1264,11 @@ class ThreadsClient:
}
for s in supersteps
]
if ttl is not None:
if isinstance(ttl, (int, float)):
payload["ttl"] = {"ttl": ttl, "strategy": "delete"}
else:
payload["ttl"] = ttl
return await self.http.post(
"/threads", json=payload, headers=headers, params=params
@@ -1241,6 +1279,7 @@ class ThreadsClient:
thread_id: str,
*,
metadata: Mapping[str, Any],
ttl: int | Mapping[str, Any] | None = None,
headers: Mapping[str, str] | None = None,
params: QueryParamTypes | None = None,
) -> Thread:
@@ -1249,6 +1288,9 @@ class ThreadsClient:
Args:
thread_id: ID of thread to update.
metadata: Metadata to merge with existing thread metadata.
ttl: Optional time-to-live in minutes for the thread. You can pass an
integer (minutes) or a mapping with keys `ttl` and optional
`strategy` (defaults to "delete").
headers: Optional custom headers to include with the request.
params: Optional query parameters to include with the request.
@@ -1262,12 +1304,19 @@ class ThreadsClient:
thread = await client.threads.update(
thread_id="my-thread-id",
metadata={"number":1},
ttl=43_200,
)
```
""" # noqa: E501
payload: dict[str, Any] = {"metadata": metadata}
if ttl is not None:
if isinstance(ttl, (int, float)):
payload["ttl"] = {"ttl": ttl, "strategy": "delete"}
else:
payload["ttl"] = ttl
return await self.http.patch(
f"/threads/{thread_id}",
json={"metadata": metadata},
json=payload,
headers=headers,
params=params,
)
@@ -1306,6 +1355,7 @@ class ThreadsClient:
*,
metadata: Json = None,
values: Json = None,
ids: Sequence[str] | None = None,
status: ThreadStatus | None = None,
limit: int = 10,
offset: int = 0,
@@ -1320,6 +1370,7 @@ class ThreadsClient:
Args:
metadata: Thread metadata to filter on.
values: State values to filter on.
ids: List of thread IDs to filter by.
status: Thread status to filter on.
Must be one of 'idle', 'busy', 'interrupted' or 'error'.
limit: Limit on number of threads to return.
@@ -1353,6 +1404,8 @@ class ThreadsClient:
payload["metadata"] = metadata
if values:
payload["values"] = values
if ids:
payload["ids"] = ids
if status:
payload["status"] = status
if sort_by:
@@ -1682,6 +1735,53 @@ class ThreadsClient:
params=params,
)
async def join_stream(
self,
thread_id: str,
*,
last_event_id: str | None = None,
stream_mode: ThreadStreamMode | Sequence[ThreadStreamMode] = "run_modes",
headers: Mapping[str, str] | None = None,
params: QueryParamTypes | None = None,
) -> AsyncIterator[StreamPart]:
"""Get a stream of events for a thread.
Args:
thread_id: The ID of the thread to get the stream for.
last_event_id: The ID of the last event to get.
headers: Optional custom headers to include with the request.
params: Optional query parameters to include with the request.
Returns:
Iterator[StreamPart]: An iterator of stream parts.
???+ example "Example Usage"
```python
for chunk in client.threads.join_stream(
thread_id="my_thread_id",
last_event_id="my_event_id",
):
print(chunk)
```
""" # noqa: E501
query_params = {
"stream_mode": stream_mode,
}
if params:
query_params.update(params)
return self.http.stream(
f"/threads/{thread_id}/stream",
"GET",
headers={
**({"Last-Event-ID": last_event_id} if last_event_id else {}),
**(headers or {}),
},
params=query_params,
)
class RunsClient:
"""Client for managing runs in LangGraph.
@@ -1772,7 +1872,7 @@ class RunsClient:
context: Context | None = None,
checkpoint: Checkpoint | None = None,
checkpoint_id: str | None = None,
checkpoint_during: bool | None = None,
checkpoint_during: bool | None = None, # deprecated
interrupt_before: All | Sequence[str] | None = None,
interrupt_after: All | Sequence[str] | None = None,
feedback_keys: Sequence[str] | None = None,
@@ -1785,6 +1885,7 @@ class RunsClient:
headers: Mapping[str, str] | None = None,
params: QueryParamTypes | None = None,
on_run_created: Callable[[RunCreateMetadata], None] | None = None,
durability: Durability | None = None,
) -> AsyncIterator[StreamPart]:
"""Create a run and stream the results.
@@ -1804,7 +1905,7 @@ class RunsClient:
context: Static context to add to the assistant.
!!! version-added "Supported with langgraph>=0.6.0"
checkpoint: The checkpoint to resume from.
checkpoint_during: Whether to checkpoint during the run (or only at the end/interruption).
checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
interrupt_before: Nodes to interrupt immediately before they get executed.
interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
feedback_keys: Feedback keys to assign to run.
@@ -1822,6 +1923,10 @@ class RunsClient:
headers: Optional custom headers to include with the request.
params: Optional query parameters to include with the request.
on_run_created: Callback when a run is created.
durability: The durability to use for the run. Values are "sync", "async", or "exit".
"async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
"sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
"exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
Returns:
AsyncIterator[StreamPart]: Asynchronous iterator of stream results.
@@ -1857,6 +1962,13 @@ class RunsClient:
```
""" # noqa: E501
if checkpoint_during is not None:
warnings.warn(
"`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
DeprecationWarning,
stacklevel=2,
)
payload = {
"input": input,
"command": (
@@ -1881,6 +1993,7 @@ class RunsClient:
"on_disconnect": on_disconnect,
"on_completion": on_completion,
"after_seconds": after_seconds,
"durability": durability,
}
endpoint = (
f"/threads/{thread_id}/runs/stream"
@@ -1971,7 +2084,7 @@ class RunsClient:
context: Context | None = None,
checkpoint: Checkpoint | None = None,
checkpoint_id: str | None = None,
checkpoint_during: bool | None = None,
checkpoint_during: bool | None = None, # deprecated
interrupt_before: All | Sequence[str] | None = None,
interrupt_after: All | Sequence[str] | None = None,
webhook: str | None = None,
@@ -1982,6 +2095,7 @@ class RunsClient:
headers: Mapping[str, str] | None = None,
params: QueryParamTypes | None = None,
on_run_created: Callable[[RunCreateMetadata], None] | None = None,
durability: Durability | None = None,
) -> Run:
"""Create a background run.
@@ -2001,7 +2115,7 @@ class RunsClient:
context: Static context to add to the assistant.
!!! version-added "Supported with langgraph>=0.6.0"
checkpoint: The checkpoint to resume from.
checkpoint_during: Whether to checkpoint during the run (or only at the end/interruption).
checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
interrupt_before: Nodes to interrupt immediately before they get executed.
interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
webhook: Webhook to call after LangGraph API call is done.
@@ -2015,6 +2129,10 @@ class RunsClient:
Use to schedule future runs.
headers: Optional custom headers to include with the request.
on_run_created: Optional callback to call when a run is created.
durability: The durability to use for the run. Values are "sync", "async", or "exit".
"async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
"sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
"exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
Returns:
Run: The created background run.
@@ -2090,6 +2208,12 @@ class RunsClient:
}
```
""" # noqa: E501
if checkpoint_during is not None:
warnings.warn(
"`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
DeprecationWarning,
stacklevel=2,
)
payload = {
"input": input,
"command": (
@@ -2112,6 +2236,7 @@ class RunsClient:
"if_not_exists": if_not_exists,
"on_completion": on_completion,
"after_seconds": after_seconds,
"durability": durability,
}
payload = {k: v for k, v in payload.items() if v is not None}
@@ -2209,7 +2334,7 @@ class RunsClient:
context: Context | None = None,
checkpoint: Checkpoint | None = None,
checkpoint_id: str | None = None,
checkpoint_during: bool | None = None,
checkpoint_during: bool | None = None, # deprecated
interrupt_before: All | Sequence[str] | None = None,
interrupt_after: All | Sequence[str] | None = None,
webhook: str | None = None,
@@ -2222,6 +2347,7 @@ class RunsClient:
headers: Mapping[str, str] | None = None,
params: QueryParamTypes | None = None,
on_run_created: Callable[[RunCreateMetadata], None] | None = None,
durability: Durability | None = None,
) -> list[dict] | dict[str, Any]:
"""Create a run, wait until it finishes and return the final state.
@@ -2237,7 +2363,7 @@ class RunsClient:
context: Static context to add to the assistant.
!!! version-added "Supported with langgraph>=0.6.0"
checkpoint: The checkpoint to resume from.
checkpoint_during: Whether to checkpoint during the run (or only at the end/interruption).
checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
interrupt_before: Nodes to interrupt immediately before they get executed.
interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
webhook: Webhook to call after LangGraph API call is done.
@@ -2253,6 +2379,10 @@ class RunsClient:
Use to schedule future runs.
headers: Optional custom headers to include with the request.
on_run_created: Optional callback to call when a run is created.
durability: The durability to use for the run. Values are "sync", "async", or "exit".
"async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
"sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
"exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
Returns:
Union[list[dict], dict[str, Any]]: The output of the run.
@@ -2306,6 +2436,12 @@ class RunsClient:
```
""" # noqa: E501
if checkpoint_during is not None:
warnings.warn(
"`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
DeprecationWarning,
stacklevel=2,
)
payload = {
"input": input,
"command": (
@@ -2326,6 +2462,7 @@ class RunsClient:
"on_disconnect": on_disconnect,
"on_completion": on_completion,
"after_seconds": after_seconds,
"durability": durability,
}
endpoint = (
f"/threads/{thread_id}/runs/wait" if thread_id is not None else "/runs/wait"
@@ -4241,6 +4378,7 @@ class SyncThreadsClient:
if_exists: OnConflictBehavior | None = None,
supersteps: Sequence[dict[str, Sequence[dict[str, Any]]]] | None = None,
graph_id: str | None = None,
ttl: int | Mapping[str, Any] | None = None,
headers: Mapping[str, str] | None = None,
params: QueryParamTypes | None = None,
) -> Thread:
@@ -4255,6 +4393,9 @@ class SyncThreadsClient:
supersteps: Apply a list of supersteps when creating a thread, each containing a sequence of updates.
Each update has `values` or `command` and `as_node`. Used for copying a thread between deployments.
graph_id: Optional graph ID to associate with the thread.
ttl: Optional time-to-live in minutes for the thread. You can pass an
integer (minutes) or a mapping with keys `ttl` and optional
`strategy` (defaults to "delete").
headers: Optional custom headers to include with the request.
Returns:
@@ -4296,6 +4437,11 @@ class SyncThreadsClient:
}
for s in supersteps
]
if ttl is not None:
if isinstance(ttl, (int, float)):
payload["ttl"] = {"ttl": ttl, "strategy": "delete"}
else:
payload["ttl"] = ttl
return self.http.post("/threads", json=payload, headers=headers, params=params)
@@ -4304,6 +4450,7 @@ class SyncThreadsClient:
thread_id: str,
*,
metadata: Mapping[str, Any],
ttl: int | Mapping[str, Any] | None = None,
headers: Mapping[str, str] | None = None,
params: QueryParamTypes | None = None,
) -> Thread:
@@ -4312,7 +4459,11 @@ class SyncThreadsClient:
Args:
thread_id: ID of thread to update.
metadata: Metadata to merge with existing thread metadata.
ttl: Optional time-to-live in minutes for the thread. You can pass an
integer (minutes) or a mapping with keys `ttl` and optional
`strategy` (defaults to "delete").
headers: Optional custom headers to include with the request.
params: Optional query parameters to include with the request.
Returns:
Thread: The created thread.
@@ -4324,12 +4475,19 @@ class SyncThreadsClient:
thread = client.threads.update(
thread_id="my-thread-id",
metadata={"number":1},
ttl=43_200,
)
```
""" # noqa: E501
payload: dict[str, Any] = {"metadata": metadata}
if ttl is not None:
if isinstance(ttl, (int, float)):
payload["ttl"] = {"ttl": ttl, "strategy": "delete"}
else:
payload["ttl"] = ttl
return self.http.patch(
f"/threads/{thread_id}",
json={"metadata": metadata},
json=payload,
headers=headers,
params=params,
)
@@ -4367,6 +4525,7 @@ class SyncThreadsClient:
*,
metadata: Json = None,
values: Json = None,
ids: Sequence[str] | None = None,
status: ThreadStatus | None = None,
limit: int = 10,
offset: int = 0,
@@ -4381,6 +4540,7 @@ class SyncThreadsClient:
Args:
metadata: Thread metadata to filter on.
values: State values to filter on.
ids: List of thread IDs to filter by.
status: Thread status to filter on.
Must be one of 'idle', 'busy', 'interrupted' or 'error'.
limit: Limit on number of threads to return.
@@ -4410,6 +4570,8 @@ class SyncThreadsClient:
payload["metadata"] = metadata
if values:
payload["values"] = values
if ids:
payload["ids"] = ids
if status:
payload["status"] = status
if sort_by:
@@ -4733,6 +4895,54 @@ class SyncThreadsClient:
params=params,
)
def join_stream(
self,
thread_id: str,
*,
stream_mode: ThreadStreamMode | Sequence[ThreadStreamMode] = "run_modes",
last_event_id: str | None = None,
headers: Mapping[str, str] | None = None,
params: QueryParamTypes | None = None,
) -> Iterator[StreamPart]:
"""Get a stream of events for a thread.
Args:
thread_id: The ID of the thread to get the stream for.
last_event_id: The ID of the last event to get.
headers: Optional custom headers to include with the request.
params: Optional query parameters to include with the request.
Returns:
Iterator[StreamPart]: An iterator of stream parts.
???+ example "Example Usage"
```python
for chunk in client.threads.join_stream(
thread_id="my_thread_id",
last_event_id="my_event_id",
stream_mode="run_modes",
):
print(chunk)
```
""" # noqa: E501
query_params = {
"stream_mode": stream_mode,
}
if params:
query_params.update(params)
return self.http.stream(
f"/threads/{thread_id}/stream",
"GET",
headers={
**({"Last-Event-ID": last_event_id} if last_event_id else {}),
**(headers or {}),
},
params=query_params,
)
class SyncRunsClient:
"""Synchronous client for managing runs in LangGraph.
@@ -4823,7 +5033,7 @@ class SyncRunsClient:
context: Context | None = None,
checkpoint: Checkpoint | None = None,
checkpoint_id: str | None = None,
checkpoint_during: bool | None = None,
checkpoint_during: bool | None = None, # deprecated
interrupt_before: All | Sequence[str] | None = None,
interrupt_after: All | Sequence[str] | None = None,
feedback_keys: Sequence[str] | None = None,
@@ -4836,6 +5046,7 @@ class SyncRunsClient:
headers: Mapping[str, str] | None = None,
params: QueryParamTypes | None = None,
on_run_created: Callable[[RunCreateMetadata], None] | None = None,
durability: Durability | None = None,
) -> Iterator[StreamPart]:
"""Create a run and stream the results.
@@ -4855,7 +5066,7 @@ class SyncRunsClient:
context: Static context to add to the assistant.
!!! version-added "Supported with langgraph>=0.6.0"
checkpoint: The checkpoint to resume from.
checkpoint_during: Whether to checkpoint during the run (or only at the end/interruption).
checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
interrupt_before: Nodes to interrupt immediately before they get executed.
interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
feedback_keys: Feedback keys to assign to run.
@@ -4872,6 +5083,11 @@ class SyncRunsClient:
Use to schedule future runs.
headers: Optional custom headers to include with the request.
on_run_created: Optional callback to call when a run is created.
durability: The durability to use for the run. Values are "sync", "async", or "exit".
"async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
"sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
"exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
Returns:
Iterator[StreamPart]: Iterator of stream results.
@@ -4904,6 +5120,12 @@ class SyncRunsClient:
StreamPart(event='end', data=None)
```
""" # noqa: E501
if checkpoint_during is not None:
warnings.warn(
"`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
DeprecationWarning,
stacklevel=2,
)
payload = {
"input": input,
"command": (
@@ -4928,6 +5150,7 @@ class SyncRunsClient:
"on_disconnect": on_disconnect,
"on_completion": on_completion,
"after_seconds": after_seconds,
"durability": durability,
}
endpoint = (
f"/threads/{thread_id}/runs/stream"
@@ -5018,7 +5241,7 @@ class SyncRunsClient:
context: Context | None = None,
checkpoint: Checkpoint | None = None,
checkpoint_id: str | None = None,
checkpoint_during: bool | None = None,
checkpoint_during: bool | None = None, # deprecated
interrupt_before: All | Sequence[str] | None = None,
interrupt_after: All | Sequence[str] | None = None,
webhook: str | None = None,
@@ -5029,6 +5252,7 @@ class SyncRunsClient:
headers: Mapping[str, str] | None = None,
params: QueryParamTypes | None = None,
on_run_created: Callable[[RunCreateMetadata], None] | None = None,
durability: Durability | None = None,
) -> Run:
"""Create a background run.
@@ -5048,7 +5272,7 @@ class SyncRunsClient:
context: Static context to add to the assistant.
!!! version-added "Supported with langgraph>=0.6.0"
checkpoint: The checkpoint to resume from.
checkpoint_during: Whether to checkpoint during the run (or only at the end/interruption).
checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
interrupt_before: Nodes to interrupt immediately before they get executed.
interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
webhook: Webhook to call after LangGraph API call is done.
@@ -5062,6 +5286,10 @@ class SyncRunsClient:
Use to schedule future runs.
headers: Optional custom headers to include with the request.
on_run_created: Optional callback to call when a run is created.
durability: The durability to use for the run. Values are "sync", "async", or "exit".
"async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
"sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
"exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
Returns:
Run: The created background run.
@@ -5137,6 +5365,12 @@ class SyncRunsClient:
}
```
""" # noqa: E501
if checkpoint_during is not None:
warnings.warn(
"`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
DeprecationWarning,
stacklevel=2,
)
payload = {
"input": input,
"command": (
@@ -5159,6 +5393,7 @@ class SyncRunsClient:
"if_not_exists": if_not_exists,
"on_completion": on_completion,
"after_seconds": after_seconds,
"durability": durability,
}
payload = {k: v for k, v in payload.items() if v is not None}
@@ -5254,7 +5489,7 @@ class SyncRunsClient:
metadata: Mapping[str, Any] | None = None,
config: Config | None = None,
context: Context | None = None,
checkpoint_during: bool | None = None,
checkpoint_during: bool | None = None, # deprecated
checkpoint: Checkpoint | None = None,
checkpoint_id: str | None = None,
interrupt_before: All | Sequence[str] | None = None,
@@ -5269,6 +5504,7 @@ class SyncRunsClient:
headers: Mapping[str, str] | None = None,
params: QueryParamTypes | None = None,
on_run_created: Callable[[RunCreateMetadata], None] | None = None,
durability: Durability | None = None,
) -> list[dict] | dict[str, Any]:
"""Create a run, wait until it finishes and return the final state.
@@ -5284,7 +5520,7 @@ class SyncRunsClient:
context: Static context to add to the assistant.
!!! version-added "Supported with langgraph>=0.6.0"
checkpoint: The checkpoint to resume from.
checkpoint_during: Whether to checkpoint during the run (or only at the end/interruption).
checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
interrupt_before: Nodes to interrupt immediately before they get executed.
interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
webhook: Webhook to call after LangGraph API call is done.
@@ -5301,6 +5537,10 @@ class SyncRunsClient:
raise_error: Whether to raise an error if the run fails.
headers: Optional custom headers to include with the request.
on_run_created: Optional callback to call when a run is created.
durability: The durability to use for the run. Values are "sync", "async", or "exit".
"async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
"sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
"exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
Returns:
Union[list[dict], dict[str, Any]]: The output of the run.
@@ -5355,6 +5595,12 @@ class SyncRunsClient:
```
""" # noqa: E501
if checkpoint_during is not None:
warnings.warn(
"`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
DeprecationWarning,
stacklevel=2,
)
payload = {
"input": input,
"command": (
@@ -5376,6 +5622,7 @@ class SyncRunsClient:
"on_completion": on_completion,
"after_seconds": after_seconds,
"raise_error": raise_error,
"durability": durability,
}
def on_response(res: httpx.Response):
+14
View File
@@ -38,6 +38,14 @@ Represents the status of a thread:
- "error": An exception occurred during task processing.
"""
ThreadStreamMode = Literal["run_modes", "lifecycle", "state_update"]
"""
Defines the mode of streaming:
- "run_modes": Stream the same events as the runs on thread, as well as run_done events.
- "lifecycle": Stream only run start/end events.
- "state_update": Stream state updates on the thread.
"""
StreamMode = Literal[
"values",
"messages",
@@ -91,6 +99,12 @@ Defines action after completion:
- "keep": Retain resources after completion.
"""
Durability = Literal["sync", "async", "exit"]
"""Durability mode for the graph execution.
- `"sync"`: Changes are persisted synchronously before the next step starts.
- `"async"`: Changes are persisted asynchronously while the next step executes.
- `"exit"`: Changes are persisted only when the graph exits."""
All = Literal["*"]
"""Represents a wildcard or 'all' selector."""