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. |
GET |
/v1/models/{model} |
Retrieve one model with the required LGOS metadata extension. |
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.
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 must contain at least one graph. Pydantic rejects empty registries
and model IDs that cannot be addressed as one URL path segment. Registry keys
are read-only after validation; use registry.register(model_id, config) to add
or replace a graph.
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 Chat Completions metadata or the Chat Completions 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.
GraphConfig accepts:
graph: compiled graph, sync factory, or async factory.description: required human-readable model description advertised by model listing and retrieval.streamable_node_names: node names whose streamedAIMessageChunkvalues are forwarded as assistant text. If several nodes contribute, the graph's output adapter must render the same ordered content for complete responses.features:GraphFeaturevalues that enable optional server behavior.client_settings: explicit publicClientSettingsmodel class advertised by model retrieval.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 OpenAI request to graph input.context_factory(request, client_settings): compose the final typed LangGraph runtime context from server-owned values and optional validated public settings.output_to_message(output): custom graph output to a durableAIMessage.
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].
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.langgraph_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 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.chat_completion and adds RunnableConfig.metadata fields for the
request ID, registered graph model, (for interrupt runs) operation ID, and (when
the request supplies metadata.session_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 same features set drives runtime behavior and the versioned
langgraph_openai_serve.features extension returned by
GET /v1/models/{model}. GraphFeature.CLIENT_EVENTS enables and advertises
public client-event chunks. 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.langgraph_runtime_settings string. Clients omit values equal to the advertised
defaults. System instructions remain ordinary OpenAI messages and are
independent of ClientSettings; native Chat Completions 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
langgraph_openai_serve.client_settings, with independent schema_version,
json_schema, and defaults fields. All client settings use the fixed
metadata.langgraph_runtime_settings envelope. Clients use the descriptor's
validated defaults object as the baseline; default keywords within the
generated JSON Schema are annotations, not the runtime baseline.
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 returns it in every interrupt tool call. A caller that needs deterministic
initial-request retries can instead supply a non-nil UUID in
metadata.langgraph_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".
Client Stream Events¶
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 portable status data matches native UI status concepts:
{
"type": "status",
"namespace": ["media"],
"data": {
"description": "Generating audio",
"done": false,
"hidden": false
}
}
done=False displays ongoing work; always finish a visible status sequence with
done=True. Set hidden=True on the final update when clients should remove the
status after completion. Status text is deliberately authored by the graph:
LGOS does not infer it from internal node names or state.
For other passive notifications, use client_event():
from langgraph.config import get_stream_writer
from langgraph_openai_serve import client_event
get_stream_writer()(
client_event(
"progress",
{
"stage": "retrieval",
"completed": 2,
"total": 5,
"message": "Searching documents",
},
namespace=("research",),
)
)
The v1 vocabulary is status, progress, and artifact. Event data must be
JSON-safe, and every namespace segment must be a string. Keep payloads small and
represent large artifacts by an ID or URL. The namespace is a stable,
author-defined path; LGOS does not expose LangGraph's dynamic execution
namespace.
Events are streaming-only and require both the graph feature and client opt-in.
Clients request them with
metadata={"langgraph_stream_events": "v1"} and receive a versioned
langgraph_openai_serve property on an otherwise standard Chat Completions
chunk. Missing and unsupported versions produce the ordinary strict stream.
Unknown custom events remain available only to direct runner consumers.
See Client stream events for the wire contract and OpenAI clients 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(annotation, text) to validate received indices and convert
them to a Python slice. LGOS maps native LangChain citations to completed
message.annotations; the streaming compatibility extension is added to the
final delta.
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.
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 chat completion 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
GraphFeature ¶
Bases: StrEnum
Features supported by a registered graph.
GraphRegistry ¶
Bases: BaseModel
Registry of graphs.
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.
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 OpenAI inclusive citation span to a validated Python slice.
Source code in src/langgraph_openai_serve/graph/events.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 ¶
deps ¶
Dependencies for chat completion routes.
schemas ¶
Pydantic models for the OpenAI API.
This module defines Pydantic models that match the OpenAI API request and response formats.
ChatCompletionRequest ¶
Bases: BaseModel
Model for a chat completion request.
ChatCompletionRequestMessage ¶
Bases: BaseModel
Model for a chat completion request message.
reject_legacy_fields
classmethod
¶
Reject the deprecated singular Chat Completions function call.
Source code in src/langgraph_openai_serve/api/chat/schemas.py
ChatCompletionResponse ¶
Bases: BaseModel
Model for a chat completion response.
ChatCompletionResponseChoice ¶
Bases: BaseModel
Model for a chat completion response choice.
ChatCompletionResponseMessage ¶
Bases: BaseModel
Model for a chat completion response message.
ChatCompletionStreamOptions ¶
Bases: BaseModel
Options that affect Chat Completions streaming.
ChatCompletionStreamResponse ¶
Bases: BaseModel
Model for a chat completion stream response.
ChatCompletionStreamResponseChoice ¶
Bases: BaseModel
Model for a chat completion stream response choice.
ChatCompletionStreamResponseDelta ¶
Bases: BaseModel
Model for a chat completion stream response delta.
ChatCompletionStreamToolCall ¶
Bases: BaseModel
Model for a streaming tool call delta.
ChatCompletionStreamToolCallFunction ¶
Bases: BaseModel
Model for a streaming tool call function delta.
FunctionDefinition ¶
Bases: BaseModel
Model for a function definition.
Role ¶
Bases: StrEnum
Role options for chat messages.
Tool ¶
Bases: BaseModel
Model for a tool.
ToolCall ¶
Bases: BaseModel
Model for a tool call.
ToolCallFunction ¶
Bases: BaseModel
Model for a tool call function.
ToolFunction ¶
Bases: BaseModel
Model for a tool function.
UsageInfo ¶
Bases: BaseModel
Model for usage information.
service ¶
Functions for generating chat completions.
generate_completion
async
¶
Generate a chat completion.
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
utils ¶
events ¶
Adapt generic LangGraph custom events to OpenAI chat fields.
client_event_extension_from_custom_event ¶
Validate an explicitly public event and build its stream extension.
Source code in src/langgraph_openai_serve/api/chat/utils/events.py
stream_events_requested ¶
Return whether a request opted into the supported event stream version.
Source code in src/langgraph_openai_serve/api/chat/utils/events.py
interrupts ¶
OpenAI Chat Completions codec for LangGraph interrupts.
InterruptResume
dataclass
¶
A complete, causally bound set of interrupt answers.
InvalidInterruptPayloadError ¶
Bases: ValueError
Raised when graph-authored interrupt data cannot cross the JSON API.
InvalidResumeRequestError ¶
Bases: ValueError
Raised when an OpenAI tool exchange is not a valid interrupt resume.
interrupt_arguments ¶
Encode one interrupt without coercing unsupported graph values.
Source code in src/langgraph_openai_serve/api/chat/utils/interrupts.py
interrupt_tool_call_id ¶
parse_resume_request ¶
Parse the trailing canonical assistant/tool interrupt exchange.
Ordinary tool messages remain ordinary graph input. A LangGraph resume is
recognized only when the tool results answer a preceding assistant message
whose function calls are all langgraph_interrupt calls.
Source code in src/langgraph_openai_serve/api/chat/utils/interrupts.py
validate_interrupt_payload ¶
responses ¶
OpenAI chat response builders.
ChatCompletionStreamResponseBuilder ¶
Build OpenAI-compatible chat completion SSE chunks.
Source code in src/langgraph_openai_serve/api/chat/utils/responses.py
Build an empty-delta chunk carrying the opt-in event extension.
Source code in src/langgraph_openai_serve/api/chat/utils/responses.py
Stream finish.
Source code in src/langgraph_openai_serve/api/chat/utils/responses.py
Stream interrupt.
Source code in src/langgraph_openai_serve/api/chat/utils/responses.py
Stream complete final-message tool calls as one delta.
Source code in src/langgraph_openai_serve/api/chat/utils/responses.py
Stream the optional final usage-only chunk.
Source code in src/langgraph_openai_serve/api/chat/utils/responses.py
annotations_from_message ¶
Convert native LangChain citations to OpenAI URL annotations.
Source code in src/langgraph_openai_serve/api/chat/utils/responses.py
chat_completion_response ¶
Build a non-streaming OpenAI-compatible chat completion response.
Source code in src/langgraph_openai_serve/api/chat/utils/responses.py
interrupt_tool_arguments ¶
Format interrupt tool arguments.
Source code in src/langgraph_openai_serve/api/chat/utils/responses.py
interrupt_tool_call ¶
Format interrupt tool call.
Source code in src/langgraph_openai_serve/api/chat/utils/responses.py
response_message ¶
Format response message.
Source code in src/langgraph_openai_serve/api/chat/utils/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/utils/responses.py
usage_info ¶
Map LangChain's provider-reported usage to Chat Completions usage.
Source code in src/langgraph_openai_serve/api/chat/utils/responses.py
streaming ¶
Tie LangGraph stream production to a FastAPI request's lifetime.
Starlette owns response consumption, not the nested graph producer, so a client
disconnect may leave graph and provider work running. The request dependency
creates a _StreamOwner; the route passes start()'s receive stream to
StreamingResponse, and dependency cleanup cancels the producer and releases
its GraphRun.
AnyIO still provides the channel and cleanup shield, but its task-group level
cancellation can repeatedly interrupt LangGraph's asyncio-native teardown. The
producer therefore remains an asyncio.Task so cancellation is delivered once
at the stream boundary.
views ¶
Chat completion router.
This module provides the FastAPI router for the chat completion endpoint, implementing an OpenAI-compatible interface.
client_error_param ¶
Get client error param.
Source code in src/langgraph_openai_serve/api/chat/views.py
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_dependency)]
|
The graph registry dependency. |
required |
checkpoint_scope
|
Annotated[str, Depends(checkpoint_scope_dependency)]
|
The checkpoint scope boundary. |
required |
stream_owner
|
Annotated[_StreamOwner, Depends(stream_owner_dependency, scope=request)]
|
The request-scoped streaming task owner. |
required |
Returns:
| Type | Description |
|---|---|
StreamingResponse | ChatCompletionResponse
|
A chat completion response, either as a complete response or as a stream. |
Source code in src/langgraph_openai_serve/api/chat/views.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | |
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
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 ¶
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.
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.
citation_slice ¶
Convert an OpenAI inclusive citation span to a validated Python slice.
Source code in src/langgraph_openai_serve/graph/events.py
client_event ¶
Build an explicitly public, JSON-safe client stream event.
Source code in src/langgraph_openai_serve/graph/events.py
client_event_extension ¶
Build a stream extension from validated public custom stream 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 chat completion 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
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 ¶
Bases: BaseModel
Registry of graphs.
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.
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.
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.
models ¶
Result models produced by interrupt-enabled graph runs.
LangGraphInterruptBatch
dataclass
¶
The durable interrupts awaiting answers for one graph run.
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
checkpoint_state_token
async
¶
Fingerprint the latest checkpoint in every namespace.
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
¶
Read the durable checkpoint head after graph execution has quiesced.
Source code in src/langgraph_openai_serve/graph/interrupt/state.py
get_run_id ¶
Read the optional interrupt run id from OpenAI 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
runner ¶
Run LangGraph workflows behind the OpenAI-compatible chat API.
delete_checkpoint_thread
async
¶
Delete terminal state retained only to support an active interrupt.
Source code in src/langgraph_openai_serve/graph/runner.py
finalize_run
async
¶
Finalize checkpoint retention, then release any interrupt-run lease.
Only state exposed as a resumable interrupt is preserved. Cleanup for an unclassified run is best-effort so it cannot mask the failure that prevented classification.
Source code in src/langgraph_openai_serve/graph/runner.py
invoke_run
async
¶
Invoke a graph and return only its durable result.
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 |
|---|---|---|---|
model
|
str
|
The name of the model to use, which also determines which graph to use. |
required |
messages
|
list[ChatCompletionRequestMessage]
|
A list of messages to process through the LangGraph. |
required |
graph_registry
|
GraphRegistry
|
The GraphRegistry instance containing registered graphs. |
required |
request
|
ChatCompletionRequest | None
|
The complete chat completion request passed to graph adapters. |
None
|
Returns:
| Type | Description |
|---|---|
LangGraphInvocation
|
The durable graph output. |
Source code in src/langgraph_openai_serve/graph/runner.py
run_langgraph_stream
async
¶
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 |
|---|---|---|---|
model
|
str
|
The name of the model (graph) to run. |
required |
messages
|
list[ChatCompletionRequestMessage]
|
A list of OpenAI-compatible messages. |
required |
graph_registry
|
GraphRegistry
|
The registry containing the graph configurations. |
required |
request
|
ChatCompletionRequest | None
|
The complete chat completion request passed to graph adapters. |
None
|
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 an already prepared LangGraph invocation.
Yields:
| Type | Description |
|---|---|
AsyncGenerator[LangGraphStreamEvent, None]
|
LangGraph stream events. |
Source code in src/langgraph_openai_serve/graph/runner.py
text_from_message_event ¶
Extract visible text from a streamable LangGraph message event.
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,
usage_callback=UsageMetadataCallbackHandler(),
_lease=None,
)
Context for a graph run.
aclose
async
¶
Release this run's interrupt lease exactly once, if present.
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
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 | |
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
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.
Source code in src/langgraph_openai_serve/utils/fake_llm.py
message ¶
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. |