Reference¶
OpenAI-Compatible API¶
Default prefix: /v1. Change it with LGOS_OPENAI_API_PREFIX or
bind_openai_api(prefix=...).
| Method | Path | Purpose |
|---|---|---|
GET |
/v1/models |
List standard summaries for registered graph models. |
GET |
/v1/models/{model} |
Retrieve one model with optional LGOS discovery metadata. |
POST |
/v1/chat/completions |
Run a graph through OpenAI chat completions. |
GET |
/v1/health |
Health check. |
FastAPI docs for the mounted OpenAI app are disabled by default. Set
LGOS_OPENAI_API_DOCS_ENABLED=true to expose {prefix}/docs, {prefix}/redoc,
and {prefix}/openapi.json.
Settings¶
Package settings:
| Setting | Default | Notes |
|---|---|---|
LGOS_OPENAI_API_PREFIX |
/v1 |
Must start with /; trailing slash is normalized. |
LGOS_OPENAI_API_DOCS_ENABLED |
false |
Enables docs only for the mounted OpenAI app. |
Demo API and graph settings:
| Setting | Default | Notes |
|---|---|---|
DEMO_OPENAI_BASE_URL |
https://api.openai.com/v1 |
Upstream OpenAI-compatible base URL for LLM-backed demo graphs. |
DEMO_OPENAI_API_KEY |
DUMMY |
Upstream API key for LLM-backed demo graphs. |
DEMO_OPENAI_MODEL |
gpt-5.4-mini |
Upstream generation model for LLM-backed demo graphs. |
DEMO_OPENAI_EMBEDDING_MODEL |
text-embedding-3-small |
Embedding model used by the lgos-rag demo graph. |
DEMO_POSTGRES_URI |
postgresql://lgos:lgos@localhost:5432/lgos |
Checkpoint database used by the interruptible demo graph. |
Settings for optional clients and gateways are documented under Integrations.
Public API¶
Use LanggraphOpenaiServe to bind OpenAI-compatible routes to a FastAPI app.
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.
GraphConfig accepts:
graph: compiled graph, sync factory, or async factory.streamable_node_names: node names whose streamedAIMessageChunkvalues are forwarded to clients.features:GraphFeaturevalues that enable optional server behavior.client_settings: explicit publicClientSettingsmodel class advertised by model retrieval.runtime_callbacks: callbacks included in the LangGraphRunnableConfig.request_to_input(request, messages): custom OpenAI request to graph input.context_factory(request, client_settings): compose the final typed LangGraph runtime context from server-owned values and optional validated public settings.output_to_text(output): custom graph output to assistant text.
When both are configured, LGOS validates the public settings first and passes
them to context_factory. Without a factory, the validated settings instance is
the runtime context, so the graph must use that settings model as its
context_schema. A factory may return None; every non-null result requires a
graph context schema. LGOS passes server-owned factory results to LangGraph
without rebuilding them. LangGraph's native
runtime-context handling
constructs mapping values through dataclass and Pydantic context schemas and
trusts existing instances. The factory owns the validity of instances it
creates. Graphs should access context from an injected Runtime[Context].
Runtime context is separate from RunnableConfig:
| Value | LGOS/LangGraph path | Intended use |
|---|---|---|
| Graph input | graph.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. |
| Checkpoint thread | metadata.langgraph_thread_id → config["configurable"]["thread_id"] |
Load, save, interrupt, and resume checkpoint state. |
LGOS assembles runnable config from runtime_callbacks and, when present, the
checkpoint 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.
The same features set drives runtime behavior and the versioned
langgraph_openai_serve.features extension returned by
GET /v1/models/{model}. GraphFeature.INTERRUPTS enables and advertises the
interrupt/resume flow.
Runtime Settings¶
Subclass ClientSettings to publish only fields deliberately selected by the
server author. LGOS never inspects or publishes the LangGraph context schema:
from pydantic import Field
from langgraph_openai_serve import ClientSettings
class PublicSettings(ClientSettings):
use_history: bool = Field(default=True, title="Use conversation history")
Pass this model as GraphConfig.client_settings and use it as the graph's context
schema when it is the complete runtime context. Every public field must have a
default. Registration rejects subclasses that change the inherited strict,
frozen, extra-forbid, or default-validation behavior, as well as fields excluded
from Pydantic serialization.
All public fields travel together as compact JSON text in the
metadata.langgraph_runtime_settings string. Clients omit values equal to the advertised
defaults. System instructions remain ordinary OpenAI messages and are
independent of ClientSettings; native Chat Completions fields keep their
standard request semantics.
LGOS validates defaults and generates the discovery JSON Schema when the graph
is registered, then validates settings on every request. Without
context_factory, the settings become Runtime.context. A factory can instead
combine them with server-derived identity, authorization, database clients, and
other dependencies.
The serialized descriptor appears only on model retrieval as
langgraph_openai_serve.client_settings, with independent schema_version,
json_schema, and defaults fields. All client settings use the fixed
metadata.langgraph_runtime_settings envelope. Clients use the descriptor's
validated defaults object as the baseline; default keywords within the
generated JSON Schema are annotations, not the runtime baseline.
See Configure LangGraph Runtime Settings for the runtime settings flow, and Runtime Settings for the request lifecycle.
Interrupt-enabled graphs must be compiled with a LangGraph checkpointer and
requests must include metadata={"langgraph_thread_id": "<client-chat-id>"}.
Use a durable checkpointer in production.
Client Stream Events¶
Inside a graph node or tool, mark a passive client notification as explicitly
public with client_event():
from langgraph.config import get_stream_writer
from langgraph_openai_serve import client_event
get_stream_writer()(
client_event(
"progress",
{
"stage": "retrieval",
"completed": 2,
"total": 5,
"message": "Searching documents",
},
namespace=("research",),
)
)
The v1 vocabulary is status, progress, and artifact. Event data must be
JSON-safe, and every namespace segment must be a string. Keep payloads small and
represent large artifacts by an ID or URL. The namespace is a stable,
author-defined path; LGOS does not expose LangGraph's dynamic execution
namespace.
Events are streaming-only and opt-in. Clients request them with
metadata={"langgraph_stream_events": "v1"} and receive a versioned
langgraph_openai_serve property on an otherwise standard Chat Completions
chunk. Missing and unsupported versions produce the ordinary strict stream.
Unknown custom events remain available only to direct runner consumers.
See Client stream events for the wire contract and OpenAI clients for consumption.
Citation Events¶
Inside a graph node or tool, emit a citation with LangGraph's stream writer:
from langgraph.config import get_stream_writer
from langgraph_openai_serve import citation_event
get_stream_writer()(
citation_event(
url="https://example.com/source",
title="Example source",
span=(10, 14),
)
)
span uses Python's half-open convention, so text[10:14] returns the cited
text. LGOS converts it to OpenAI's inclusive end_index at the event boundary.
Use citation_slice(annotation, text) to validate received indices and convert
them back to a Python slice. Citation events must refer to the final rendered
assistant text.
See Citation ownership for transport and client behavior.
The graph runner preserves LangGraph's native CustomStreamPart values,
including their execution namespace. Other event types remain available to
direct runner consumers through langgraph_openai_serve.graph.runner.
Demo Models¶
make run-demo-api registers:
simple-graph(runtime settings for conversation history and intended audience)citation-events(structured URL citations alongside portable Markdown)lgos-ragcustom-input-output-contextadvanced-mcp-toolscomplex-subgraphscustom-event-showcase(status, progress, and artifact stream events)interruptible-approval
Local Commands¶
UI and gateway setup is documented under Integrations.
langgraph-openai-serve package.
ClientSettings ¶
Bases: BaseModel
Base class for settings that clients may configure for a graph.
Subclasses define the complete public contract. Every field must have a valid JSON-serializable default so model discovery can advertise a usable settings object without maintaining a second defaults mapping.
defaults
classmethod
¶
Return a deep copy of the registration-validated defaults.
validate_request
classmethod
¶
Read and validate this model's values from an OpenAI request.
Source code in src/langgraph_openai_serve/graph/client_settings.py
GraphConfig ¶
Bases: BaseModel
build_context
async
¶
Build the LangGraph runtime context for a request.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
build_input
async
¶
Build the native graph input for a chat completion request.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
render_output
async
¶
Convert native graph output into assistant response text.
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
get_graph ¶
Get a graph by its name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the graph to retrieve. |
required |
Returns:
| Type | Description |
|---|---|
GraphConfig
|
The graph configuration associated with the given name. |
Raises:
| Type | Description |
|---|---|
GraphNotFoundError
|
If the graph name is not found in the registry. |
Source code in src/langgraph_openai_serve/graph/graph_registry.py
get_graph_names ¶
register ¶
Add or replace one graph through the validated registry boundary.
LanggraphOpenaiServe ¶
Server class to connect LangGraph instances with an OpenAI-compatible API.
This class serves as a bridge between LangGraph instances and an OpenAI-compatible API. It allows users to register their LangGraph instances and expose them through an OpenAI-compatible sub-application mounted on a FastAPI host app.
Attributes:
| Name | Type | Description |
|---|---|---|
app |
FastAPI
|
The host FastAPI application to mount the OpenAI API on. |
graph_registry |
The populated GraphRegistry containing the graphs to serve. |
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 |
Raises:
| Type | Description |
|---|---|
TypeError
|
If graphs is not a GraphRegistry instance. |
Source code in src/langgraph_openai_serve/openai_server.py
bind_openai_api ¶
Mount OpenAI-compatible endpoints on the host FastAPI app.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str | None
|
Optional; The URL prefix for the OpenAI-compatible endpoints. Defaults to settings.OPENAI_API_PREFIX. |
None
|
Source code in src/langgraph_openai_serve/openai_server.py
citation_event ¶
Build an OpenAI URL citation from a Python-style half-open span.
Source code in src/langgraph_openai_serve/graph/events.py
citation_slice ¶
Convert an OpenAI inclusive citation span to a validated Python slice.
Source code in src/langgraph_openai_serve/graph/events.py
client_event ¶
Build an explicitly public, JSON-safe client stream event.
Source code in src/langgraph_openai_serve/graph/events.py
api ¶
chat ¶
schemas ¶
Pydantic models for the OpenAI API.
This module defines Pydantic models that match the OpenAI API request and response formats.
ChatCompletionRequest ¶
Bases: BaseModel
Model for a chat completion request.
reject_legacy_fields
classmethod
¶
Reject deprecated Chat Completions function parameters.
Source code in src/langgraph_openai_serve/api/chat/schemas.py
ChatCompletionRequestMessage ¶
Bases: BaseModel
Model for a chat completion request message.
reject_legacy_fields
classmethod
¶
Reject the deprecated singular Chat Completions function call.
Source code in src/langgraph_openai_serve/api/chat/schemas.py
ChatCompletionResponse ¶
Bases: BaseModel
Model for a chat completion response.
ChatCompletionResponseChoice ¶
Bases: BaseModel
Model for a chat completion response choice.
ChatCompletionResponseMessage ¶
Bases: BaseModel
Model for a chat completion response message.
ChatCompletionStreamResponse ¶
Bases: BaseModel
Model for a chat completion stream response.
ChatCompletionStreamResponseChoice ¶
Bases: BaseModel
Model for a chat completion stream response choice.
ChatCompletionStreamResponseDelta ¶
Bases: BaseModel
Model for a chat completion stream response delta.
ChatCompletionStreamToolCall ¶
Bases: BaseModel
Model for a streaming tool call delta.
ChatCompletionStreamToolCallFunction ¶
Bases: BaseModel
Model for a streaming tool call function delta.
FunctionDefinition ¶
Bases: BaseModel
Model for a function definition.
Role ¶
Bases: str, Enum
Role options for chat messages.
Tool ¶
Bases: BaseModel
Model for a tool.
ToolCall ¶
Bases: BaseModel
Model for a tool call.
ToolCallFunction ¶
Bases: BaseModel
Model for a tool call function.
ToolFunction ¶
Bases: BaseModel
Model for a tool function.
UsageInfo ¶
Bases: BaseModel
Model for usage information.
service ¶
Chat completion service.
ChatCompletionService ¶
Service for handling 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.
Source code in src/langgraph_openai_serve/api/chat/service.py
utils ¶
events ¶
Adapt generic LangGraph custom events to OpenAI chat fields.
annotation_from_custom_event ¶
Validate a recognized OpenAI annotation custom event.
Source code in src/langgraph_openai_serve/api/chat/utils/events.py
client_event_extension_from_custom_event ¶
Validate an explicitly public event and build its stream extension.
Source code in src/langgraph_openai_serve/api/chat/utils/events.py
stream_events_requested ¶
Return whether a request opted into the supported event stream version.
Source code in src/langgraph_openai_serve/api/chat/utils/events.py
interrupts ¶
OpenAI chat protocol helpers for LangGraph interrupts.
InvalidResumeRequestError ¶
Bases: ValueError
Raised when a tool response cannot be used to resume an interrupt.
responses ¶
OpenAI chat response builders.
ChatCompletionStreamResponseBuilder ¶
Build OpenAI-compatible chat completion SSE chunks.
Source code in src/langgraph_openai_serve/api/chat/utils/responses.py
Build an empty-delta chunk carrying the opt-in event extension.
Source code in src/langgraph_openai_serve/api/chat/utils/responses.py
chat_completion_response ¶
Build a non-streaming OpenAI-compatible chat completion response.
Source code in src/langgraph_openai_serve/api/chat/utils/responses.py
views ¶
Chat completion router.
This module provides the FastAPI router for the chat completion endpoint, implementing an OpenAI-compatible interface.
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 |
service
|
Annotated[ChatCompletionService, Depends(ChatCompletionService)]
|
The chat completion service dependency. |
required |
stream_owner
|
Annotated[_StreamOwner, Depends(_stream_owner_dependency, scope=request)]
|
The request-scoped streaming task owner. |
required |
Returns:
| Type | Description |
|---|---|
StreamingResponse | ChatCompletionResponse
|
A chat completion response, either as a complete response or as a stream. |
Source code in src/langgraph_openai_serve/api/chat/views.py
models ¶
schemas ¶
LangGraphModelExtension ¶
Bases: BaseModel
Versioned LangGraph OpenAI Serve model extension.
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 ¶
Model service.
This module provides a service for handling OpenAI model information.
ModelService ¶
Service for handling model operations.
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.
get_graph_registry_dependency ¶
list_models ¶
Get a list of available models.
Source code in src/langgraph_openai_serve/api/models/views.py
retrieve_model ¶
Retrieve one registered graph as an OpenAI model.
Source code in src/langgraph_openai_serve/api/models/views.py
core ¶
errors ¶
OpenAI-compatible error response helpers.
OpenAIHTTPException ¶
Bases: HTTPException
HTTP exception that carries OpenAI error object metadata.
Source code in src/langgraph_openai_serve/core/errors.py
configure_openai_error_handlers ¶
Install OpenAI-compatible JSON error handlers on a FastAPI app.
Source code in src/langgraph_openai_serve/core/errors.py
settings ¶
Settings ¶
Bases: BaseSettings
This class is used to load environment variables either from environment or from a .env file and store them as class attributes. NOTE: - environment variables will always take priority over values loaded from a dotenv file - environment variable names are case-insensitive - environment variable type is inferred from the type hint of the class attribute - For environment variables that are not set, a default value should be provided
For more info, see the related pydantic docs: https://docs.pydantic.dev/latest/concepts/pydantic_settings
check_langfuse_settings
classmethod
¶
Validate Langfuse settings if enabled.
Source code in src/langgraph_openai_serve/core/settings.py
validate_openai_api_prefix
classmethod
¶
Validate the mount prefix for OpenAI-compatible endpoints.
normalize_openai_api_prefix ¶
Normalize and validate the OpenAI-compatible API mount prefix.
Source code in src/langgraph_openai_serve/core/settings.py
graph ¶
Service package for the LangGraph OpenAI compatible API.
client_settings ¶
Public graph settings transported through standard OpenAI requests.
ClientSettings ¶
Bases: BaseModel
Base class for settings that clients may configure for a graph.
Subclasses define the complete public contract. Every field must have a valid JSON-serializable default so model discovery can advertise a usable settings object without maintaining a second defaults mapping.
defaults
classmethod
¶
Return a deep copy of the registration-validated defaults.
validate_request
classmethod
¶
Read and validate this model's values from an OpenAI request.
Source code in src/langgraph_openai_serve/graph/client_settings.py
ClientSettingsValidationError ¶
client_settings_default_values ¶
Return a fresh copy of the registration-validated JSON defaults.
Source code in src/langgraph_openai_serve/graph/client_settings.py
client_settings_json_schema ¶
Return a fresh copy of the registration-validated discovery schema.
Source code in src/langgraph_openai_serve/graph/client_settings.py
validate_client_settings_model ¶
Validate the registration-time contract of a settings model.
Source code in src/langgraph_openai_serve/graph/client_settings.py
events ¶
Public events emitted by LangGraph nodes and tools.
citation_event ¶
Build an OpenAI URL citation from a Python-style half-open span.
Source code in src/langgraph_openai_serve/graph/events.py
citation_slice ¶
Convert an OpenAI inclusive citation span to a validated Python slice.
Source code in src/langgraph_openai_serve/graph/events.py
client_event ¶
Build an explicitly public, JSON-safe client stream event.
Source code in src/langgraph_openai_serve/graph/events.py
client_event_extension ¶
Build a stream extension from validated public custom stream data.
Source code in src/langgraph_openai_serve/graph/events.py
graph_registry ¶
GraphConfig ¶
Bases: BaseModel
build_context
async
¶
Build the LangGraph runtime context for a request.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
build_input
async
¶
Build the native graph input for a chat completion request.
Source code in src/langgraph_openai_serve/graph/graph_registry.py
render_output
async
¶
Convert native graph output into assistant response text.
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
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.
runner ¶
Run LangGraph workflows behind the OpenAI-compatible chat API.
LangGraphInvocation
dataclass
¶
A graph result together with custom events emitted during its run.
extract_stream_interrupt ¶
Extract interrupt metadata from a LangGraph v2 values stream part.
Source code in src/langgraph_openai_serve/graph/runner.py
invoke_run
async
¶
Invoke a graph and collect its custom events.
Source code in src/langgraph_openai_serve/graph/runner.py
legacy_output ¶
Match the plain output shape adapters received from LangGraph v1.
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:
>>> invocation = await run_langgraph("my-model", messages, registry)
>>> print(invocation.output)
>>> print(invocation.custom_events)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
The name of the model to use, which also determines which graph to use. |
required |
messages
|
list[ChatCompletionRequestMessage]
|
A list of messages to process through the LangGraph. |
required |
graph_registry
|
GraphRegistry
|
The GraphRegistry instance containing registered graphs. |
required |
request
|
ChatCompletionRequest | None
|
The complete chat completion request passed to graph adapters. |
None
|
Returns:
| Type | Description |
|---|---|
LangGraphInvocation
|
The graph output and custom events emitted during the invocation. |
Source code in src/langgraph_openai_serve/graph/runner.py
run_langgraph_stream
async
¶
Prepare and stream a graph for direct runner callers.
This convenience wrapper combines :func:prepare_run and :func:stream_run.
The HTTP route prepares its run before starting the streaming response so
preparation errors remain normal OpenAI-compatible HTTP errors; its service
therefore calls stream_run directly with that prepared run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
The name of the model (graph) to run. |
required |
messages
|
list[ChatCompletionRequestMessage]
|
A list of OpenAI-compatible messages. |
required |
graph_registry
|
GraphRegistry
|
The registry containing the graph configurations. |
required |
request
|
ChatCompletionRequest | None
|
The complete chat completion request passed to graph adapters. |
None
|
Yields:
| Type | Description |
|---|---|
AsyncGenerator[LangGraphStreamEvent, None]
|
Assistant text chunks, custom events, or LangGraph interrupts. |
Source code in src/langgraph_openai_serve/graph/runner.py
stream_run
async
¶
Stream an already prepared LangGraph invocation.
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
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),
... "simple_graph_2": GraphConfig(graph=simple_graph_2),
... }
... )
>>> 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. |
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 |
Raises:
| Type | Description |
|---|---|
TypeError
|
If graphs is not a GraphRegistry instance. |
Source code in src/langgraph_openai_serve/openai_server.py
bind_openai_api ¶
Mount OpenAI-compatible endpoints on the host FastAPI app.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str | None
|
Optional; The URL prefix for the OpenAI-compatible endpoints. Defaults to settings.OPENAI_API_PREFIX. |
None
|
Source code in src/langgraph_openai_serve/openai_server.py
schemas ¶
Models package for the LangGraph OpenAI compatible API.
utils ¶
Utility functions.
fake_llm ¶
Shared fake streaming model helpers for demos and tests.
stream_fake_chat_response
async
¶
Stream a deterministic fake chat response and collect it for graph state.
Source code in src/langgraph_openai_serve/utils/fake_llm.py
message ¶
InvalidChatMessageError ¶
Bases: ValueError
Raised when a chat message is missing a role-specific required field.
convert_to_lc_messages ¶
Convert OpenAI messages to LangChain messages.
This function converts a list of OpenAI-compatible message objects to their LangChain equivalents for use with LangGraph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
list[ChatCompletionRequestMessage]
|
A list of OpenAI chat completion request messages to convert. |
required |
Returns:
| Type | Description |
|---|---|
list[BaseMessage]
|
A list of LangChain message objects. |