Django
Django views with an OpenAI-compatible uncensored API
Call Abliterator from Django: a shared client configured in settings, a JSON view, an async StreamingHttpResponse under ASGI, and a management command for batch jobs.
Read ABL_API_KEY in settings.py, build one OpenAI(base_url="https://abliterator.ai/v1") client in a module your views import, and use AsyncOpenAI with an async StreamingHttpResponse for streaming under ASGI.
Django has no LLM integration of its own. The simplest durable setup is the official openai package configured from settings.py, plus Django's own streaming responses for token output. The examples assume an app named secops and were run with Django 6.1 and openai 3.60 using Django's test client against a stand-in server.
Install and configure
pip install django openai uvicorn
export ABL_API_KEY="sk-abl-v1-..."
Add the key and model choices to settings.py:
import os
ABL_API_KEY = os.environ["ABL_API_KEY"]
ABL_BASE_URL = "https://abliterator.ai/v1"
ABL_MODEL = "kimi-k3.1-pro-abliterated"
ABL_MODEL_FAST = "deepseek-v4.1-flash-abliterated"
Build the clients once in secops/llm.py:
from django.conf import settings
from openai import AsyncOpenAI, OpenAI
client = OpenAI(base_url=settings.ABL_BASE_URL, api_key=settings.ABL_API_KEY, timeout=120)
aclient = AsyncOpenAI(base_url=settings.ABL_BASE_URL, api_key=settings.ABL_API_KEY, timeout=120)
A JSON view
secops/views.py:
import json
from django.conf import settings
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from secops.llm import aclient, client
@require_POST
def explain_alert(request):
alert = json.loads(request.body)["alert"]
r = client.chat.completions.create(
model=settings.ABL_MODEL_FAST,
messages=[
{"role": "system", "content": "Explain SIEM alerts to on-call engineers: cause, risk, first step."},
{"role": "user", "content": alert},
],
max_tokens=600,
)
return JsonResponse({"explanation": r.choices[0].message.content})
Wire it in urls.py with path("alerts/explain", views.explain_alert), and exempt or handle CSRF as your API requires.
Stream with an async view
Add to the same secops/views.py. An async generator passed to StreamingHttpResponse streams each delta as it arrives when Django runs under ASGI:
from django.http import StreamingHttpResponse
async def stream_report(request):
topic = request.GET.get("topic", "credential stuffing")
async def events():
stream = await aclient.chat.completions.create(
model=settings.ABL_MODEL,
messages=[{"role": "user", "content": f"Write a detection-engineering brief on {topic}."}],
stream=True,
)
async for chunk in stream:
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"
response = StreamingHttpResponse(events(), content_type="text/event-stream")
response["Cache-Control"] = "no-cache"
response["X-Accel-Buffering"] = "no"
return response
Run the project with uvicorn myproject.asgi:application. Under runserver and WSGI the view still works but the output may arrive in one piece.
Batch work in a management command
Labeling a backlog does not belong in a web request. A management command, secops/management/commands/label_tickets.py, can run it from cron or a worker:
from django.conf import settings
from django.core.management.base import BaseCommand
from secops.llm import client
class Command(BaseCommand):
help = "Label security tickets as phishing, malware, account takeover or other."
def add_arguments(self, parser):
parser.add_argument("subjects", nargs="+")
def handle(self, *args, **options):
for subject in options["subjects"]:
r = client.chat.completions.create(
model=settings.ABL_MODEL_FAST,
messages=[
{"role": "system", "content": "Reply with one label: phishing, malware, account_takeover or other."},
{"role": "user", "content": subject},
],
max_tokens=10,
)
self.stdout.write(f"{r.choices[0].message.content.strip()}\t{subject}")
python manage.py label_tickets "Password reset I did not request" "Invoice.zip from unknown sender"
In a real job, read tickets from the ORM and save the label back. Keep loops sequential or use a small thread pool so you stay under your plan's request limits (/docs/rate-limits).
Troubleshooting
SynchronousOnlyOperationin the async view. ORM calls insideasync defneedawait Model.objects.aget(...)orsync_to_async. The Abliterator call itself is fine withaclient.- Warning: "StreamingHttpResponse must consume asynchronous iterators in order to serve them synchronously". The project is running under WSGI. Use an ASGI server for streaming views.
- Stream arrives all at once behind nginx. Keep the
X-Accel-Buffering: noheader, and do not apply GZip middleware to the streaming view. KeyError: 'ABL_API_KEY'at startup. The variable is not exported in the process that runs Django (systemd unit, container env or.envloader).- Worker timeouts. Long completions can exceed gunicorn's default 30-second
--timeout. Stream, raise the timeout, or move the call to a background job.
Frequently asked questions
Does streaming work under gunicorn with WSGI?
Not well. Django consumes an async iterator synchronously under WSGI and warns about it, and many WSGI setups buffer the response. Serve the streaming view with an ASGI server such as uvicorn or daphne.
Where should the Abliterator client live in a Django project?
In one module (for example secops/llm.py) that builds the client from settings at import time. Views and management commands import it, so connections are reused and the key is read in one place.
How do I run long batch jobs without blocking web workers?
Put them in a management command or a task queue worker, as in the example on this page, and use deepseek-v4.1-flash-abliterated for high-volume labeling.