Flask

Flask apps with an OpenAI-compatible uncensored API

Add Abliterator models to a Flask app: a client stored in app.extensions, streamed responses with stream_with_context, and a route that runs a tool-calling loop.

Reviewed FlaskPython

Quick answer

In your app factory, create OpenAI(base_url="https://abliterator.ai/v1", api_key=os.environ["ABL_API_KEY"]), store it in app.extensions, and stream from routes with stream_with_context.

Flask leaves model access to you. The official openai package pointed at Abliterator covers it, and Flask's streaming support handles token output. Tested with Flask 3.1 and openai 3.60 through Flask's test client against a stand-in server.

Install

pip install flask openai
export ABL_API_KEY="sk-abl-v1-..."

App factory and a JSON route

Save this as app.py. The client lives in app.extensions so every blueprint can reach it through current_app:

import json
import os

from flask import Flask, Response, current_app, jsonify, request, stream_with_context
from openai import OpenAI


def create_app() -> Flask:
    app = Flask(__name__)
    app.extensions["abliterator"] = OpenAI(base_url="https://abliterator.ai/v1", api_key=os.environ["ABL_API_KEY"], timeout=120)

    @app.post("/summarize")
    def summarize():
        text = request.get_json()["text"]
        r = current_app.extensions["abliterator"].chat.completions.create(
            model="deepseek-v4.1-flash-abliterated",
            messages=[
                {"role": "system", "content": "Summarize incident notes for an executive in three sentences."},
                {"role": "user", "content": text},
            ],
            max_tokens=300,
        )
        return jsonify(summary=r.choices[0].message.content, cost=r.usage.model_extra.get("cost"))

    @app.get("/stream")
    def stream():
        topic = request.args.get("topic", "password spraying")

        def generate():
            chunks = current_app.extensions["abliterator"].chat.completions.create(
                model="kimi-k3.1-pro-abliterated",
                messages=[{"role": "user", "content": f"Explain {topic} and how to detect it in Entra ID sign-in logs."}],
                stream=True,
            )
            for chunk in chunks:
                if chunk.choices and chunk.choices[0].delta.content:
                    yield f"data: {json.dumps(chunk.choices[0].delta.content)}\n\n"
            yield "data: [DONE]\n\n"

        return Response(stream_with_context(generate()), mimetype="text/event-stream")

    return app

Run it with flask --app app:create_app run. The /stream route is plain SSE, so a browser EventSource("/stream?topic=...") can read it.

A route that runs tools

Tool calling with the bare SDK is a short loop: send tools, run whatever the model asks for, append the results, call again. This route lets an analyst ask about a host and the model looks it up:

import json
import os

from flask import Flask, jsonify, request
from openai import OpenAI

app = Flask(__name__)
abliterator = OpenAI(base_url="https://abliterator.ai/v1", api_key=os.environ["ABL_API_KEY"])

INVENTORY = {"web-03": {"os": "Ubuntu 22.04", "exposed": True, "last_patch": "2026-07-02"}}

TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "get_host",
            "description": "Look up a host in the asset inventory.",
            "parameters": {
                "type": "object",
                "properties": {"hostname": {"type": "string"}},
                "required": ["hostname"],
            },
        },
    }
]


@app.post("/ask")
def ask():
    messages = [
        {"role": "system", "content": "You are an asset-risk assistant. Use get_host before answering."},
        {"role": "user", "content": request.get_json()["question"]},
    ]
    for _ in range(4):
        r = abliterator.chat.completions.create(model="kimi-k3.1-pro-abliterated", messages=messages, tools=TOOLS)
        msg = r.choices[0].message
        if not msg.tool_calls:
            return jsonify(answer=msg.content)
        messages.append(msg.model_dump(exclude_none=True))
        for call in msg.tool_calls:
            args = json.loads(call.function.arguments)
            result = INVENTORY.get(args.get("hostname"), {"error": "unknown host"})
            messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})
    return jsonify(error="tool loop limit reached"), 502

The loop cap keeps a confused model from spending your balance. More on the message format in /docs/tool-calling.

Troubleshooting

  • RuntimeError: Working outside of request context inside the stream. The generator touched request or current_app after the view returned. Wrap it in stream_with_context, as above.
  • The stream arrives in one block. A reverse proxy is buffering; disable buffering for the route (X-Accel-Buffering: no for nginx). Under gunicorn, prefer --worker-class gthread so one long stream does not occupy a whole sync worker.
  • 400 after a tool call. Each tool message must carry the tool_call_id of the call it answers, and the assistant message with tool_calls must come right before the results. Appending msg.model_dump(exclude_none=True) keeps that message intact and JSON-serializable for logging.
  • Worker timeouts on long answers. gunicorn kills sync workers after 30 seconds by default. Raise --timeout or stream.
  • Model ID typos. Abliterator returns 404 for unknown models. Keep kimi-k3.1-pro-abliterated and deepseek-v4.1-flash-abliterated in config rather than scattered string literals.

Frequently asked questions

Why use stream_with_context for streaming?

Flask tears down the request context once the view returns. stream_with_context keeps it alive while the generator runs, so request and current_app still work inside the stream.

Is the OpenAI client safe to share between Flask threads?

Yes. The client is thread-safe and pools connections, so create one per app in the factory instead of one per request.

Can Flask run the async client?

Flask supports async views with the flask[async] extra, but each request still runs in its own event loop. For many concurrent streams, the sync client with a threaded server, or an ASGI framework, is simpler.