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
function tools and 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.
LGOS does not persist completed Responses for retrieve or deletion. Omitted store and
store=false are accepted; 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 OpenAI-hosted tools, structured output, image/audio
input, URL or inline file input, 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.
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 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.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 or advertise a graph input capability.hosted_tools: allowlistedlgos_...tool identifiers accepted by Responses; the graph owns their schemas and execution. See hosted tools.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 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.
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
only the shared model, metadata, user, normalized function tools,
tool_choice, parallel_tool_calls, and hosted_tools values.
hosted_tools is a tuple of selected LGOS identifiers, separate from function
tools; Chat requests leave it empty. 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 same features set drives runtime behavior and the versioned
lgos.features extension returned by model listing and
retrieval. GraphFeature.CLIENT_EVENTS enables and advertises public
status commentary in streaming Responses. Chat Completions ignores custom
stream events and does not emit commentary.
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 received indices and convert
them to 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
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.
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
NamedFunctionToolChoice
dataclass
¶
Require one named client-supplied function.
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.
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.
ChatCompletionRequest ¶
Bases: BaseModel
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: BaseModel
Model for a chat completion request message.
ChatCompletionStreamOptions ¶
Bases: BaseModel
Options that affect Chat Completions streaming.
FunctionDefinition ¶
Bases: BaseModel
Model for a function definition.
NamedToolChoice ¶
Bases: BaseModel
Named function tool choice accepted by Chat Completions.
NamedToolChoiceFunction ¶
Bases: BaseModel
Function selected by a named Chat Completions tool choice.
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.
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
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_dependency)]
|
The graph registry dependency. |
required |
stream_owner
|
Annotated[_StreamOwner, Depends(stream_owner_dependency, 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.
checkpoint_scope_dependency
async
¶
Resolve the server-trusted checkpoint scope for one request.
Source code in src/langgraph_openai_serve/api/deps.py
stream_owner_dependency
async
¶
Manage the streaming producer owned by one request.
Yields:
| Type | Description |
|---|---|
AsyncIterator[_StreamOwner]
|
The request-scoped stream owner. |
Source code in src/langgraph_openai_serve/api/deps.py
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.
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
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
validate_hosted_tools ¶
Reject unavailable hosted tools before graph 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.
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.
ResponseHostedTool ¶
Bases: _ResponsesRequestModel
Select a graph-owned LGOS tool without supplying its function schema.
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 tool.
ResponseOutputMessageInput ¶
Bases: _ResponsesRequestModel
A completed assistant output message replayed as input.
ResponseOutputTextInput ¶
Bases: _ResponsesRequestModel
Plain output text replayed from a previous assistant message.
ResponseTextConfig ¶
Bases: _ResponsesRequestModel
Plain-text response configuration.
ResponseTextFormat ¶
Bases: _ResponsesRequestModel
The supported plain-text output format.
service ¶
Execute and assemble OpenAI Response objects.
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/service.py
UnsupportedResponsesOutputError ¶
Bases: RuntimeError
Raised when graph output cannot be serialized as supported Responses items.
generate_response
async
¶
Invoke a graph and serialize its durable Responses output.
Source code in src/langgraph_openai_serve/api/responses/service.py
interrupt_output_items ¶
Serialize one durable interrupt batch as function-call items.
Source code in src/langgraph_openai_serve/api/responses/service.py
response_function_call ¶
Serialize one LangChain client tool call.
Source code in src/langgraph_openai_serve/api/responses/service.py
response_function_calls ¶
Serialize and validate all client tool calls from an assistant message.
Source code in src/langgraph_openai_serve/api/responses/service.py
response_object ¶
Build one SDK-typed Response with the route's stable defaults.
Source code in src/langgraph_openai_serve/api/responses/service.py
response_output_items ¶
Serialize one assistant message into ordered Responses output items.
Source code in src/langgraph_openai_serve/api/responses/service.py
response_output_text ¶
Build final Responses text and validated native URL annotations.
Source code in src/langgraph_openai_serve/api/responses/service.py
response_usage ¶
Map provider-reported LangChain usage to Responses token details.
Source code in src/langgraph_openai_serve/api/responses/service.py
streaming ¶
Assemble SDK-typed OpenAI Responses streaming events.
ResponsesStreamBuilder ¶
Own stable state for one Responses SSE lifecycle.
Source code in src/langgraph_openai_serve/api/responses/streaming.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/streaming.py
created ¶
Create the initial response event.
Source code in src/langgraph_openai_serve/api/responses/streaming.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/streaming.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/streaming.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/streaming.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/streaming.py
in_progress ¶
Create the response in-progress event.
Source code in src/langgraph_openai_serve/api/responses/streaming.py
encode_event ¶
Encode one Responses event using the official named SSE framing.
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/streaming.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.
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 ¶
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
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.
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
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 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.
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 |
|---|---|---|---|
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 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,
)
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
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 | |
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.