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, features, and tool names. |
GET |
/v1/models/{model} |
Retrieve one model with the required LGOS metadata extension. |
POST |
/v1/responses |
Run a graph now or accept an opted-in polling-only background Response. |
GET |
/v1/responses/{response_id} |
Retrieve an authorized background Response. |
POST |
/v1/responses/{response_id}/cancel |
Cancel an active background Response or return a finished one. |
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, safety_identifier
and its deprecated alias user, flat client
function tools, registered name-only custom-tool selectors, standard
web_search, their choices,
parallel_tool_calls, plain text output, and streaming. Replayed
assistant output messages preserve phase; complete
function_call items and matching string-valued function_call_output items
support ordinary client-tool continuation. Interrupt continuation sends only
matching function_call_output items with previous_response_id.
Server execution returns native custom_tool_call and
custom_tool_call_output pairs or a
web_search_call in the same response; complete output items can also be
replayed as history.
LGOS executes registered custom tools inside that response. This intentionally
differs from OpenAI's ordinary custom-tool flow, where caller code executes the
tool and supplies its output to a later model request; the wire items remain
standard Responses types.
The public web_search shape does not prescribe the graph's search backend;
the bundled demo chooses an HTTP or upstream provider backend.
Foreground LGOS Responses are not persisted for retrieval or deletion. Omitted,
null, and false store values are accepted, and the returned foreground
Response reports store=false; foreground store=true is rejected.
For a model declaring GraphFeature.BACKGROUND, background=true selects the
polling-only path and permits either store=false or store=true; the
background engine keeps the result either way, and Hatchet keeps it for its
data retention period
(30 days by default when self-hosted). Background streaming and
cursor/event replay are rejected. conversation is unsupported in both modes.
previous_response_id is supported for interruptible graphs to resume execution
(and rejected for non-interruptible graphs); new instructions are rejected on
those resumes. The route also rejects unregistered custom tools, client-supplied
custom descriptions or formats, other built-in tools,
structured output, image/audio input, URL or inline file input, function
result-content lists, reasoning and generation controls, include, stream options,
service tiers, reusable prompts,
prompt-cache controls, and truncation. Unknown fields are not silently ignored.
See the supported Responses subset
for the complete behavior and continuation rules.
Chat Completions Request¶
Chat messages accept string content, explicit text content parts, and native
file parts containing only file.file_id. The route supports modern function
tools, tool_choice, assistant tool_calls, matching tool messages,
streaming, and stream_options.include_usage. Image and audio parts, inline
file data or filenames, prompt-cache fields, deprecated function fields,
generation controls, and other unknown fields are rejected.
Settings¶
Package settings:
| Setting | Default | Notes |
|---|---|---|
LGOS_OPENAI_API_PREFIX |
/v1 |
Must start with /; trailing slash is normalized. |
LGOS_OPENAI_API_DOCS_ENABLED |
False |
Enables docs only for the mounted OpenAI app. |
LGOS_ENABLE_LANGFUSE |
False |
Lazily adds the package Langfuse callback to every graph run. |
The lgos command adds the server settings.
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(graphs={...}, run_coordinator=...) to map OpenAI model
names to GraphConfig values; registry.graphs is a plain dict. The registry
must contain at least one graph. Model IDs must be non-empty, must not contain
/, and must not be . or ... registry.get_graph(model) returns a
GraphConfig or raises a 404 model_not_found error. run_coordinator is
shared by every interrupt-enabled graph and is required only when a graph
declares GraphFeature.INTERRUPTS.
LanggraphOpenaiServe(registry=registry, app=app) serves the registry.
LanggraphOpenaiServe(..., background=backend) accepts an optional
BackgroundBackend. LanggraphOpenaiServe(..., checkpoint_scope=resolver)
accepts an optional sync or async callable from FastAPI Request to a
non-empty, server-trusted string.
Interrupt checkpoint keys and background Response authorization include this
scope before model and run identity. Use
an authenticated tenant or principal identifier when runs must be isolated
between security domains; do not derive the scope from
untrusted OpenAI metadata or the end-user safety_identifier and user
fields. 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.
RequestContextFilter adds the active request's LGOS fields, such as
request_id, to log records; install it on a host handler to enrich every
record. See Production Logging.
Responses input_file.file_id content and native Chat file parts normalize to
the same LangChain file block, so graphs receive native file_id values and
decide whether to download, parse, or forward them. File upload and storage
belong to an external OpenAI Files API, not the LGOS package. See
Accept And Display Files.
GraphConfig accepts:
graph: compiled graph, sync factory, or async factory.description: required human-readable model description advertised by model listing and retrieval.features:GraphFeaturevalues that enable optional server behavior or advertise graph input and client-tool capabilities.client_settings: explicit publicClientSettingsmodel class advertised by model retrieval.server_tools: allowlist of server-executed tool names, advertised aslgos.server_tools. A registered custom tool is selected with the Responsescustomtype and name;web_searchuses its built-in type. The graph owns tool definitions and execution. See Server Tools.client_tools: names of client-owned functions the graph can call, such asdisplay_file, advertised aslgos.client_toolsso clients offer only the functions a graph uses. LGOS does not enforce the list, and a name cannot also be a server tool.runtime_callbacks: callbacks included in the LangGraphRunnableConfig. When Langfuse tracing is enabled, LGOS adds its callback without mutating this collection or manager.request_to_input(request, messages): custom normalized request and LangChain messages to graph input.context_factory(request, client_settings): compose the final typed LangGraph runtime context from normalized request values, server-owned values, and optional validated public settings.output_to_message(output): custom graph output to a durableAIMessage.
GraphConfig is immutable after construction. Pydantic snapshots features,
server_tools, and client_tools as frozen sets, so later mutations of the
input collections cannot change a registered model. Freezing the declaration
does not make a caller-owned callback handler or callback manager internally
immutable.
Streaming forwards non-empty text from every AIMessageChunk emitted by the
graph's messages stream. To keep a private model call out of the stream, tag
it with LangGraph's
nostream
tag (langgraph.constants.TAG_NOSTREAM), for example
ChatOpenAI(..., tags=[TAG_NOSTREAM]); the call still runs and
returns its output, but LangGraph emits none of its tokens.
disable_streaming=True
is for models that cannot stream: it makes the provider request non-streaming,
and LangGraph emits the call's complete message instead. With either option,
LangGraph also emits a complete message that a node returns into state. LGOS
forwards neither complete message, but other consumers of the graph's stream
see them.
A directly supplied compiled graph is reused and validated when its
GraphConfig is built. A sync or async graph factory is called for every request
and is never cached; LGOS validates each resolved value as a compiled state graph
and rechecks it before execution. Validation checks the context schema and
interrupt checkpointer capabilities, rejects static breakpoints
(interrupt_before or interrupt_after) in the graph or its subgraph nodes,
since LGOS pauses only at interrupt(), and rejects a checkpointer, including
checkpointer=True, on a graph without GraphFeature.INTERRUPTS, since clients
send the full conversation with every other request. A registry with an
interrupt-enabled graph and no run_coordinator fails during GraphRegistry
construction. A graph may declare both interrupts and background; a background
run that reaches an interrupt completes with lgos_interrupt function calls,
and an answer in either mode continues it.
When both are configured, LGOS validates the public settings first and passes
them to context_factory. Without a factory, the validated settings instance is
the runtime context, so the graph must use that settings model as its
context_schema. A factory may return None; every non-null result requires a
graph context schema. LGOS passes server-owned factory results to LangGraph
without rebuilding them. LangGraph's native
runtime-context handling
constructs mapping values through dataclass and Pydantic context schemas and
trusts existing instances. The factory owns the validity of instances it
creates. Graphs should access context from an injected Runtime[Context].
Graph adapters receive an immutable, protocol-neutral GraphRequest from either
API's decoder. It exposes
the shared model, metadata, user (the end user from safety_identifier, or
the deprecated user field), normalized client function tools,
selected server-tool names in server_tools, tool_choice, and parallel_tool_calls
values. NamedFunctionToolChoice identifies a required client function, while
NamedCustomToolChoice identifies a required registered custom tool. A
single web_search declaration with tool_choice="required" requires search.
Named built-in choices are outside the supported subset.
Raw OpenAI transport models are
not part of the graph-adapter interface.
Runtime context is separate from RunnableConfig:
| Value | LGOS/LangGraph path | Intended use |
|---|---|---|
| Graph input | graph.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 + server-generated run UUID → internal checkpoint key | Isolate, 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 run 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. A self-hosted Langfuse must
be a release that Langfuse's
compatibility matrix
lists for the Python SDK version that the extra installs. 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. Before that, LGOS creates the Langfuse
client with a tracer provider of its own, as Langfuse
recommends beside another
tracing backend. Langfuse's observations, which carry prompts and outputs, then
never reach the application's OpenTelemetry exporters, and the
application's spans never reach Langfuse; both share each trace ID. An
application that creates its own Langfuse client first keeps its own tracing
setup. 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.
LGOS gives every 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 it names an end user with safety_identifier or the deprecated user)
that end user as lgos.user. Graph code can read them with LangGraph's
get_config(), with or without Langfuse. When the toggle is on, LGOS also sets
the end user, metadata.conversation_id, and the registered model as Langfuse's
native user, session, and trace name on every observation of the run; a custom
handler passed with the toggle off does not receive them. LangGraph also propagates primitive
configurable values
during execution, so callbacks on interrupt runs receive the derived checkpoint
thread_id. LGOS does not set LangChain's native tracer run_id or force a
custom Langfuse trace ID. See Production Logging and Request
Correlation.
The features set is returned in the lgos.features extension and
enables server behavior where applicable.
GraphFeature.MCP_TOOLS advertises that a client may attach and execute tools
from its configured MCP gateway; it does not publish tool definitions or grant
access to them.
GraphFeature.FILE_INPUTS advertises that the graph
resolves native file content parts. GraphFeature.INTERRUPTS enables and
advertises the interrupt/resume flow. GraphFeature.BACKGROUND enables and
advertises polling-only background Responses.
OpenTelemetry¶
LGOS reports every graph execution through the OpenTelemetry API, following the
GenAI workflow span
and workflow metric
conventions. The API records nothing until the host application configures an
SDK, for example with opentelemetry-instrument.
HTTP request telemetry belongs to the host app. The mounted OpenAI app turns off
FastAPI's native OpenTelemetry,
so the host's telemetry settings, including turning it off, cover LGOS routes,
and http.route includes the mount, such as /v1/responses.
| Signal | Name | Attributes |
|---|---|---|
Span, kind INTERNAL |
invoke_workflow {model} |
gen_ai.operation.name=invoke_workflow, gen_ai.workflow.name, gen_ai.conversation.id when the request supplies metadata.conversation_id, and error.type on failure |
Histogram, unit s |
gen_ai.invoke_workflow.duration |
gen_ai.workflow.name, and error.type on failure |
gen_ai.workflow.name is the registered model. Both signals cover graph
execution through the final output; they exclude lease waits, background queue
time, and checkpoint cleanup. While LGOS advances the graph, the span's context
is current: spans the graph creates, such as model calls, are its children,
while code that consumes a stream keeps its own parent span between events. The
span itself is not current, so code in the graph cannot change it, and it
carries only the attributes above; add attributes to spans of your own. A run
that ends before its output exists fails: one that raises an exception, one
cancelled by a disconnecting client or a cancelled background Response, and one
whose stream the consumer closes mid-run. The span status is then ERROR with
the exception message, if any, and error.type is the exception type, qualified
by its module unless it is built in, such as asyncio.exceptions.CancelledError
or GeneratorExit. Closing a stream after its final output is not a failure.
Design Choices lists the tracers whose
cancellation handling this follows. A raised Exception propagates to its
handler: LGOS routes and the background engines log it with its traceback, and
direct Python callers receive it; cancellations and closed streams are not
logged. The span does not repeat an exception as an event. The histogram uses
the conventions' bucket boundaries, which start at one second; configure an SDK
View for finer boundaries.
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
deterministic default, because clients omit values equal to the advertised
defaults; a default_factory must return the same value on every call.
Registration fails when the model cannot build its defaults or schema.
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 the settings with the model's strict JSON validation 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 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.
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(),aput(),aput_writes(), andadelete_thread(); - configure an asynchronous
GraphRegistry.run_coordinator; and - use a durable checkpointer and cross-process coordinator in production.
The coordinator provides single-flight leases for interrupt runs: it returns an async context manager and rejects an occupied checkpoint key instead of queueing it. Exiting that context manager must release the lease even when the exit is cancelled.
The initial request does not require metadata. LGOS generates a UUID run ID for
every new run and embeds it in the paused Response ID. InMemoryRunCoordinator
is suitable only for tests and a single-process development server; it cannot
serialize requests across workers or hosts.
Expire Paused Runs¶
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. A run abandoned
after its batch is returned stays until deleted: call
delete_expired_interrupt_runs(checkpointer, run_coordinator, older_than=...)
from langgraph_openai_serve.graph.interrupt on a schedule, as LangGraph Agent
Server's checkpointer TTL
does. In production, prefer one scheduled job over a loop in every replica, for
example a Kubernetes CronJob with concurrencyPolicy: Forbid or your task
queue's scheduler. It deletes the runs whose latest pause is older than
older_than and returns their count. It reads every checkpoint through
alist(), leaves threads LGOS did not create alone, and skips runs whose lease
is held. Choose a TTL longer than the longest time a user may take to answer. To
write your own cleanup, select threads whose checkpoint metadata contains
OPERATION_ID_METADATA_KEY from the same module, then hold each run's lease,
confirm that its latest checkpoint in any namespace is still older than your
TTL, and delete it through the checkpointer. lgos serve runs this sweep in
each API process, configured by LGOS_INTERRUPT_TTL_MINUTES and
LGOS_INTERRUPT_SWEEP_INTERVAL_MINUTES; set the interval to 0 when one
scheduled job sweeps instead.
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() before serving requests, serializing
migration attempts when workers can start together. Their migrations use
CREATE INDEX CONCURRENTLY, which deadlocks with a worker blocked in
pg_advisory_lock; retry pg_try_advisory_lock instead. 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. Each process applies pending
LangGraph migrations during startup under a separate schema advisory lock.
Busy interrupt leases fail before streaming begins with HTTP 409
and code: "run_busy".
Background Execution¶
LanggraphOpenaiServe(background=...) accepts any BackgroundBackend: an
engine that runs BackgroundJobs and stores their status and result.
| Method | Contract |
|---|---|
submit(job) |
Start the job, or return the run already holding job.idempotency_key. |
get(run_id) |
Return the run's job, status, and executed Response, or None. |
cancel(run_id) |
Stop the run; a finished run keeps its outcome. |
The engine's worker calls execute_background_job(job, run_id, registry). It
runs the job through the foreground Responses path and returns the Response
JSON the engine stores. Run IDs must be UUIDs because the public Response ID
embeds the run ID, so reading a Response needs no lookup table.
InMemoryBackgroundBackend(registry) runs jobs as tasks of one process for
development and tests; enter its lifespan in the application's lifespan.
Install langgraph-openai-serve[hatchet] for
langgraph_openai_serve.integrations.hatchet. create_hatchet_task(hatchet)
registers the task in the API and worker processes, with a 30-minute
schedule_timeout and a one-hour execution_timeout by default.
HatchetBackgroundBackend(task, hatchet.runs) submits, reads, and cancels its
runs. The worker's Hatchet lifespan yields the GraphRegistry, including its
run_coordinator, that the task executes. The task has no retries, and its
24-hour Hatchet idempotency key is the scoped Idempotency-Key digest. The
adapter is never imported by the core package.
Background create accepts an optional Idempotency-Key header of 1 to 255
characters. A retry returns the original Response without starting a second
run; reuse with different content returns 422 with
code="idempotency_key_reused". A background interrupt run chooses its run ID
at submission.
See Run Responses In The Background for the client contract, graph requirements, and deployment wiring.
Server¶
Install langgraph-openai-serve[server] for the lgos command and
langgraph_openai_serve.server. lgos serve module:attribute and
lgos worker module:attribute run a RegistryFactory: a callable that takes
ServerResources (checkpointer, store, run_coordinator) and returns a
GraphRegistry, or an async context manager that yields one. lgos serve
also accepts every Uvicorn option and UVICORN_* variable.
create_app(factory, settings=...) returns the FastAPI application that
lgos serve runs; its lifespan opens the resources and mounts the OpenAI
routes. ServerSettings reads the LGOS_* server settings. See
Run The LGOS Server.
Streaming Status¶
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"))
# Perform the long-running work.
writer(status_event("Audio ready"))
The helper returns this custom stream value:
Status text is deliberately authored by the graph; LGOS does not infer it from internal node names or state. Graphs need no feature declaration to publish status.
Status is streaming-only. Streaming Responses needs no metadata opt-in and emits
each non-empty description as a standard phase="commentary" message.
Non-streaming Responses and Chat Completions ignore statuses. Both APIs ignore
any other custom stream data. Use standard Responses function calls plus the
Files API for portable durable rich output.
See Streaming status for the wire contract and Stream final text and commentary for consumption.
Citations¶
Put citations on the final LangChain AIMessage:
from langchain_core.messages import AIMessage
from langchain_core.messages.content import create_citation, create_text_block
message = AIMessage(
content=[
create_text_block(
text="Read the source [1].",
annotations=[
create_citation(
url="https://example.com/source",
title="Example source",
start_index=9,
end_index=14,
cited_text="source",
)
],
)
]
)
Put visible inline citations in the assistant text. Structured annotations add machine-readable provenance; clients are not required to invent marker text from annotation indices.
LangChain citation indices refer to their containing text block. LGOS offsets
them into the final response text and preserves OpenAI's inclusive end_index.
Use citation_slice(start_index, end_index, text) to validate them and create a
Python slice. Responses maps citations to output_text.annotations and emits
the typed annotation event while streaming. Chat maps them to completed
message.annotations; its final streaming delta uses the compatibility
extension.
See Citation ownership for transport and client behavior.
The streaming graph runner preserves LangGraph's native CustomStreamPart
values, including their execution namespace. Non-streaming invocation does not
subscribe to or replay custom events.
langgraph-openai-serve package.
BackgroundBackend ¶
BackgroundJob ¶
Bases: BaseModel
A validated request and the server-owned context that executes it.
BackgroundRun ¶
Bases: BaseModel
An engine's current view of one submitted job.
snapshot ¶
Return the public Response for the run's current state.
Source code in src/langgraph_openai_serve/background.py
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 needs a deterministic default so model discovery can advertise a complete, stable settings object.
default_values
classmethod
¶
Return the JSON defaults advertised by model discovery.
Source code in src/langgraph_openai_serve/graph/client_settings.py
json_schema
classmethod
¶
Return the JSON Schema advertised by model discovery.
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
¶
Fail at registration when a settings model cannot be advertised.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
validate_compiled_graph ¶
Fail at registration when a directly supplied graph cannot be served.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
validate_tool_ownership ¶
Keep the side that executes each advertised tool unambiguous.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
GraphError ¶
Bases: RuntimeError
Raised when a graph's configuration or output cannot be served.
GraphFeature ¶
Bases: StrEnum
Features supported by a registered graph.
GraphRegistry
dataclass
¶
The graphs served as OpenAI models, keyed by model ID.
run_coordinator leases the interrupt runs of every interrupt-enabled
graph; use a shared coordinator when several processes serve these graphs.
__post_init__ ¶
Fail at startup for a registry the OpenAI routes cannot serve.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
get_graph ¶
Return the graph served as model.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
GraphRequest
dataclass
¶
Request data shared by protocol decoders and graph execution.
InMemoryBackgroundBackend ¶
Run background jobs as tasks of this application process.
For development and tests: runs stay in memory until the process exits.
Source code in src/langgraph_openai_serve/background.py
cancel
async
¶
Mark an active run cancelled and cancel its task.
Source code in src/langgraph_openai_serve/background.py
get
async
¶
lifespan
async
¶
Own the execution tasks for one ASGI application lifespan.
Source code in src/langgraph_openai_serve/background.py
submit
async
¶
Start one task, or return the run holding the job's key.
Source code in src/langgraph_openai_serve/background.py
InvalidRequestError ¶
Bases: Exception
A request rejected with an OpenAI invalid_request_error envelope.
Source code in src/langgraph_openai_serve/core/errors.py
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 graphs to serve and their interrupt run coordinator. |
|
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 |
|---|---|---|---|
registry
|
GraphRegistry
|
The graphs to serve and their interrupt run coordinator. |
required |
app
|
FastAPI | None
|
The host FastAPI application to mount the OpenAI API on. If None, a new FastAPI app will be created. |
None
|
checkpoint_scope
|
Callable[[Request], str | Awaitable[str]] | None
|
Optional server-trusted resolver used to isolate interrupt checkpoints by deployment or authenticated principal. |
None
|
background
|
BackgroundBackend | None
|
Optional polling-only background backend. |
None
|
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
RequestContextFilter ¶
Bases: Filter
Add the active LGOS request fields to log records.
LGOS installs it on its own loggers. A host that installs it on a handler also enriches records from graph nodes, dependencies, and its own code.
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
citation_slice ¶
Convert an inclusive citation span to a validated Python slice.
Source code in src/langgraph_openai_serve/graph/citations.py
execute_background_job
async
¶
Execute one job through the foreground Responses path.
Source code in src/langgraph_openai_serve/background.py
status_event ¶
Build a status update for a node to write with get_stream_writer().
api ¶
chat ¶
messages ¶
Convert Chat Completions messages into LangChain messages.
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.
ChatCompletionFileContentPart ¶
Bases: _ChatRequestModel
One native Chat Completions file-ID content part.
ChatCompletionFileReference ¶
Bases: _ChatRequestModel
One uploaded file selected by its opaque Files API ID.
ChatCompletionRequest ¶
Bases: _ChatRequestModel
Model for a chat completion request.
validate_stream_options ¶
Allow stream options only for streaming requests.
Source code in src/langgraph_openai_serve/api/chat/schemas.py
ChatCompletionRequestMessage ¶
Bases: _ChatRequestModel
Model for a chat completion request message.
ChatCompletionStreamOptions ¶
Bases: _ChatRequestModel
Options that affect Chat Completions streaming.
ChatCompletionTextContentPart ¶
Bases: _ChatRequestModel
One text part in a Chat Completions message.
FunctionDefinition ¶
Bases: _ChatRequestModel
Model for a function definition.
NamedToolChoice ¶
Bases: _ChatRequestModel
Named function tool choice accepted by Chat Completions.
NamedToolChoiceFunction ¶
Bases: _ChatRequestModel
Function selected by a named Chat Completions tool choice.
Role ¶
Bases: StrEnum
Role options for chat messages.
Tool ¶
Bases: _ChatRequestModel
Model for a tool.
ToolCall ¶
Bases: _ChatRequestModel
Model for a tool call.
ToolCallFunction ¶
Bases: _ChatRequestModel
Model for a tool call function.
service ¶
Prepare and execute graph runs for OpenAI Chat Completions.
generate_completion
async
¶
Generate a chat completion.
Source code in src/langgraph_openai_serve/api/chat/service.py
prepare_completion_run
async
¶
Validate a Chat request and prepare its graph run.
Source code in src/langgraph_openai_serve/api/chat/service.py
stream_completion
async
¶
Stream a chat completion response.
Yields:
| Type | Description |
|---|---|
AsyncGenerator[str, None]
|
String chunks representing Server-Sent Events. |
Source code in src/langgraph_openai_serve/api/chat/service.py
views ¶
OpenAI-compatible Chat Completions router.
create_chat_completion
async
¶
Create one chat completion, as JSON or as an SSE stream.
Source code in src/langgraph_openai_serve/api/chat/views.py
deps ¶
Dependencies shared by OpenAI-compatible API routes.
get_graph_registry ¶
get_stream_owner
async
¶
Provide one request-scoped stream owner.
Yields:
| Type | Description |
|---|---|
AsyncIterator[StreamOwner]
|
The stream owner, closed after the response finishes. |
Source code in src/langgraph_openai_serve/api/deps.py
metadata ¶
Validation constraints shared by OpenAI request metadata and end-user 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
LGOS fields safe to include in a model list.
Model ¶
Bases: BaseModel
Individual model information.
ModelClientSettings ¶
Bases: BaseModel
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
responses ¶
OpenAI-compatible Responses API.
background ¶
Create, retrieve, and cancel polling-only background Responses.
cancel_background_response
async
¶
Cancel an active Response; a finished one is returned unchanged.
Source code in src/langgraph_openai_serve/api/responses/background.py
create_background_response
async
¶
create_background_response(
request, graph_registry, background, *, checkpoint_scope, idempotency_key=None
)
Validate one request and submit it to the background engine.
Proxies and SDKs retry creates after timeouts and 5xx responses. With an
Idempotency-Key, a retry returns the original Response instead of
starting a second run.
Source code in src/langgraph_openai_serve/api/responses/background.py
retrieve_background_response
async
¶
Read one authorized Response snapshot.
Source code in src/langgraph_openai_serve/api/responses/background.py
deps ¶
FastAPI dependencies local to the Responses route.
get_background_backend ¶
Return the optional server-injected background backend.
get_checkpoint_scope
async
¶
Resolve the server-trusted checkpoint scope for one request.
Source code in src/langgraph_openai_serve/api/responses/deps.py
validate_background_retrieval ¶
Reject streaming and cursors before reading the background engine.
Source code in src/langgraph_openai_serve/api/responses/deps.py
events ¶
Build SDK-typed OpenAI Responses events and named SSE frames.
ResponsesEventBuilder ¶
ResponsesEventBuilder(
request, *, run_id=None, response_id=None, created_at=None, server_tools=()
)
Own stable state for one Responses event lifecycle.
Source code in src/langgraph_openai_serve/api/responses/events.py
commentary ¶
Emit one complete commentary message lifecycle.
Yields:
| Type | Description |
|---|---|
ResponseStreamEvent
|
Typed events for the message lifecycle. |
Source code in src/langgraph_openai_serve/api/responses/events.py
created ¶
Create the initial response event.
Source code in src/langgraph_openai_serve/api/responses/events.py
failure ¶
Emit the normative terminal failure sequence.
Yields:
| Type | Description |
|---|---|
ResponseStreamEvent
|
The error and failed Response events. |
Source code in src/langgraph_openai_serve/api/responses/events.py
final_delta ¶
Emit one final-answer delta, opening its item if needed.
Yields:
| Type | Description |
|---|---|
ResponseStreamEvent
|
Typed events that open or update the final message. |
Source code in src/langgraph_openai_serve/api/responses/events.py
finish ¶
Reconcile final text, finish its item, and complete the Response.
Yields:
| Type | Description |
|---|---|
ResponseStreamEvent
|
Typed terminal events for a successful Response. |
Source code in src/langgraph_openai_serve/api/responses/events.py
finish_interrupt ¶
Emit a durable interrupt batch and complete the Response.
Yields:
| Type | Description |
|---|---|
ResponseStreamEvent
|
Typed function-call and terminal events. |
Source code in src/langgraph_openai_serve/api/responses/events.py
in_progress ¶
Create the response in-progress event.
Source code in src/langgraph_openai_serve/api/responses/events.py
server_tools ¶
Expose selected tool activity from one root graph update.
Yields:
| Type | Description |
|---|---|
ResponseStreamEvent
|
Native application-tool item lifecycle events. |
Source code in src/langgraph_openai_serve/api/responses/events.py
encode_event ¶
Encode one Responses event using the official named SSE framing.
interrupts ¶
OpenAI Responses encoding for LangGraph interrupt continuations.
interrupt_response_id ¶
Create a Response ID that carries its interrupt run identity.
A background Response passes its engine run UUID as nonce, so the ID
alone locates that run.
Source code in src/langgraph_openai_serve/api/responses/interrupts.py
interrupt_response_nonce ¶
Return the nonce UUID of an interrupt-style Response ID.
Source code in src/langgraph_openai_serve/api/responses/interrupts.py
interrupt_run_id ¶
Return the run UUID carried by an interrupt-style Response ID.
Source code in src/langgraph_openai_serve/api/responses/interrupts.py
interrupt_tool_call_id ¶
Expose one native LangGraph interrupt ID as an OpenAI call ID.
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.
convert_responses_input ¶
Normalize supported Responses text and message input.
Source code in src/langgraph_openai_serve/api/responses/messages.py
output ¶
Convert graph output into OpenAI Response models.
ResponseContext
dataclass
¶
Stable identity and request fields shared by one response lifecycle.
for_run
classmethod
¶
Build context, binding an interrupt response ID when run_id is present.
A background Response passes the response_id and created_at it
was accepted with, so every snapshot keeps one identity.
Source code in src/langgraph_openai_serve/api/responses/output.py
response ¶
Build one SDK-typed Response with the route's stable defaults.
Source code in src/langgraph_openai_serve/api/responses/output.py
interrupt_output_items ¶
Serialize one durable interrupt batch as function-call items.
Source code in src/langgraph_openai_serve/api/responses/output.py
response_function_call ¶
Serialize one LangChain client tool call.
Source code in src/langgraph_openai_serve/api/responses/output.py
response_function_calls ¶
Serialize and validate all client tool calls from an assistant message.
Source code in src/langgraph_openai_serve/api/responses/output.py
response_incomplete_details ¶
Keep the final provider's truncation or filtering outcome visible.
Source code in src/langgraph_openai_serve/api/responses/output.py
response_output_text ¶
Build final Responses text and validated native URL annotations.
Source code in src/langgraph_openai_serve/api/responses/output.py
response_refusals ¶
Read refusals through LangChain's normalized content boundary.
Source code in src/langgraph_openai_serve/api/responses/output.py
response_usage ¶
Map provider-reported LangChain usage to Responses token details.
Source code in src/langgraph_openai_serve/api/responses/output.py
request ¶
Decode Responses requests for protocol-neutral graph execution.
decode_graph_request ¶
Validate and normalize one Responses request for its registered graph.
Source code in src/langgraph_openai_serve/api/responses/request.py
decode_responses_request ¶
Normalize one supported, stateless Responses request.
Source code in src/langgraph_openai_serve/api/responses/request.py
selected_server_tools ¶
Return the registered server tools selected for this response.
Source code in src/langgraph_openai_serve/api/responses/request.py
schemas ¶
Validated request models for the supported Responses API subset.
ResponseCreateRequest ¶
Bases: _ResponsesRequestModel
The stateless Responses request accepted by LGOS.
ResponseCustomTool ¶
Bases: _ResponsesRequestModel
Select one registered server tool with the Responses custom-tool shape.
ResponseCustomToolCallInput ¶
Bases: _ResponsesRequestModel
A custom-tool call replayed from a previous Response.
ResponseCustomToolCallOutputInput ¶
Bases: _ResponsesRequestModel
A string result replayed for a preceding custom-tool call.
ResponseFunctionCallInput ¶
Bases: _ResponsesRequestModel
A function call replayed from a previous Response.
ResponseFunctionCallOutputInput ¶
Bases: _ResponsesRequestModel
Client output for a preceding function call.
ResponseFunctionTool ¶
Bases: _ResponsesRequestModel
A client-supplied function available to the graph.
ResponseInputFile ¶
Bases: _ResponsesRequestModel
One file stored in the configured OpenAI Files service.
ResponseInputMessage ¶
Bases: _ResponsesRequestModel
A standard OpenAI role message provided as input.
phase is accepted for every role and used only for assistant messages.
See https://developers.openai.com/api/reference/resources/responses.
ResponseInputText ¶
Bases: _ResponsesRequestModel
One plain-text input content part.
ResponseNamedToolChoice ¶
Bases: _ResponsesRequestModel
Require one named function or custom tool.
ResponseOutputMessageInput ¶
Bases: _ResponsesRequestModel
A terminal assistant output message replayed as input.
ResponseOutputTextInput ¶
Bases: _ResponsesRequestModel
Plain output text replayed from a previous assistant message.
ResponseRefusalInput ¶
Bases: _ResponsesRequestModel
A model refusal replayed from an assistant message.
ResponseTextConfig ¶
Bases: _ResponsesRequestModel
Plain-text response configuration.
ResponseTextFormat ¶
Bases: _ResponsesRequestModel
The supported plain-text output format.
ResponseURLCitationInput ¶
Bases: _ResponsesRequestModel
A URL citation replayed with assistant output text.
ResponseWebSearchActionInput ¶
Bases: _ResponsesRequestModel
The query action produced by LGOS's supported web-search tool.
ResponseWebSearchCallInput ¶
Bases: _ResponsesRequestModel
A web-search call replayed from a previous Response.
ResponseWebSearchTool ¶
Bases: _ResponsesRequestModel
Select the graph's OpenAI-compatible web-search capability.
server_tools ¶
Translate LGOS-executed tools into native Responses output items.
ServerToolTracker ¶
Correlate root-graph server-tool calls with their ToolMessages.
Source code in src/langgraph_openai_serve/api/responses/server_tools.py
client_function_calls ¶
Return final function calls that belong to the client.
Source code in src/langgraph_openai_serve/api/responses/server_tools.py
ensure_complete ¶
Reject a response whose selected call has no graph-produced result.
Source code in src/langgraph_openai_serve/api/responses/server_tools.py
items ¶
Yield public tool items represented by one root graph update.
Yields:
| Type | Description |
|---|---|
ServerToolItem
|
Selected calls and graph-produced results. |
Source code in src/langgraph_openai_serve/api/responses/server_tools.py
service ¶
Prepare and execute graph runs for OpenAI Responses.
collect_response
async
¶
Build one non-streaming Response from the graph's durable output.
Source code in src/langgraph_openai_serve/api/responses/service.py
prepare_response_run
async
¶
Validate a Responses request and prepare its graph run.
A background run passes the interrupt run_id it chose at submission.
Source code in src/langgraph_openai_serve/api/responses/service.py
stream_response
async
¶
Stream one prepared graph run as a typed Responses lifecycle.
Yields:
| Type | Description |
|---|---|
AsyncGenerator[str, None]
|
Named, compact Responses SSE frames. |
Source code in src/langgraph_openai_serve/api/responses/service.py
views ¶
OpenAI-compatible Responses router.
cancel_response
async
¶
Cancel one authorized active background Response.
Source code in src/langgraph_openai_serve/api/responses/views.py
create_response
async
¶
create_response(
response_request,
graph_registry,
checkpoint_scope,
background,
stream_owner,
idempotency_key=None,
)
Create one OpenAI Response, as JSON, an SSE stream, or a background run.
Source code in src/langgraph_openai_serve/api/responses/views.py
retrieve_response
async
¶
Retrieve one authorized background Response snapshot.
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. The producer
runs as a TaskStream, which request cleanup stops whether or not Starlette
is still consuming it.
StreamOwner ¶
Own the producer task and prepared run of one streaming request.
Source code in src/langgraph_openai_serve/api/streaming.py
aclose
async
¶
Stop the producer, then close the run it may not have reached.
Source code in src/langgraph_openai_serve/api/streaming.py
start ¶
Stream source as SSE and close run when the request ends.
Source code in src/langgraph_openai_serve/api/streaming.py
tools ¶
Shared function-call decoding for the OpenAI protocol adapters.
decode_function_call ¶
Parse once, preserving malformed arguments for the graph to handle.
Source code in src/langgraph_openai_serve/api/tools.py
background ¶
Polling-only background Responses executed by a pluggable engine.
BackgroundBackend ¶
BackgroundJob ¶
Bases: BaseModel
A validated request and the server-owned context that executes it.
BackgroundRun ¶
Bases: BaseModel
An engine's current view of one submitted job.
snapshot ¶
Return the public Response for the run's current state.
Source code in src/langgraph_openai_serve/background.py
InMemoryBackgroundBackend ¶
Run background jobs as tasks of this application process.
For development and tests: runs stay in memory until the process exits.
Source code in src/langgraph_openai_serve/background.py
cancel
async
¶
Mark an active run cancelled and cancel its task.
Source code in src/langgraph_openai_serve/background.py
get
async
¶
lifespan
async
¶
Own the execution tasks for one ASGI application lifespan.
Source code in src/langgraph_openai_serve/background.py
submit
async
¶
Start one task, or return the run holding the job's key.
Source code in src/langgraph_openai_serve/background.py
execute_background_job
async
¶
Execute one job through the foreground Responses path.
Source code in src/langgraph_openai_serve/background.py
cli ¶
The lgos command: serve a graph registry or run its Hatchet worker.
main ¶
serve ¶
Serve REGISTRY ($LGOS_REGISTRY), a module:attribute factory, with Uvicorn.
Source code in src/langgraph_openai_serve/cli.py
worker ¶
Run background Responses for REGISTRY ($LGOS_REGISTRY) on Hatchet.
Source code in src/langgraph_openai_serve/cli.py
core ¶
errors ¶
OpenAI-compatible error responses.
GraphError ¶
Bases: RuntimeError
Raised when a graph's configuration or output cannot be served.
InvalidRequestError ¶
Bases: Exception
A request rejected with an OpenAI invalid_request_error envelope.
Source code in src/langgraph_openai_serve/core/errors.py
configure_openai_error_handlers ¶
Return every error from app as an OpenAI-compatible JSON envelope.
Source code in src/langgraph_openai_serve/core/errors.py
logging ¶
Request-scoped context for standard-library log records.
RequestContextFilter ¶
Bases: Filter
Add the active LGOS request fields to log records.
LGOS installs it on its own loggers. A host that installs it on a handler also enriches records from graph nodes, dependencies, and its own code.
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 needs a deterministic default so model discovery can advertise a complete, stable settings object.
default_values
classmethod
¶
Return the JSON defaults advertised by model discovery.
Source code in src/langgraph_openai_serve/graph/client_settings.py
json_schema
classmethod
¶
Return the JSON Schema advertised by model discovery.
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
events ¶
Status updates that graph nodes publish as Responses commentary.
status_description ¶
Return a status update's description, ignoring other custom stream data.
Source code in src/langgraph_openai_serve/graph/events.py
status_event ¶
Build a status update for a node to write with get_stream_writer().
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
¶
Fail at registration when a settings model cannot be advertised.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
validate_compiled_graph ¶
Fail at registration when a directly supplied graph cannot be served.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
validate_tool_ownership ¶
Keep the side that executes each advertised tool unambiguous.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
GraphRegistry
dataclass
¶
The graphs served as OpenAI models, keyed by model ID.
run_coordinator leases the interrupt runs of every interrupt-enabled
graph; use a shared coordinator when several processes serve these graphs.
__post_init__ ¶
Fail at startup for a registry the OpenAI routes cannot serve.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
get_graph ¶
Return the graph served as model.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
interrupt ¶
Durable LangGraph interrupts: run leases, run identity, and resume state.
InMemoryRunCoordinator ¶
Coordinate interrupt runs within one event loop.
Source code in src/langgraph_openai_serve/graph/interrupt.py
__call__
async
¶
Hold the lease for key or raise RunBusyError.
Source code in src/langgraph_openai_serve/graph/interrupt.py
InterruptResume
dataclass
¶
A complete set of interrupt answers for one run.
LangGraphInterruptBatch
dataclass
¶
The durable interrupts awaiting answers for one graph run.
RunBusyError ¶
Bases: InvalidRequestError
Raised when another request holds an interrupt run's lease.
Source code in src/langgraph_openai_serve/graph/interrupt.py
RunCoordinator ¶
Bases: Protocol
Acquire a lease that rejects, rather than queues, an occupied run.
Exiting the lease must release it even when the exit is cancelled, because run cleanup is abandoned after a deadline; shield an asynchronous release.
checkpoint_key ¶
Derive a fixed-length checkpoint thread ID for one scoped model run.
Source code in src/langgraph_openai_serve/graph/interrupt.py
delete_expired_interrupt_runs
async
¶
Delete paused interrupt runs whose latest pause is older than older_than.
Other threads in checkpointer are left alone, and a run whose lease is
held, such as one being resumed, is skipped until the next call.
Returns:
| Type | Description |
|---|---|
int
|
The number of deleted runs. |
Source code in src/langgraph_openai_serve/graph/interrupt.py
interrupt_batch ¶
Validate pending interrupts as JSON function-call arguments.
Source code in src/langgraph_openai_serve/graph/interrupt.py
resume_command
async
¶
Validate answers against the run's durable pending interrupts.
Source code in src/langgraph_openai_serve/graph/interrupt.py
request ¶
run ¶
Prepare one isolated LangGraph execution for the OpenAI API.
GraphRun
dataclass
¶
GraphRun(
request,
config,
graph,
inputs,
context,
runnable_config,
usage_callback,
interrupt=None,
_resources=AsyncExitStack(),
)
One prepared graph run and the resources it holds until closed.
An interrupt-enabled run holds its coordinator lease from preparation until
aclose(). Closing deletes the checkpoint thread of a run that executed
without pausing, so durable state exists only for pending interrupts.
__aenter__
async
¶
__aexit__
async
¶
aclose
async
¶
Apply checkpoint cleanup and release the lease; later calls do nothing.
When error ended the run, a cleanup failure is logged instead of
replacing it.
Source code in src/langgraph_openai_serve/graph/run.py
begin_execution ¶
hold
async
¶
keep_checkpoint ¶
langfuse_attributes ¶
Name this run's end user, session, and graph on its Langfuse observations.
Enter it where the graph's task starts. LangChain runs Langfuse's handler on worker threads with a copy of the caller's context, so the handler's own propagation reaches only the root observation, and the model calls carrying the run's cost would have no user (https://github.com/langfuse/langfuse/issues/16177).
Source code in src/langgraph_openai_serve/graph/run.py
usage_metadata ¶
Return provider-reported usage aggregated across the graph run.
Source code in src/langgraph_openai_serve/graph/run.py
InterruptRun
dataclass
¶
The durable identity of one interrupt-enabled run.
prepare_run
async
¶
prepare_run(
request,
messages,
graph_registry,
*,
resume=None,
run_id=None,
checkpoint_scope="default",
)
Resolve, lease, and build the inputs of one graph run.
An interrupt-enabled run continues resume.run_id, uses a server-chosen
run_id, or starts a new run.
Source code in src/langgraph_openai_serve/graph/run.py
runner ¶
Run LangGraph workflows from protocol-neutral requests and messages.
TaskStream ¶
Bases: Generic[_Item]
Produce an async generator's items from a dedicated asyncio task.
AnyIO cancels a scope again at every await, and LangGraph then leaves node tasks running once it runs them in the background: in parallel steps, or while a stream reads message or custom events or subgraphs. The producer task instead receives exactly one asyncio cancellation, however its consumer is cancelled.
Source code in src/langgraph_openai_serve/graph/runner.py
aclose
async
¶
Stop the producer, then raise the exception that ended it, if any.
Source code in src/langgraph_openai_serve/graph/runner.py
collect_run
async
¶
Execute a prepared run and return only its final output.
Source code in src/langgraph_openai_serve/graph/runner.py
run_langgraph
async
¶
Prepare, execute, and close one graph run for direct Python callers.
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 final assistant message or the pending interrupt batch. |
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, stream, and close one graph run for direct Python callers.
Yields:
| Type | Description |
|---|---|
AsyncGenerator[LangGraphStreamEvent, None]
|
Assistant text chunks, custom events, then the final output. |
Source code in src/langgraph_openai_serve/graph/runner.py
stream_run
async
¶
Execute a prepared run, ending with its final output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
run
|
GraphRun
|
The prepared run. |
required |
streaming
|
bool
|
Yield assistant text and custom events, including those of nested subgraphs. |
True
|
stream_updates
|
bool
|
Yield node updates; with |
False
|
Yields:
| Type | Description |
|---|---|
AsyncGenerator[LangGraphStreamEvent, None]
|
The requested intermediate events, then the final |
AsyncGenerator[LangGraphStreamEvent, None]
|
|
Source code in src/langgraph_openai_serve/graph/runner.py
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 | |
telemetry ¶
Report graph runs with the OpenTelemetry GenAI workflow conventions.
LGOS uses only the OpenTelemetry API, so nothing is recorded until the application configures an SDK.
invoke_workflow ¶
Record one graph execution as an invoke_workflow span and duration.
A run that ends before its output exists fails with its error.type:
an exception, a cancellation from a disconnecting client or a cancel
request, or a consumer closing the stream mid-run.
Yields:
| Type | Description |
|---|---|
Span
|
The run's span, which callers make current only around graph work. |
Source code in src/langgraph_openai_serve/graph/telemetry.py
integrations ¶
Optional infrastructure integrations for LangGraph OpenAI Serve.
hatchet ¶
Hatchet engine for background Responses.
HatchetBackgroundBackend ¶
Submit, read, and cancel background Responses as Hatchet task runs.
Source code in src/langgraph_openai_serve/integrations/hatchet.py
cancel
async
¶
get
async
¶
Read the run's input, status, and output from Hatchet.
Source code in src/langgraph_openai_serve/integrations/hatchet.py
submit
async
¶
Trigger the task, or return the run holding the job's key.
Source code in src/langgraph_openai_serve/integrations/hatchet.py
create_hatchet_task ¶
create_hatchet_task(
hatchet,
*,
name="lgos-background-response",
schedule_timeout=timedelta(minutes=30),
execution_timeout=timedelta(hours=1),
)
Register the background Response task in the API and worker processes.
The worker lifespan must yield the GraphRegistry the task executes.
The task is not retried: a failed Response is final, and the client may
create a new one.
Source code in src/langgraph_openai_serve/integrations/hatchet.py
langfuse ¶
Lazy construction for the optional Langfuse tracing integration.
get_langfuse_callback
cached
¶
Return the process-wide Langfuse callback, constructing it lazily.
Source code in src/langgraph_openai_serve/integrations/langfuse.py
trace_attributes ¶
Return Langfuse's context naming the end user, session, and trace.
Source code in src/langgraph_openai_serve/integrations/langfuse.py
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
¶
Hold a PostgreSQL advisory lock 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")
>>> registry = GraphRegistry(
... graphs={
... "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(registry=registry, app=app)
>>> 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 graphs to serve and their interrupt run coordinator. |
|
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 |
|---|---|---|---|
registry
|
GraphRegistry
|
The graphs to serve and their interrupt run coordinator. |
required |
app
|
FastAPI | None
|
The host FastAPI application to mount the OpenAI API on. If None, a new FastAPI app will be created. |
None
|
checkpoint_scope
|
Callable[[Request], str | Awaitable[str]] | None
|
Optional server-trusted resolver used to isolate interrupt checkpoints by deployment or authenticated principal. |
None
|
background
|
BackgroundBackend | None
|
Optional polling-only background backend. |
None
|
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.
server ¶
Serve a graph registry as a standalone application: lgos serve and lgos worker.
RegistryFactory
module-attribute
¶
RegistryFactory = Callable[
[ServerResources], GraphRegistry | AbstractAsyncContextManager[GraphRegistry]
]
Build the served graphs, or open them for the process lifetime.
ServerResources
dataclass
¶
Persistence shared by every graph one server process runs.
ServerSettings ¶
Bases: BaseSettings
Server settings read from explicit values and the process environment.
create_app ¶
Serve the factory's registry under the OpenAI prefix once the app starts.
Source code in src/langgraph_openai_serve/server/app.py
app ¶
The FastAPI application that lgos serve runs.
create_app ¶
Serve the factory's registry under the OpenAI prefix once the app starts.
Source code in src/langgraph_openai_serve/server/app.py
hatchet ¶
Hatchet background execution for the server and its worker process.
create_hatchet ¶
Create a client configured by the environment and traced when exporting.
Source code in src/langgraph_openai_serve/server/hatchet.py
create_hatchet_backend ¶
Build the API-side backend that submits, reads, and cancels runs.
Source code in src/langgraph_openai_serve/server/hatchet.py
run_worker ¶
Run background Responses for the same registry the API serves.
Source code in src/langgraph_openai_serve/server/hatchet.py
logging ¶
Structured logging on stdout for the server and worker processes.
configure_logging ¶
Install the logging configuration for a process that Uvicorn does not run.
logging_config ¶
Return a dictConfig that logs INFO from LGOS, Uvicorn, and the app.
Source code in src/langgraph_openai_serve/server/logging.py
runtime ¶
Persistence the server owns and passes to the application's registry.
RegistryFactory
module-attribute
¶
RegistryFactory = Callable[
[ServerResources], GraphRegistry | AbstractAsyncContextManager[GraphRegistry]
]
Build the served graphs, or open them for the process lifetime.
ServerResources
dataclass
¶
Persistence shared by every graph one server process runs.
expire_paused_runs
async
¶
Delete abandoned interrupt runs on an interval, like Agent Server's TTL.
Source code in src/langgraph_openai_serve/server/runtime.py
open_registry
async
¶
Build the registry, entering it when the factory owns resources.
Yields:
| Type | Description |
|---|---|
AsyncGenerator[GraphRegistry, None]
|
The registry to serve until the process stops. |
Source code in src/langgraph_openai_serve/server/runtime.py
open_resources
async
¶
Open PostgreSQL persistence, or process memory when no database is set.
Yields:
| Type | Description |
|---|---|
AsyncGenerator[ServerResources, None]
|
The checkpointer, store, and run coordinator for this process. |