Reference¶
OpenAI-Compatible API¶
Default prefix: /v1. Change it with LGOS_OPENAI_API_PREFIX or
bind_openai_api(prefix=...). Generic access logs are emitted by the
deployment's ASGI server or ingress proxy.
| Method | Path | Purpose |
|---|---|---|
GET |
/v1/models |
List registered graph models with LGOS descriptions and features. |
GET |
/v1/models/{model} |
Retrieve one model with the required LGOS metadata extension. |
POST |
/v1/responses |
Run a graph through the stateless OpenAI Responses subset. |
POST |
/v1/chat/completions |
Run a graph through OpenAI chat completions. |
GET |
/v1/health |
Health check. |
FastAPI docs for the mounted OpenAI app are disabled by default. Set
LGOS_OPENAI_API_DOCS_ENABLED=true to expose {prefix}/docs, {prefix}/redoc,
and {prefix}/openapi.json.
Responses Request¶
The route accepts string or ordered message input, instructions, plain
input_text, input_file.file_id, string-valued metadata, user, flat client
function tools, registered name-only custom-tool selectors, standard
web_search, their choices,
parallel_tool_calls, plain text output, and streaming. Replayed
assistant output messages preserve phase; complete
function_call items and matching string-valued function_call_output items
support ordinary client-tool continuation. Interrupt continuation sends only
matching function_call_output items with previous_response_id.
Server execution returns native custom_tool_call and
custom_tool_call_output pairs or a
web_search_call in the same response; complete output items can also be
replayed as history.
LGOS executes registered custom tools inside that response. This intentionally
differs from OpenAI's ordinary custom-tool flow, where caller code executes the
tool and supplies its output to a later model request; the wire items remain
standard Responses types.
The public web_search shape does not prescribe the graph's search backend;
the bundled demo chooses an HTTP or upstream provider backend.
LGOS does not persist completed Responses for retrieve or deletion. Omitted,
null, and false store values are accepted, and the returned Response reports
store=false; store=true, conversation, and background mode are rejected.
previous_response_id is supported for interruptible graphs to resume execution
(and rejected for non-interruptible graphs); new instructions are rejected on
those resumes. The route also rejects unregistered custom tools, client-supplied
custom descriptions or formats, other built-in tools,
structured output, image/audio input, URL or inline file input, function
result-content lists, reasoning and generation controls, include, stream options,
service tiers, reusable prompts,
prompt-cache controls, and truncation. Unknown fields are not silently ignored.
See the supported Responses subset
for the complete behavior and continuation rules.
Chat Completions Request¶
Chat messages accept string content, explicit text content parts, and native
file parts containing only file.file_id. The route supports modern function
tools, tool_choice, assistant tool_calls, matching tool messages,
streaming, and stream_options.include_usage. Image and audio parts, inline
file data or filenames, prompt-cache fields, deprecated function fields,
generation controls, and other unknown fields are rejected.
Settings¶
Package settings:
| Setting | Default | Notes |
|---|---|---|
LGOS_OPENAI_API_PREFIX |
/v1 |
Must start with /; trailing slash is normalized. |
LGOS_OPENAI_API_DOCS_ENABLED |
false |
Enables docs only for the mounted OpenAI app. |
LGOS_ENABLE_LANGFUSE |
false |
Lazily adds the package Langfuse callback to every graph run. |
Settings prefixed with DEMO_ belong to the independent example applications
and are documented under Demo Settings and Commands.
Public API¶
Use LanggraphOpenaiServe to bind OpenAI-compatible routes to a FastAPI app.
After binding, server.openai_app exposes the mounted FastAPI application for
host integrations such as manual middleware or telemetry instrumentation.
Use GraphRegistry to map OpenAI model names to GraphConfig values.
The registry copies its initial mapping and must contain at least one graph. It
rejects empty model IDs, ., .., and IDs containing /. The public
registry.registry mapping is an insertion-ordered, read-only view; use
registry.register(model_id, config) to add or replace a graph. Replacing an
existing ID preserves its position.
LanggraphOpenaiServe(..., checkpoint_scope=resolver) accepts an optional sync
or async callable from FastAPI Request to a non-empty, server-trusted string.
Interrupt checkpoint keys include this scope before model and run identity. Use
an authenticated tenant or principal identifier when caller-chosen run UUIDs
must be isolated between security domains; do not derive the scope from
untrusted OpenAI metadata or the OpenAI user field. The
default "default" scope is suitable only for a single-tenant or shared-trust
deployment. The resolver must return the same scope for the initial request and
its resume; changing tenant identity makes the other scope's checkpoint
deliberately unreachable.
Responses input_file.file_id content and native Chat file parts normalize to
the same LangChain file block, so graphs receive native file_id values and
decide whether to download, parse, or forward them. File upload and storage
belong to an external OpenAI Files API, not the LGOS package. See
Accept And Display Files.
GraphConfig accepts:
graph: compiled graph, sync factory, or async factory.description: required human-readable model description advertised by model listing and retrieval.features:GraphFeaturevalues that enable optional server behavior or advertise graph input and client-tool capabilities.client_settings: explicit publicClientSettingsmodel class advertised by model retrieval.server_tools: internal allowlist of server-executed tool names. A registered custom tool is selected with the Responsescustomtype and name;web_searchuses its built-in type. The graph owns tool definitions and execution. Model retrieval does not advertise tools. See Server Tools.runtime_callbacks: callbacks included in the LangGraphRunnableConfig. When Langfuse tracing is enabled, LGOS adds its callback without mutating this collection or manager.run_coordinator: asynchronous single-flight coordination for interrupt runs. It rejects an occupied LGOS checkpoint key instead of queueing it and returns an async context manager.request_to_input(request, messages): custom normalized request and LangChain messages to graph input.context_factory(request, client_settings): compose the final typed LangGraph runtime context from normalized request values, server-owned values, and optional validated public settings.output_to_message(output): custom graph output to a durableAIMessage.
GraphConfig is immutable after construction. Pydantic snapshots features
and server_tools as frozen sets, so later mutations of the input collections
cannot change a registered model. To change a declaration, construct a
replacement and pass it to registry.register(). Freezing the declaration does
not make a caller-owned callback handler or callback manager internally
immutable.
Streaming forwards non-empty text from every AIMessageChunk emitted by the
graph's messages stream. Configure private ChatOpenAI calls with
disable_streaming=True;
LangChain then uses the complete invocation path and does not emit model stream
chunks for that call.
A directly supplied compiled graph is reused. A sync or async graph factory is
called for every request and is never cached; LGOS validates each resolved value
as a compiled state graph and rechecks its context schema and interrupt
checkpointer capabilities before execution. Static configuration relationships,
including the requirement that run_coordinator appear exactly when
GraphFeature.INTERRUPTS is enabled, fail during GraphConfig construction.
When both are configured, LGOS validates the public settings first and passes
them to context_factory. Without a factory, the validated settings instance is
the runtime context, so the graph must use that settings model as its
context_schema. A factory may return None; every non-null result requires a
graph context schema. LGOS passes server-owned factory results to LangGraph
without rebuilding them. LangGraph's native
runtime-context handling
constructs mapping values through dataclass and Pydantic context schemas and
trusts existing instances. The factory owns the validity of instances it
creates. Graphs should access context from an injected Runtime[Context].
Graph adapters receive an immutable, protocol-neutral GraphRequest from either
API's decoder. It exposes
the shared model, metadata, user, normalized client function tools,
selected server-tool names in server_tools, tool_choice, and parallel_tool_calls
values. NamedFunctionToolChoice identifies a required client function, while
NamedCustomToolChoice identifies a required registered custom tool. A
single web_search declaration with tool_choice="required" requires search.
Named built-in choices are outside the supported subset.
Raw OpenAI transport models are
not part of the graph-adapter interface.
Runtime context is separate from RunnableConfig:
| Value | LGOS/LangGraph path | Intended use |
|---|---|---|
| Graph input | graph.ainvoke(input, ...) or graph.astream(input, ...) |
Messages and mutable workflow state. |
| Runtime context | public settings → optional context_factory → context= → Runtime.context |
Immutable per-run application values and dependencies. |
| Runnable config | config= |
Callbacks, tags, tracing, and other execution controls. |
| Interrupt run | server scope + model + optional metadata.lgos_run_id UUID → internal checkpoint key |
Isolate, retry, interrupt, and resume one operation. |
LGOS assembles runnable config from runtime_callbacks and, for an
interrupt-enabled run, a fixed-length SHA-256 checkpoint key derived from the
server-trusted scope, registered model, and operation UUID. This is deliberately
not a UI chat or thread ID. There is intentionally no adapter for placing
arbitrary OpenAI request fields into config["configurable"]; use typed runtime
context for values consumed by nodes.
Langfuse Tracing¶
Langfuse is a first-class optional integration. Install it and enable the default callback through process environment settings:
uv add "langgraph-openai-serve[tracing]"
export LGOS_ENABLE_LANGFUSE=true
export LANGFUSE_PUBLIC_KEY=pk-lf-...
export LANGFUSE_SECRET_KEY=sk-lf-...
LANGFUSE_BASE_URL is optional; Langfuse Cloud is the default. Set it only for
a different cloud region or a self-hosted instance. Langfuse's
CallbackHandler owns its standard SDK configuration and error behavior. LGOS
constructs it on the first graph run that needs runnable configuration, then
reuses that process-wide handler. When enabled, the deployment-level toggle is
authoritative: LGOS adds Langfuse alongside empty, list, or manager callbacks
without altering the registered GraphConfig or caller-owned collection. To
provide a custom Langfuse handler, leave the toggle off and pass that handler
through runtime_callbacks.
For explicit construction, import
langgraph_openai_serve.integrations.langfuse.get_langfuse_callback or pass an
application-created vendor handler through runtime_callbacks.
When a callback is present, LGOS gives the graph run the stable name
lgos.graph_run for both endpoints and adds RunnableConfig.metadata fields for the
request ID, registered graph model, (for interrupt runs) operation ID, and (when
the request supplies metadata.conversation_id) the Langfuse-recognized
langfuse_session_id. LangGraph also propagates primitive configurable values
during execution, so callbacks on interrupt runs receive the derived checkpoint
thread_id. LGOS does not set LangChain's native tracer run_id or force a
custom Langfuse trace ID. See Production Logging and Request
Correlation.
The features set is returned in the versioned lgos.features extension and
enables server behavior where applicable. GraphFeature.CLIENT_EVENTS enables
and advertises public
status commentary in streaming Responses. Chat Completions ignores custom
stream events and does not emit commentary.
GraphFeature.MCP_TOOLS advertises that a client may attach and execute tools
from its configured MCP gateway; it does not publish tool definitions or grant
access to them.
GraphFeature.FILE_INPUTS advertises that the graph
resolves native file content parts. GraphFeature.INTERRUPTS enables and
advertises the interrupt/resume flow.
Runtime Settings¶
Subclass ClientSettings to publish only fields deliberately selected by the
server author. LGOS never inspects or publishes the LangGraph context schema:
from pydantic import Field
from langgraph_openai_serve import ClientSettings
class PublicSettings(ClientSettings):
use_history: bool = Field(default=True, title="Use conversation history")
Pass this model as GraphConfig.client_settings and use it as the graph's context
schema when it is the complete runtime context. Every public field must have a
default. Registration rejects subclasses that change the inherited strict,
frozen, extra-forbid, or default-validation behavior, as well as fields excluded
from Pydantic serialization.
All public fields travel together as compact JSON text in the
metadata.lgos_settings string. Clients omit values equal to the advertised
defaults. System instructions remain ordinary OpenAI messages and are
independent of ClientSettings; native OpenAI fields keep their standard
request semantics.
LGOS validates defaults and generates the discovery JSON Schema when the graph
is registered, then validates settings on every request. Without
context_factory, the settings become Runtime.context. A factory can instead
combine them with server-derived identity, authorization, database clients, and
other dependencies.
The serialized descriptor appears only on model retrieval as
lgos.client_settings, with independent schema_version,
json_schema, and defaults fields. All client settings use the fixed
metadata.lgos_settings key. Clients use the descriptor's
validated defaults object as the baseline; default keywords within the
generated JSON Schema are annotations, not the runtime baseline. The schema's
$schema keyword declares the JSON Schema 2020-12 dialect independently of the
LGOS descriptor version.
See Configure LangGraph Runtime Settings for the runtime settings flow, and Runtime Settings for the request lifecycle.
Interrupt-enabled graphs have additional registration requirements:
- compile the graph with an asynchronous checkpointer that supports
aget_tuple(),alist(),aput(),aput_writes(), andadelete_thread(); - configure an asynchronous
run_coordinator; and - use a durable checkpointer and cross-process coordinator in production.
The initial request does not require metadata. LGOS generates a UUID operation
ID and embeds it in the paused Response ID. A caller that needs deterministic
initial-request retries can instead supply a non-nil UUID in
metadata.lgos_run_id. InMemoryRunCoordinator is suitable only for
tests and a single-process development server; it cannot serialize requests
across workers or hosts.
Pending checkpoints exist only to resume an interrupt batch returned to the client. LGOS deletes isolated checkpoint state after terminal completion or when execution fails or is cancelled before producing that batch. Operators must separately define an expiry policy for runs abandoned after a batch is returned.
PostgreSQL Coordination¶
Install langgraph-openai-serve[postgres] to use the public
langgraph_openai_serve.integrations.postgres.PostgresRunCoordinator. Use
LangGraph's official
AsyncPostgresSaver
for checkpoints and
AsyncPostgresStore
for application data. The LGOS adapter supplies only the cross-worker
interrupt-run lease; it does not replace either storage primitive. Run each
configured storage adapter's setup() once before API workers start. A shared
pool must follow the upstream connection requirements: autocommit=True,
prepare_threshold=0, and mapping rows.
PostgresRunCoordinator(pool, max_concurrent_leases=...) accepts an existing
psycopg_pool.AsyncConnectionPool configured with mapping rows and the default
close_returns=False; physical session closure is the safety fallback for an
indeterminate lock operation. When persistence adapters share that pool, set
the lease limit below the pool maximum so at least one connection remains
available for persistence I/O. Create one coordinator per process-owned pool
so that this capacity limit is not accidentally multiplied. Session advisory
locks require direct PostgreSQL connections or session-mode pooling;
transaction-mode poolers cannot preserve the lease. Lock contention itself
fails immediately through PostgreSQL's pg_try_advisory_lock; connection
checkout still follows the pool's configured timeout. The
demo deployment uses one pool for both
storage adapters and interrupt coordination, plus a separate one-shot schema
setup process. Busy interrupt leases fail before streaming begins with HTTP 409
and code: "run_busy".
Streaming Status¶
Declare the feature on every graph that publishes client events:
from langgraph_openai_serve import GraphConfig, GraphFeature
config = GraphConfig(
graph=graph,
description="Graph that reports media-generation status.",
features={GraphFeature.CLIENT_EVENTS},
)
Inside a long-running graph node or tool, publish user-facing status with
status_event():
from langgraph.config import get_stream_writer
from langgraph_openai_serve import status_event
writer = get_stream_writer()
writer(status_event("Generating audio", namespace=("media",)))
# Perform the long-running work.
writer(
status_event(
"Audio ready",
done=True,
namespace=("media",),
)
)
The helper writes this versioned graph-to-LGOS envelope:
{
"type": "lgos.client_event",
"schema_version": 1,
"event": {
"type": "status",
"namespace": ["media"],
"data": {
"description": "Generating audio",
"done": false,
"hidden": false
}
}
}
Status text is deliberately authored by the graph; LGOS does not infer it from
internal node names or state. Responses exposes the description as commentary
and suppresses hidden updates; the namespace, done, and hidden fields do not
become nonstandard Response fields.
The event envelope has its own schema version, independent of model discovery
and client settings. The v1 event vocabulary is status, progress, and
artifact.
client_event("status", data) remains the lower-level equivalent when an
application already has validated status data; prefer status_event() for its
typed fields. Event data must be JSON-safe, and every namespace segment must be a
string. The namespace is a stable, author-defined path; LGOS does not expose
LangGraph's dynamic execution namespace.
Status is streaming-only and always requires the graph feature. Responses needs
no metadata opt-in and emits each visible update as a standard
phase="commentary" message. The Chat Completions API is strictly for simple
graphs and plain text streaming; it ignores custom stream events and does not emit
commentary. Responses ignores progress and artifact. Use standard Responses
function calls plus the Files API for portable durable rich output. Unknown custom
events remain available only to direct runner consumers.
See Streaming status for the wire contract and Stream final text and commentary for consumption.
Citations¶
Put citations on the final LangChain AIMessage:
from langchain_core.messages import AIMessage
from langchain_core.messages.content import create_citation, create_text_block
message = AIMessage(
content=[
create_text_block(
text="Read the source [1].",
annotations=[
create_citation(
url="https://example.com/source",
title="Example source",
start_index=9,
end_index=14,
cited_text="source",
)
],
)
]
)
Put visible inline citations in the assistant text. Structured annotations add machine-readable provenance; clients are not required to invent marker text from annotation indices.
LangChain citation indices refer to their containing text block. LGOS offsets
them into the final response text and preserves OpenAI's inclusive end_index.
Use citation_slice(start_index, end_index, text) to validate them and create a
Python slice. Responses maps citations to output_text.annotations and emits
the typed annotation event while streaming. Chat maps them to completed
message.annotations; its final streaming delta uses the compatibility
extension.
See Citation ownership for transport and client behavior.
The streaming graph runner preserves LangGraph's native CustomStreamPart
values, including their execution namespace. Non-streaming invocation does not
subscribe to or replay custom events.
langgraph-openai-serve package.
ClientFunctionTool
dataclass
¶
A client-supplied function available to the graph.
ClientSettings ¶
Bases: BaseModel
Base class for settings that clients may configure for a graph.
Subclasses define the complete public contract. Every field must have a valid JSON-serializable default so model discovery can advertise a usable settings object without maintaining a second defaults mapping.
defaults
classmethod
¶
Return a deep copy of the registration-validated defaults.
validate_request
classmethod
¶
Read and validate this model's values from an OpenAI request.
Source code in src/langgraph_openai_serve/graph/client_settings.py
GraphConfig ¶
Bases: BaseModel
Graph configuration.
build_context
async
¶
Build the LangGraph runtime context for a request.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
build_input
async
¶
Build the native graph input for a normalized request.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
render_output
async
¶
Convert native graph output into the durable assistant message.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
resolve_graph
async
¶
Get the graph instance, resolving callable graph factories.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
supports ¶
validate_client_settings
classmethod
¶
Validate a public settings model when its graph is registered.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
validate_interrupt_configuration ¶
Validate feature relationships that do not depend on a resolved graph.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
GraphFeature ¶
Bases: StrEnum
Features supported by a registered graph.
GraphRegistry ¶
Registry of graphs.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
get_graph ¶
Get a graph by its name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the graph to retrieve. |
required |
Returns:
| Type | Description |
|---|---|
GraphConfig
|
The graph configuration associated with the given name. |
Raises:
| Type | Description |
|---|---|
GraphNotFoundError
|
If the graph name is not found in the registry. |
Source code in src/langgraph_openai_serve/graph/graph_registry.py
get_graph_names ¶
register ¶
Add or replace one graph through the validated registry boundary.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
GraphRequest
dataclass
¶
Request data shared by protocol decoders and graph execution.
LanggraphOpenaiServe ¶
Server class to connect LangGraph instances with an OpenAI-compatible API.
This class serves as a bridge between LangGraph instances and an OpenAI-compatible API. It allows users to register their LangGraph instances and expose them through an OpenAI-compatible sub-application mounted on a FastAPI host app.
Attributes:
| Name | Type | Description |
|---|---|---|
app |
FastAPI
|
The host FastAPI application to mount the OpenAI API on. |
graph_registry |
The populated GraphRegistry containing the graphs to serve. |
|
openai_app |
FastAPI
|
The mounted OpenAI-compatible FastAPI application. |
Initialize the server with a FastAPI app and a populated graph registry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app
|
FastAPI | None
|
The host FastAPI application to mount the OpenAI API on. If None, a new FastAPI app will be created. |
None
|
graphs
|
GraphRegistry
|
A GraphRegistry instance containing the graphs to serve. |
required |
checkpoint_scope
|
Callable[[Request], str | Awaitable[str]] | None
|
Optional server-trusted resolver used to isolate interrupt checkpoints by deployment or authenticated principal. |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If graphs is not a GraphRegistry instance. |
Source code in src/langgraph_openai_serve/openai_server.py
bind_openai_api ¶
Mount OpenAI-compatible endpoints on the host FastAPI app.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str | None
|
Optional; The URL prefix for the OpenAI-compatible endpoints. Defaults to settings.OPENAI_API_PREFIX. |
None
|
Source code in src/langgraph_openai_serve/openai_server.py
citation_slice ¶
Convert an inclusive citation span to a validated Python slice.
Source code in src/langgraph_openai_serve/graph/citations.py
client_event ¶
Build an explicitly public, JSON-safe client stream event.
Source code in src/langgraph_openai_serve/graph/events.py
status_event ¶
Build a portable status update for native client UI.
Source code in src/langgraph_openai_serve/graph/events.py
api ¶
chat ¶
messages ¶
Convert Chat Completions messages into LangChain messages.
InvalidChatMessageError ¶
Bases: ValueError
Raised when a chat message is missing a role-specific required field.
convert_to_lc_messages ¶
Convert OpenAI messages to LangChain messages.
This function converts a list of OpenAI-compatible message objects to their LangChain equivalents for use with LangGraph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
list[ChatCompletionRequestMessage]
|
A list of OpenAI chat completion request messages to convert. |
required |
Returns:
| Type | Description |
|---|---|
list[BaseMessage]
|
A list of LangChain message objects. |
Source code in src/langgraph_openai_serve/api/chat/messages.py
request ¶
Decode Chat Completions requests for protocol-neutral graph execution.
UnsupportedChatRequestError ¶
decode_chat_request ¶
Normalize one Chat Completions request for graph execution.
Source code in src/langgraph_openai_serve/api/chat/request.py
responses ¶
OpenAI chat response builders.
ChatCompletionStreamResponseBuilder ¶
Build OpenAI-compatible chat completion SSE chunks.
Source code in src/langgraph_openai_serve/api/chat/responses.py
done
staticmethod
¶
error ¶
finish ¶
Stream finish.
Source code in src/langgraph_openai_serve/api/chat/responses.py
role ¶
text ¶
tool_calls ¶
Stream complete final-message tool calls as one delta.
Source code in src/langgraph_openai_serve/api/chat/responses.py
usage ¶
Stream the optional final usage-only chunk.
Source code in src/langgraph_openai_serve/api/chat/responses.py
annotations_from_message ¶
Convert validated LangChain citations to Chat URL annotations.
Source code in src/langgraph_openai_serve/api/chat/responses.py
chat_completion_response ¶
Build a non-streaming OpenAI-compatible chat completion response.
Source code in src/langgraph_openai_serve/api/chat/responses.py
response_message ¶
Format response message.
Source code in src/langgraph_openai_serve/api/chat/responses.py
tool_calls_from_message ¶
Convert native LangChain tool calls to Chat Completions tool calls.
Source code in src/langgraph_openai_serve/api/chat/responses.py
usage_info ¶
Map LangChain's provider-reported usage to Chat Completions usage.
Source code in src/langgraph_openai_serve/api/chat/responses.py
schemas ¶
Request models for the supported Chat Completions subset.
ChatCompletionFileContentPart ¶
Bases: _ChatRequestModel
One native Chat Completions file-ID content part.
ChatCompletionFileReference ¶
Bases: _ChatRequestModel
One uploaded file selected by its opaque Files API ID.
ChatCompletionRequest ¶
Bases: _ChatRequestModel
Model for a chat completion request.
validate_stream_options ¶
Allow stream options only for streaming requests.
Source code in src/langgraph_openai_serve/api/chat/schemas.py
ChatCompletionRequestMessage ¶
Bases: _ChatRequestModel
Model for a chat completion request message.
ChatCompletionStreamOptions ¶
Bases: _ChatRequestModel
Options that affect Chat Completions streaming.
ChatCompletionTextContentPart ¶
Bases: _ChatRequestModel
One text part in a Chat Completions message.
FunctionDefinition ¶
Bases: _ChatRequestModel
Model for a function definition.
NamedToolChoice ¶
Bases: _ChatRequestModel
Named function tool choice accepted by Chat Completions.
NamedToolChoiceFunction ¶
Bases: _ChatRequestModel
Function selected by a named Chat Completions tool choice.
Role ¶
Bases: StrEnum
Role options for chat messages.
Tool ¶
Bases: _ChatRequestModel
Model for a tool.
ToolCall ¶
Bases: _ChatRequestModel
Model for a tool call.
ToolCallFunction ¶
Bases: _ChatRequestModel
Model for a tool call function.
service ¶
Prepare and execute graph runs for OpenAI Chat Completions.
generate_completion
async
¶
Generate a chat completion.
Source code in src/langgraph_openai_serve/api/chat/service.py
prepare_completion_run
async
¶
Validate a Chat request and prepare its graph run.
Source code in src/langgraph_openai_serve/api/chat/service.py
stream_completion
async
¶
Stream a chat completion response.
Yields:
| Type | Description |
|---|---|
AsyncGenerator[str, None]
|
String chunks representing Server-Sent Events. |
Source code in src/langgraph_openai_serve/api/chat/service.py
views ¶
OpenAI-compatible Chat Completions router.
create_chat_completion
async
¶
Create a chat completion.
This endpoint is compatible with OpenAI's chat completion API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chat_request
|
ChatCompletionRequest
|
The parsed chat completion request. |
required |
graph_registry
|
Annotated[GraphRegistry, Depends(get_graph_registry)]
|
The graph registry dependency. |
required |
stream_owner
|
Annotated[StreamOwner, Depends(get_stream_owner, scope=request)]
|
The request-scoped streaming task owner. |
required |
Returns:
| Type | Description |
|---|---|
StreamingResponse | ChatCompletion
|
A chat completion response, either as a complete response or as a stream. |
Source code in src/langgraph_openai_serve/api/chat/views.py
deps ¶
Dependencies shared by OpenAI-compatible API routes.
get_graph_registry ¶
get_stream_owner
async
¶
Manage the streaming producer owned by one request.
Yields:
| Type | Description |
|---|---|
AsyncIterator[StreamOwner]
|
The request-scoped stream owner. |
errors ¶
Translate shared graph failures at either OpenAI inference boundary.
graph_errors ¶
Map graph errors to OpenAI errors using the endpoint's input field.
Yields:
| Type | Description |
|---|---|
None
|
Control to request decoding, preparation, and non-streaming execution. |
Source code in src/langgraph_openai_serve/api/errors.py
metadata ¶
Validation constraints shared by OpenAI request metadata fields.
middleware ¶
Pure ASGI middleware for request correlation.
RequestContextMiddleware ¶
Attach a request ID and request context to the mounted LGOS app.
Source code in src/langgraph_openai_serve/api/middleware.py
__call__
async
¶
Handle HTTP requests and pass non-HTTP scopes through unchanged.
Source code in src/langgraph_openai_serve/api/middleware.py
models ¶
schemas ¶
LangGraphModelExtension ¶
LangGraphModelSummaryExtension ¶
Bases: BaseModel
Versioned LGOS fields safe to include in a model list.
Model ¶
Bases: BaseModel
Individual model information.
ModelClientSettings ¶
Bases: BaseModel
Versioned public runtime settings for one registered graph.
ModelList ¶
Bases: BaseModel
List of available models.
service ¶
Functions for building OpenAI model information.
get_model ¶
Get one registered graph as an OpenAI model with LGOS metadata.
Source code in src/langgraph_openai_serve/api/models/service.py
get_models ¶
Get a list of available models.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph_registry
|
GraphRegistry
|
The GraphRegistry containing registered graphs. |
required |
Returns:
| Type | Description |
|---|---|
ModelList
|
A list of models in OpenAI compatible format. |
Source code in src/langgraph_openai_serve/api/models/service.py
views ¶
Models router.
This module provides the FastAPI router for the models endpoint, implementing an OpenAI-compatible interface for model listing.
list_models ¶
Get a list of available models.
retrieve_model ¶
Retrieve one registered graph as an OpenAI model.
Source code in src/langgraph_openai_serve/api/models/views.py
responses ¶
OpenAI-compatible Responses API.
deps ¶
FastAPI dependencies local to the Responses route.
get_checkpoint_scope
async
¶
Resolve the server-trusted checkpoint scope for one request.
Source code in src/langgraph_openai_serve/api/responses/deps.py
events ¶
Build SDK-typed OpenAI Responses events and named SSE frames.
ResponsesEventBuilder ¶
Own stable state for one Responses event lifecycle.
Source code in src/langgraph_openai_serve/api/responses/events.py
commentary ¶
Emit one complete commentary message lifecycle.
Yields:
| Type | Description |
|---|---|
ResponseStreamEvent
|
Typed events for the message lifecycle. |
Source code in src/langgraph_openai_serve/api/responses/events.py
created ¶
Create the initial response event.
Source code in src/langgraph_openai_serve/api/responses/events.py
failure ¶
Emit the normative terminal failure sequence.
Yields:
| Type | Description |
|---|---|
ResponseStreamEvent
|
The error and failed Response events. |
Source code in src/langgraph_openai_serve/api/responses/events.py
final_delta ¶
Emit one final-answer delta, opening its item if needed.
Yields:
| Type | Description |
|---|---|
ResponseStreamEvent
|
Typed events that open or update the final message. |
Source code in src/langgraph_openai_serve/api/responses/events.py
finish ¶
Reconcile final text, finish its item, and complete the Response.
Yields:
| Type | Description |
|---|---|
ResponseStreamEvent
|
Typed terminal events for a successful Response. |
Source code in src/langgraph_openai_serve/api/responses/events.py
finish_interrupt ¶
Emit a durable interrupt batch and complete the Response.
Yields:
| Type | Description |
|---|---|
ResponseStreamEvent
|
Typed function-call and terminal events. |
Source code in src/langgraph_openai_serve/api/responses/events.py
in_progress ¶
Create the response in-progress event.
Source code in src/langgraph_openai_serve/api/responses/events.py
server_tools ¶
Expose selected tool activity from one root graph update.
Yields:
| Type | Description |
|---|---|
ResponseStreamEvent
|
Native application-tool item lifecycle events. |
Source code in src/langgraph_openai_serve/api/responses/events.py
encode_event ¶
Encode one Responses event using the official named SSE framing.
interrupts ¶
OpenAI Responses encoding for LangGraph interrupt continuations.
interrupt_response_id ¶
Create a unique Response ID that carries its interrupt run identity.
interrupt_tool_call_id ¶
Bind one interrupt to its Response and durable checkpoint generation.
Source code in src/langgraph_openai_serve/api/responses/interrupts.py
parse_responses_resume ¶
Parse the sole supported interrupt continuation form.
Source code in src/langgraph_openai_serve/api/responses/interrupts.py
messages ¶
Convert Responses message input into LangChain messages.
InvalidResponsesInputError ¶
Bases: ValueError
Raised when Responses input items cannot be replayed unambiguously.
convert_responses_input ¶
Normalize supported Responses text and message input.
Source code in src/langgraph_openai_serve/api/responses/messages.py
output ¶
Convert graph output into OpenAI Response models.
ResponseContext
dataclass
¶
Stable identity and request fields shared by one response lifecycle.
for_run
classmethod
¶
Build context, binding an interrupt response ID when run_id is present.
Source code in src/langgraph_openai_serve/api/responses/output.py
response ¶
Build one SDK-typed Response with the route's stable defaults.
Source code in src/langgraph_openai_serve/api/responses/output.py
UnsupportedResponsesOutputError ¶
Bases: RuntimeError
Raised when graph output cannot be serialized as supported Responses items.
interrupt_output_items ¶
Serialize one durable interrupt batch as function-call items.
Source code in src/langgraph_openai_serve/api/responses/output.py
response_function_call ¶
Serialize one LangChain client tool call.
Source code in src/langgraph_openai_serve/api/responses/output.py
response_function_calls ¶
Serialize and validate all client tool calls from an assistant message.
Source code in src/langgraph_openai_serve/api/responses/output.py
response_incomplete_details ¶
Keep the final provider's truncation or filtering outcome visible.
Source code in src/langgraph_openai_serve/api/responses/output.py
response_output_text ¶
Build final Responses text and validated native URL annotations.
Source code in src/langgraph_openai_serve/api/responses/output.py
response_refusals ¶
Read refusals through LangChain's normalized content boundary.
Source code in src/langgraph_openai_serve/api/responses/output.py
response_usage ¶
Map provider-reported LangChain usage to Responses token details.
Source code in src/langgraph_openai_serve/api/responses/output.py
request ¶
Decode Responses requests for protocol-neutral graph execution.
UnsupportedResponsesRequestError ¶
decode_responses_request ¶
Normalize one supported, stateless Responses request.
Source code in src/langgraph_openai_serve/api/responses/request.py
selected_server_tools ¶
Return the registered server tools selected for this response.
Source code in src/langgraph_openai_serve/api/responses/request.py
validate_tools ¶
Reject unknown server-tool selectors before execution or SSE starts.
Source code in src/langgraph_openai_serve/api/responses/request.py
schemas ¶
Validated request models for the supported Responses API subset.
ResponseCreateRequest ¶
Bases: _ResponsesRequestModel
The stateless Responses request accepted by LGOS.
ResponseCustomTool ¶
Bases: _ResponsesRequestModel
Select one registered server tool with the Responses custom-tool shape.
ResponseCustomToolCallInput ¶
Bases: _ResponsesRequestModel
A custom-tool call replayed from a previous Response.
ResponseCustomToolCallOutputInput ¶
Bases: _ResponsesRequestModel
A string result replayed for a preceding custom-tool call.
ResponseFunctionCallInput ¶
Bases: _ResponsesRequestModel
A function call replayed from a previous Response.
ResponseFunctionCallOutputInput ¶
Bases: _ResponsesRequestModel
Client output for a preceding function call.
ResponseFunctionTool ¶
Bases: _ResponsesRequestModel
A client-supplied function available to the graph.
ResponseInputFile ¶
Bases: _ResponsesRequestModel
One file stored in the configured OpenAI Files service.
ResponseInputMessage ¶
Bases: _ResponsesRequestModel
A standard OpenAI role message provided as input.
phase is accepted for every role and used only for assistant messages.
See https://developers.openai.com/api/reference/resources/responses.
ResponseInputText ¶
Bases: _ResponsesRequestModel
One plain-text input content part.
ResponseNamedToolChoice ¶
Bases: _ResponsesRequestModel
Require one named function or custom tool.
ResponseOutputMessageInput ¶
Bases: _ResponsesRequestModel
A terminal assistant output message replayed as input.
ResponseOutputTextInput ¶
Bases: _ResponsesRequestModel
Plain output text replayed from a previous assistant message.
ResponseRefusalInput ¶
Bases: _ResponsesRequestModel
A model refusal replayed from an assistant message.
ResponseTextConfig ¶
Bases: _ResponsesRequestModel
Plain-text response configuration.
ResponseTextFormat ¶
Bases: _ResponsesRequestModel
The supported plain-text output format.
ResponseURLCitationInput ¶
Bases: _ResponsesRequestModel
A URL citation replayed with assistant output text.
ResponseWebSearchActionInput ¶
Bases: _ResponsesRequestModel
The query action produced by LGOS's supported web-search tool.
ResponseWebSearchCallInput ¶
Bases: _ResponsesRequestModel
A web-search call replayed from a previous Response.
ResponseWebSearchTool ¶
Bases: _ResponsesRequestModel
Select the graph's OpenAI-compatible web-search capability.
server_tools ¶
Translate LGOS-executed tools into native Responses output items.
ServerToolTracker ¶
Correlate root-graph server-tool calls with their ToolMessages.
Source code in src/langgraph_openai_serve/api/responses/server_tools.py
client_function_calls ¶
Return final function calls that belong to the client.
Source code in src/langgraph_openai_serve/api/responses/server_tools.py
ensure_complete ¶
Reject a response whose selected call has no graph-produced result.
Source code in src/langgraph_openai_serve/api/responses/server_tools.py
items ¶
Yield public tool items represented by one root graph update.
Yields:
| Type | Description |
|---|---|
ServerToolItem
|
Selected calls and graph-produced results. |
Source code in src/langgraph_openai_serve/api/responses/server_tools.py
service ¶
Prepare and execute graph runs for OpenAI Responses.
collect_response
async
¶
Build one non-streaming Response from the graph's durable output.
Source code in src/langgraph_openai_serve/api/responses/service.py
prepare_response_run
async
¶
Validate a Responses request and prepare its graph run.
Source code in src/langgraph_openai_serve/api/responses/service.py
stream_response
async
¶
Stream one prepared graph run as a typed Responses lifecycle.
Yields:
| Type | Description |
|---|---|
AsyncGenerator[str, None]
|
Named, compact Responses SSE frames. |
Source code in src/langgraph_openai_serve/api/responses/service.py
views ¶
OpenAI-compatible Responses router.
create_response
async
¶
Create one stateless OpenAI Response, optionally as an SSE stream.
Source code in src/langgraph_openai_serve/api/responses/views.py
streaming ¶
Tie OpenAI stream production to a FastAPI request's lifetime.
Starlette owns response consumption, not the nested graph producer, so a client disconnect may otherwise leave graph and provider work running. Chat and Responses use this shared request owner with separate protocol generators.
AnyIO provides the backpressured channel and cleanup shield. The producer stays
an asyncio.Task so cancellation reaches LangGraph's asyncio-native teardown
once at the stream boundary.
StreamOwner ¶
Own the producer and resources for one streaming graph run.
Source code in src/langgraph_openai_serve/api/streaming.py
__aenter__
async
¶
__aexit__
async
¶
Close the producer and prepared run when the request scope exits.
Source code in src/langgraph_openai_serve/api/streaming.py
aclose
async
¶
Stop production and close the prepared run exactly once.
Source code in src/langgraph_openai_serve/api/streaming.py
start ¶
Start the producer and take fallback ownership of its prepared run.
Source code in src/langgraph_openai_serve/api/streaming.py
tools ¶
Shared function-call decoding for the OpenAI protocol adapters.
decode_function_call ¶
Parse once, preserving malformed arguments for the graph to handle.
Source code in src/langgraph_openai_serve/api/tools.py
core ¶
errors ¶
OpenAI-compatible error response helpers.
OpenAIHTTPException ¶
Bases: HTTPException
HTTP exception that carries OpenAI error object metadata.
Source code in src/langgraph_openai_serve/core/errors.py
configure_openai_error_handlers ¶
Install OpenAI-compatible JSON error handlers on a FastAPI app.
Source code in src/langgraph_openai_serve/core/errors.py
openai_error_payload ¶
Create OpenAI error payload.
Source code in src/langgraph_openai_serve/core/errors.py
openai_http_exception_handler
async
¶
Handle HTTP exceptions.
Source code in src/langgraph_openai_serve/core/errors.py
openai_request_validation_exception_handler
async
¶
Handle validation exceptions.
Source code in src/langgraph_openai_serve/core/errors.py
openai_unhandled_exception_handler
async
¶
Handle unhandled exceptions.
Source code in src/langgraph_openai_serve/core/errors.py
logging ¶
Request-scoped context for standard-library log records.
RequestContextFilter ¶
Bases: Filter
Add active LGOS request fields to records emitted by LGOS loggers.
Source code in src/langgraph_openai_serve/core/logging.py
filter ¶
Enrich a record while preserving fields supplied by the caller.
Source code in src/langgraph_openai_serve/core/logging.py
begin_log_context ¶
Start a request context and return a token for restoring its parent.
bind_log_context ¶
Add fields to the active request context without mutating it.
Source code in src/langgraph_openai_serve/core/logging.py
exception_type_name ¶
Return the canonical OpenTelemetry error type for an exception.
Source code in src/langgraph_openai_serve/core/logging.py
get_log_context ¶
get_logger ¶
Return a normal logger with the LGOS context filter installed once.
Source code in src/langgraph_openai_serve/core/logging.py
reset_log_context ¶
settings ¶
Settings ¶
Bases: BaseSettings
Package settings read from explicit values and the process environment.
check_langfuse_settings
classmethod
¶
Validate Langfuse settings if enabled.
Source code in src/langgraph_openai_serve/core/settings.py
validate_openai_api_prefix
classmethod
¶
Validate the mount prefix for OpenAI-compatible endpoints.
normalize_openai_api_prefix ¶
Normalize and validate the OpenAI-compatible API mount prefix.
Source code in src/langgraph_openai_serve/core/settings.py
graph ¶
Service package for the LangGraph OpenAI compatible API.
citations ¶
Validate native LangChain citations independently of the HTTP protocol.
citation_slice ¶
Convert an inclusive citation span to a validated Python slice.
Source code in src/langgraph_openai_serve/graph/citations.py
citations_from_message ¶
Extract URL citations with validated offsets into the complete text.
Source code in src/langgraph_openai_serve/graph/citations.py
client_settings ¶
Public graph settings transported through standard OpenAI requests.
ClientSettings ¶
Bases: BaseModel
Base class for settings that clients may configure for a graph.
Subclasses define the complete public contract. Every field must have a valid JSON-serializable default so model discovery can advertise a usable settings object without maintaining a second defaults mapping.
defaults
classmethod
¶
Return a deep copy of the registration-validated defaults.
validate_request
classmethod
¶
Read and validate this model's values from an OpenAI request.
Source code in src/langgraph_openai_serve/graph/client_settings.py
ClientSettingsValidationError ¶
client_settings_default_values ¶
Return a fresh copy of the registration-validated JSON defaults.
Source code in src/langgraph_openai_serve/graph/client_settings.py
client_settings_json_schema ¶
Return a fresh copy of the registration-validated discovery schema.
Source code in src/langgraph_openai_serve/graph/client_settings.py
validate_client_settings_model ¶
Validate the registration-time contract of a settings model.
Source code in src/langgraph_openai_serve/graph/client_settings.py
events ¶
Public events emitted by LangGraph nodes and tools.
StatusEventData ¶
Bases: BaseModel
Validated graph status used to render Responses commentary.
client_event ¶
Build an explicitly public, JSON-safe client stream event.
Source code in src/langgraph_openai_serve/graph/events.py
parse_status_event ¶
Read a public graph status, ignoring private or diagnostic custom data.
Source code in src/langgraph_openai_serve/graph/events.py
status_event ¶
Build a portable status update for native client UI.
Source code in src/langgraph_openai_serve/graph/events.py
graph_registry ¶
GraphConfig ¶
Bases: BaseModel
Graph configuration.
build_context
async
¶
Build the LangGraph runtime context for a request.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
build_input
async
¶
Build the native graph input for a normalized request.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
render_output
async
¶
Convert native graph output into the durable assistant message.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
resolve_graph
async
¶
Get the graph instance, resolving callable graph factories.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
supports ¶
validate_client_settings
classmethod
¶
Validate a public settings model when its graph is registered.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
validate_interrupt_configuration ¶
Validate feature relationships that do not depend on a resolved graph.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
GraphConfigurationError ¶
Bases: RuntimeError
Raised when a registered graph cannot satisfy its declared config.
GraphNotFoundError ¶
Bases: ValueError
Raised when a requested graph is not registered.
GraphRegistry ¶
Registry of graphs.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
get_graph ¶
Get a graph by its name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the graph to retrieve. |
required |
Returns:
| Type | Description |
|---|---|
GraphConfig
|
The graph configuration associated with the given name. |
Raises:
| Type | Description |
|---|---|
GraphNotFoundError
|
If the graph name is not found in the registry. |
Source code in src/langgraph_openai_serve/graph/graph_registry.py
get_graph_names ¶
register ¶
Add or replace one graph through the validated registry boundary.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
interrupt ¶
Durable interrupt support for LangGraph runs.
InMemoryRunCoordinator ¶
Coordinate interrupt runs within one process without waiting.
Source code in src/langgraph_openai_serve/graph/interrupt/coordination.py
__call__
async
¶
Acquire lease asynchronously.
InterruptResume
dataclass
¶
A complete, causally bound set of interrupt answers.
LangGraphInterruptBatch
dataclass
¶
The durable interrupts awaiting answers for one graph run.
RunBusyError ¶
Bases: RuntimeError
Raised when an interrupt run cannot acquire its coordination lease.
Source code in src/langgraph_openai_serve/graph/interrupt/coordination.py
RunCoordinator ¶
Bases: Protocol
Acquire a lease that rejects rather than queues an occupied interrupt run.
coordination ¶
Nonblocking coordination for interrupt-enabled graph runs.
InMemoryRunCoordinator ¶
Coordinate interrupt runs within one process without waiting.
Source code in src/langgraph_openai_serve/graph/interrupt/coordination.py
__call__
async
¶
Acquire lease asynchronously.
RunBusyError ¶
Bases: RuntimeError
Raised when an interrupt run cannot acquire its coordination lease.
Source code in src/langgraph_openai_serve/graph/interrupt/coordination.py
RunCoordinator ¶
Bases: Protocol
Acquire a lease that rejects rather than queues an occupied interrupt run.
errors ¶
models ¶
Protocol-neutral models for interrupt-enabled graph runs.
state ¶
Durable state and resume handling for interrupt-enabled graph runs.
InterruptStateConflictError ¶
Bases: RuntimeError
Raised when a resume does not match durable pending state.
InvalidRunIDError ¶
Bases: ValueError
Raised when a caller-supplied run id is not a UUID.
checkpoint_key ¶
Derive a fixed-length storage key scoped to this protocol and model.
Source code in src/langgraph_openai_serve/graph/interrupt/state.py
continuation_generation_token
async
¶
Fingerprint the durable continuation generation across all namespaces.
Nested resumes may not advance the root checkpoint, and indirectly invoked subgraphs are not exposed through state snapshots. Scanning the checkpointer keeps stale-resume detection generic without introducing separate state.
Performance impact: Local PostgreSQL measurements were 0.5-0.7 ms for the current 1-2 tuple runs, scaling linearly to about 5 ms at 100 and 45 ms at 1,000 small tuples.
Source code in src/langgraph_openai_serve/graph/interrupt/state.py
durable_interrupt_batch
async
¶
Bind native execution interrupts to the durable checkpoint head.
Source code in src/langgraph_openai_serve/graph/interrupt/state.py
get_run_id ¶
Read the optional interrupt run id from normalized request metadata.
interrupts_by_id ¶
Validate and index the interrupts exposed by a state snapshot.
Source code in src/langgraph_openai_serve/graph/interrupt/state.py
normalize_checkpoint_scope ¶
Validate a server-owned checkpoint isolation scope.
Source code in src/langgraph_openai_serve/graph/interrupt/state.py
normalize_run_id ¶
Return the canonical form of a valid, non-nil UUID run id.
Source code in src/langgraph_openai_serve/graph/interrupt/state.py
prepare_interrupt_input
async
¶
Build a new input or causally validate an interrupt resume.
Source code in src/langgraph_openai_serve/graph/interrupt/state.py
require_checkpoint_id ¶
Return the checkpoint id from a validated LangGraph config.
Source code in src/langgraph_openai_serve/graph/interrupt/state.py
resolve_run_id ¶
Resolve and validate the durable run identity for a request.
Source code in src/langgraph_openai_serve/graph/interrupt/state.py
validation ¶
Validate graph-authored LangGraph interrupt payloads.
validate_interrupt_payload ¶
Require function-call arguments containing valid JSON object values.
Source code in src/langgraph_openai_serve/graph/interrupt/validation.py
request ¶
runner ¶
Run LangGraph workflows from protocol-neutral requests and messages.
invoke_run
async
¶
Invoke a graph already owned by an active GraphRun context.
Source code in src/langgraph_openai_serve/graph/runner.py
run_langgraph
async
¶
Prepare and invoke a graph for direct runner callers.
This convenience wrapper combines :func:prepare_run and :func:invoke_run.
The HTTP route prepares its run before creating a response so preparation
errors can be returned as OpenAI-compatible HTTP errors; its service therefore
calls invoke_run directly with that prepared run.
Examples:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
GraphRequest
|
Normalized graph selection, metadata, user, and client tools. |
required |
messages
|
list[BaseMessage]
|
Decoded LangChain messages to process through the graph. |
required |
graph_registry
|
GraphRegistry
|
The GraphRegistry instance containing registered graphs. |
required |
resume
|
InterruptResume | None
|
A decoded, complete interrupt answer batch, when resuming. |
None
|
checkpoint_scope
|
str
|
Server-trusted scope used to isolate checkpoint state. |
'default'
|
Returns:
| Type | Description |
|---|---|
LangGraphOutput
|
The durable graph output. |
Source code in src/langgraph_openai_serve/graph/runner.py
run_langgraph_stream
async
¶
run_langgraph_stream(
request, messages, graph_registry, *, resume=None, checkpoint_scope="default"
)
Prepare and stream a graph for direct runner callers.
This convenience wrapper combines :func:prepare_run and :func:stream_run.
The HTTP route prepares its run before starting the streaming response so
preparation errors remain normal OpenAI-compatible HTTP errors; its service
therefore calls stream_run directly with that prepared run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
GraphRequest
|
Normalized graph selection, metadata, user, and client tools. |
required |
messages
|
list[BaseMessage]
|
Decoded LangChain messages to process through the graph. |
required |
graph_registry
|
GraphRegistry
|
The registry containing the graph configurations. |
required |
resume
|
InterruptResume | None
|
A decoded, complete interrupt answer batch, when resuming. |
None
|
checkpoint_scope
|
str
|
Server-trusted scope used to isolate checkpoint state. |
'default'
|
Yields:
| Type | Description |
|---|---|
AsyncGenerator[LangGraphStreamEvent, None]
|
Assistant text chunks, custom events, or LangGraph interrupts. |
Source code in src/langgraph_openai_serve/graph/runner.py
stream_run
async
¶
Stream a graph already owned by an active GraphRun context.
Yields:
| Type | Description |
|---|---|
AsyncGenerator[LangGraphStreamEvent, None]
|
LangGraph stream events. |
Source code in src/langgraph_openai_serve/graph/runner.py
utils ¶
Prepare one isolated LangGraph execution for the OpenAI API.
GraphRun
dataclass
¶
GraphRun(
config,
graph,
inputs,
context,
runnable_config,
run_id,
checkpoint_thread_id=None,
should_execute=True,
pending_interrupts=(),
usage_callback=UsageMetadataCallbackHandler(),
_resources=AsyncExitStack(),
)
Own one prepared graph run and its cleanup resources.
__aenter__
async
¶
Claim ownership of this prepared run.
Source code in src/langgraph_openai_serve/graph/utils.py
__aexit__
async
¶
Finalize this run without suppressing its primary failure.
Source code in src/langgraph_openai_serve/graph/utils.py
aclose
async
¶
Apply checkpoint disposition and release resources exactly once.
Source code in src/langgraph_openai_serve/graph/utils.py
begin_execution ¶
Mark checkpoint state as incomplete immediately before execution.
commit_interrupts ¶
Preserve a validated interrupt batch committed by the runner.
Source code in src/langgraph_openai_serve/graph/utils.py
record_failure ¶
Retain the first failure so later cleanup cannot replace it.
require_owner ¶
Require the caller to own this run through its async context.
usage_metadata ¶
Return provider-reported usage aggregated across the graph run.
Source code in src/langgraph_openai_serve/graph/utils.py
build_runnable_config ¶
Build runnable config.
Source code in src/langgraph_openai_serve/graph/utils.py
prepare_run
async
¶
Prepare a graph run.
Source code in src/langgraph_openai_serve/graph/utils.py
integrations ¶
Optional infrastructure integrations for LangGraph OpenAI Serve.
langfuse ¶
Lazy construction for the optional Langfuse tracing integration.
get_langfuse_callback
cached
¶
Return the process-wide Langfuse callback, constructing it lazily.
postgres ¶
PostgreSQL coordination for interrupt-enabled graph runs.
PostgresRunCoordinator ¶
Coordinate interrupt runs with PostgreSQL session advisory locks.
The pool must return mapping rows, as required by AsyncPostgresSaver
when both components share one pool (for example, row_factory=dict_row).
max_concurrent_leases limits how many pool connections coordination may
hold at once. When the checkpointer shares this pool, reserve at least one
connection for checkpoint I/O to avoid exhausting the pool with leases.
Source code in src/langgraph_openai_serve/integrations/postgres.py
__call__
async
¶
Acquire a PostgreSQL advisory lease for one interrupt run.
Source code in src/langgraph_openai_serve/integrations/postgres.py
openai_server ¶
LangGraph OpenAI API Serve.
This module provides a server class that connects LangGraph instances to an OpenAI-compatible API. It allows users to register their LangGraph instances and expose them through a mounted FastAPI sub-application.
Examples:
>>> from langgraph_openai_serve import GraphConfig, GraphRegistry, LanggraphOpenaiServe
>>> from fastapi import FastAPI
>>> from your_graphs import simple_graph_1, simple_graph_2
>>>
>>> app = FastAPI(title="LangGraph OpenAI API")
>>> graphs = GraphRegistry(
... registry={
... "simple_graph_1": GraphConfig(
... graph=simple_graph_1,
... description="First simple graph.",
... ),
... "simple_graph_2": GraphConfig(
... graph=simple_graph_2,
... description="Second simple graph.",
... ),
... }
... )
>>> graph_serve = LanggraphOpenaiServe(
... app=app,
... graphs=graphs,
... )
>>> graph_serve.bind_openai_api()
LanggraphOpenaiServe ¶
Server class to connect LangGraph instances with an OpenAI-compatible API.
This class serves as a bridge between LangGraph instances and an OpenAI-compatible API. It allows users to register their LangGraph instances and expose them through an OpenAI-compatible sub-application mounted on a FastAPI host app.
Attributes:
| Name | Type | Description |
|---|---|---|
app |
FastAPI
|
The host FastAPI application to mount the OpenAI API on. |
graph_registry |
The populated GraphRegistry containing the graphs to serve. |
|
openai_app |
FastAPI
|
The mounted OpenAI-compatible FastAPI application. |
Initialize the server with a FastAPI app and a populated graph registry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app
|
FastAPI | None
|
The host FastAPI application to mount the OpenAI API on. If None, a new FastAPI app will be created. |
None
|
graphs
|
GraphRegistry
|
A GraphRegistry instance containing the graphs to serve. |
required |
checkpoint_scope
|
Callable[[Request], str | Awaitable[str]] | None
|
Optional server-trusted resolver used to isolate interrupt checkpoints by deployment or authenticated principal. |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If graphs is not a GraphRegistry instance. |
Source code in src/langgraph_openai_serve/openai_server.py
bind_openai_api ¶
Mount OpenAI-compatible endpoints on the host FastAPI app.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str | None
|
Optional; The URL prefix for the OpenAI-compatible endpoints. Defaults to settings.OPENAI_API_PREFIX. |
None
|
Source code in src/langgraph_openai_serve/openai_server.py
protocol ¶
Stable names used by the public LGOS protocol extensions.
schemas ¶
Models package for the LangGraph OpenAI compatible API.
utils ¶
Utility functions.
fake_llm ¶
Shared fake streaming model helpers for demos and tests.
stream_fake_chat_response
async
¶
Stream a deterministic fake chat response and collect it for graph state.