FastAPI router factory for OpenAI-compatible Chat Completions, Responses, and Files upload endpoints.
Provides configurable router factories for OpenAI-style APIs, with support for
streaming (SSE), non-streaming responses, tool calling, reasoning content,
configurable hooks, custom chunk mapping, and callback-driven file upload handling.
Create an OpenAI-compatible Chat Completions server in a few lines. Both sync and async
callables are supported -- sync callables are automatically executed in a thread pool
so they never block the async event loop.
from fastapi import FastAPI
from fastapi_openai_compat import CompletionResult, MessageParam, create_chat_completion_router
def list_models() -> list[str]:
return ["my-pipeline"]
def run_completion(model: str, messages: list[MessageParam], body: dict) -> CompletionResult:
# Your (potentially blocking) pipeline execution logic here
return "Hello from Haystack!"
app = FastAPI()
router = create_chat_completion_router(
list_models=list_models,
run_completion=run_completion,
)
app.include_router(router)
The type aliases MessageParam, InputItem, and OutputItem are all
dict[str, Any] -- not Pydantic models. This is a deliberate design
choice:
Forward-compatibility. OpenAI regularly adds new message types, content
part types, and input/output item types. A strict union of Pydantic models
would reject unknown types and require a library release for every API
change. Plain dicts let your callbacks handle new types immediately.
Pass-through design. This library validates the request envelope
(correct top-level structure) and passes the inner items through to your
callback unchanged. Domain-specific validation belongs in your callback or
a pre-hook, not in the transport layer.
Consistency. Both Chat Completions (messages) and Responses API
(input_items, output) follow the same pattern, so you have a single
mental model for both.
The aliases exist to give you IDE hints and self-documenting signatures.
Each alias's docstring lists the common dict shapes you'll encounter -- check
them in your IDE or in the
source.
The run_completion callable
The run_completion callable receives three arguments:
Argument
Type
Description
model
str
The model name from the request (e.g. "my-pipeline").
The full request body, including all extra parameters (e.g. temperature, max_tokens, stream, metadata, tools).
The request model accepts any additional fields beyond model, messages, and stream.
These extra parameters are forwarded as-is in the body dict, so you can use them
however you need without any library changes.
For example, you can access metadata and any other extra field from body:
The metadata field in the response works because ChatCompletion also allows extra fields,
so you can attach any additional data to the response object.
The return type determines how the response is formatted:
Return type
Behavior
str
Wrapped automatically into a ChatCompletion response.
Generator
Each yielded chunk is converted to a chat.completion.chunk SSE message.
AsyncGenerator
Same as Generator, but async.
ChatCompletion
Returned as-is for full control over the response.
Response types
Returning a string
The simplest option -- return a plain string and the library wraps it as a
complete ChatCompletion response automatically:
Return a generator to stream responses token by token via SSE.
Each yielded string is automatically wrapped into a chat.completion.chunk message --
you only need to yield the text content, the library handles the SSE wire format.
A finish_reason="stop" sentinel is appended automatically at the end of the stream.
Your run_completion should check body.get("stream", False) to decide whether
to return a generator or a plain string:
from collections.abc import Generator
def run_completion(model: str, messages: list[MessageParam], body: dict) -> CompletionResult:
last_msg = messages[-1]["content"]
if body.get("stream", False):
def stream() -> Generator[str, None, None]:
for word in last_msg.split():
yield word + " "
return stream()
return f"You said: {last_msg}"
Async generators work the same way:
from collections.abc import AsyncGenerator
async def run_completion(model: str, messages: list[MessageParam], body: dict) -> CompletionResult:
async def stream() -> AsyncGenerator[str, None]:
for word in ["Hello", " from", " Haystack", "!"]:
yield word
return stream()
Returning a ChatCompletion
For full control over the response (e.g. custom usage, finish_reason, or system_fingerprint),
return a ChatCompletion object directly:
When using Haystack's StreamingChunk (requires pip install fastapi-openai-compat[haystack]),
tool call deltas and finish reasons are handled automatically via duck typing:
Converts ToolCallDelta objects to OpenAI wire format (tool_calls[].function.name/arguments)
Propagates finish_reason from chunks (e.g. "stop", "tool_calls", "length")
Only auto-appends finish_reason="stop" if no chunk already carried a finish reason
Works via duck typing -- any object with tool_calls and finish_reason attributes is supported
Reasoning content
When streaming, chunks with a reasoning attribute are emitted as
reasoning_content on the message delta (the
DeepSeek convention,
widely adopted by OpenAI-compatible clients). This is detected via duck
typing -- any object with a .reasoning attribute works.
With Haystack's StreamingChunk and ReasoningContent:
from haystack.dataclasses import StreamingChunk
from haystack.dataclasses.streaming_chunk import ReasoningContent
def run_completion(model: str, messages: list[MessageParam], body: dict) -> CompletionResult:
def stream():
yield StreamingChunk(content="", reasoning=ReasoningContent(reasoning_text="Let me think..."))
yield StreamingChunk(content="", reasoning=ReasoningContent(reasoning_text=" The answer is 42."))
yield StreamingChunk(content="The answer is 42.")
return stream()
The resulting SSE stream contains chunks with reasoning_content on the delta
for reasoning tokens, followed by regular content deltas for the visible
answer:
{"choices": [{"delta": {"reasoning_content": "Let me think...", "content": null}}]}
{"choices": [{"delta": {"reasoning_content": " The answer is 42.", "content": null}}]}
{"choices": [{"delta": {"content": "The answer is 42."}}]}
Any custom object works too -- the library checks for chunk.reasoning and
extracts text via .reasoning_text (falling back to str()):
You can yield custom SSE events alongside regular chat completion chunks. This is useful
for sending side-channel data to clients like Open WebUI --
status updates, notifications, source citations, etc.
Any object with a .to_event_dict() method is recognized as a custom event and serialized
as data: {"event": {...}} in the SSE stream. Custom events don't interfere with
chat completion chunks or the finish_reason tracking.
from collections.abc import Generator
from fastapi_openai_compat import CompletionResult
class StatusEvent:
def __init__(self, description: str, done: bool = False):
self.description = description
self.done = done
def to_event_dict(self) -> dict:
return {"type": "status", "data": {"description": self.description, "done": self.done}}
def run_completion(model: str, messages: list[MessageParam], body: dict) -> CompletionResult:
def stream() -> Generator[str | StatusEvent, None, None]:
yield StatusEvent("Processing your request...")
for word in ["Hello", " from", " Haystack", "!"]:
yield word
yield StatusEvent("Done", done=True)
return stream()
This works via duck typing -- any object implementing to_event_dict() -> dict is supported.
The protocol is compatible with Hayhooks' Open WebUI events.
Hooks
You can inject pre/post hooks to modify requests and results (transformer hooks)
or to observe them without modification (observer hooks). Both sync and async
hooks are supported.
Transformer hooks
Return a modified value to transform the request or result:
from fastapi_openai_compat import ChatRequest, CompletionResult
async def pre_hook(request: ChatRequest) -> ChatRequest:
# e.g. inject system prompts, validate, rate-limit
return request
async def post_hook(result: CompletionResult) -> CompletionResult:
# e.g. transform, filter
return result
router = create_chat_completion_router(
list_models=list_models,
run_completion=run_completion,
pre_hook=pre_hook,
post_hook=post_hook,
)
Observer hooks
Return None to observe without modifying (useful for logging, metrics, etc.):
By default the router handles plain str chunks and objects with a .content
attribute (e.g. Haystack StreamingChunk). If your pipeline streams a different
type, provide a chunk_mapper to extract text content:
The run_response callable receives three arguments:
Argument
Type
Description
model
str
The model name from the request.
input_items
list[InputItem]
Normalized input items (see A note on dict-based types). String shorthand is converted to a message item; None becomes [].
body
dict
The full request body, including all extra parameters (e.g. temperature, tools, instructions).
The return type determines how the response is formatted:
Return type
Behavior
str
Wrapped into a Response with a single text output message.
Generator
Each yielded chunk is emitted as named SSE events (response.output_text.delta, etc.).
AsyncGenerator
Same as Generator, but async.
Response
Returned as-is for full control over the response.
Streaming text
Return a generator to stream text via named SSE events. Each yielded string
becomes a response.output_text.delta event. The library handles all the
surrounding lifecycle events (response.created, response.in_progress,
response.output_item.added, response.completed, etc.) automatically.
from collections.abc import Generator
def run_response(model: str, input_items: list[InputItem], body: dict) -> ResponseResult:
if body.get("stream", False):
def stream() -> Generator[str, None, None]:
for word in ["Hello", " from", " streaming", "!"]:
yield word
return stream()
return "Hello!"
Streaming function calls
Yield objects with function_call_id, function_call_name, and
function_call_arguments attributes to stream function call events.
The library emits response.function_call_arguments.delta events during
streaming and a response.output_item.done event when the call completes.
Yield chunks with a reasoning attribute to stream reasoning output items.
The library emits the proper OpenAI
reasoning summary events
(response.reasoning_summary_part.added, response.reasoning_summary_text.delta,
response.reasoning_summary_text.done, response.reasoning_summary_part.done)
and produces a type: "reasoning" output item with a summary array in the
completed response.
from haystack.dataclasses import StreamingChunk
from haystack.dataclasses.streaming_chunk import ReasoningContent
def run_response(model: str, input_items: list[InputItem], body: dict) -> ResponseResult:
def stream():
yield StreamingChunk(content="", reasoning=ReasoningContent(reasoning_text="Step 1: "))
yield StreamingChunk(content="", reasoning=ReasoningContent(reasoning_text="analyze the input."))
yield StreamingChunk(content="Here is the answer.")
return stream()
The completed Response object includes the reasoning item before the message:
{
"output": [
{"type": "reasoning", "summary": [{"type": "summary_text", "text": "Step 1: analyze the input."}]},
{"type": "message", "content": [{"type": "output_text", "text": "Here is the answer."}]}
]
}