FastAPI
FastAPI endpoints with an OpenAI-compatible uncensored API
Serve Abliterator models from FastAPI: an AsyncOpenAI client in lifespan, a typed JSON endpoint, and token streaming with FastAPI's native EventSourceResponse.
Create AsyncOpenAI(base_url="https://abliterator.ai/v1", api_key=os.environ["ABL_API_KEY"]) in a lifespan handler, await client.chat.completions.create in async endpoints, and stream with response_class=EventSourceResponse.
FastAPI has no LLM layer of its own. Use the official openai package's AsyncOpenAI client with Abliterator's base URL, and FastAPI's built-in Server-Sent Events support for streaming. Tested with fastapi 0.165 and openai 3.60, run with FastAPI's TestClient against a stand-in server.
Install
pip install "fastapi[standard]" openai
export ABL_API_KEY="sk-abl-v1-..."
A typed JSON endpoint
Create the client once in the app's lifespan so its connection pool is shared and closed cleanly:
import os
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from openai import AsyncOpenAI
from pydantic import BaseModel
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.abliterator = AsyncOpenAI(base_url="https://abliterator.ai/v1", api_key=os.environ["ABL_API_KEY"])
yield
await app.state.abliterator.close()
app = FastAPI(lifespan=lifespan)
class ReviewIn(BaseModel):
code: str
language: str = "python"
class ReviewOut(BaseModel):
review: str
cost_usd: float | None
@app.post("/review")
async def review(body: ReviewIn, request: Request) -> ReviewOut:
abliterator: AsyncOpenAI = request.app.state.abliterator
r = await abliterator.chat.completions.create(
model="kimi-k3.1-pro-abliterated",
messages=[
{"role": "system", "content": "You are a secure-code reviewer. List vulnerabilities with CWE IDs and fixes."},
{"role": "user", "content": f"Language: {body.language}\n\n{body.code}"},
],
max_tokens=1200,
)
return ReviewOut(review=r.choices[0].message.content or "", cost_usd=r.usage.model_extra.get("cost"))
Run it with fastapi dev main.py and POST {"code": "..."} to /review.
Stream tokens with EventSourceResponse
With response_class=EventSourceResponse, every value the endpoint yields becomes one SSE event. Here each event carries a text delta, and a final done event carries usage:
import os
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.sse import EventSourceResponse, ServerSentEvent
from openai import AsyncOpenAI
from pydantic import BaseModel
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.abliterator = AsyncOpenAI(base_url="https://abliterator.ai/v1", api_key=os.environ["ABL_API_KEY"])
yield
await app.state.abliterator.close()
app = FastAPI(lifespan=lifespan)
class ChatIn(BaseModel):
messages: list[dict]
@app.post("/chat", response_class=EventSourceResponse)
async def chat(body: ChatIn, request: Request):
stream = await request.app.state.abliterator.chat.completions.create(
model="deepseek-v4.1-flash-abliterated", messages=body.messages, stream=True
)
try:
async for chunk in stream:
if await request.is_disconnected():
break
if chunk.choices and chunk.choices[0].delta.content:
yield {"text": chunk.choices[0].delta.content}
if chunk.usage:
yield ServerSentEvent(data=chunk.usage.model_dump(), event="done")
finally:
await stream.close()
Plain dicts are JSON-encoded into data:; ServerSentEvent lets you name the event. Closing the stream in finally cancels the upstream request when the client leaves, so you stop paying for tokens nobody reads.
Test without the network
FastAPI's TestClient drives the app in-process. Point base_url at a stub or at Abliterator in CI:
from fastapi.testclient import TestClient
from main import app
with TestClient(app) as client:
r = client.post("/chat", json={"messages": [{"role": "user", "content": "Define least privilege in one line."}]})
for line in r.text.splitlines():
if line.startswith("data:"):
print(line)
Use with TestClient(app) so the lifespan runs and app.state.abliterator exists.
Troubleshooting
AttributeError: 'State' object has no attribute 'abliterator'. The lifespan did not run. Passlifespan=lifespantoFastAPI(...), and useTestClientas a context manager in tests.- Other requests freeze during a generation. A sync
OpenAIclient insideasync defblocks the loop. UseAsyncOpenAI, or make the endpoint a plaindefso FastAPI runs it in a thread. - The browser sees
data: "text"with quotes. FastAPI JSON-encodes alldata. SendServerSentEvent(raw_data=...)for unencoded text, or parse JSON on the client. - Upstream errors surface as broken streams. Errors raised before the first
yieldreturn a normal error response; errors mid-stream cannot change the status code. Send anerrorevent instead, and see /docs/errors for Abliterator's codes. - Workers and concurrency. Each streaming request holds one of your plan's concurrent-request slots until it finishes (/pricing).
Frequently asked questions
Should I use OpenAI or AsyncOpenAI in FastAPI?
AsyncOpenAI in async def endpoints. The sync client blocks the event loop for the whole generation, so one slow answer stalls every other request on that worker.
Do I need sse-starlette for streaming?
Not on FastAPI 0.135 or later. fastapi.sse.EventSourceResponse plus a generator that yields events is built in and works with POST, which chat UIs need.
How do I stop generation when the client disconnects?
Inside the generator, check await request.is_disconnected() between chunks and break; then close the upstream stream with await stream.close() so Abliterator stops generating.