AWS Lambda

AWS Lambda Python with an OpenAI-compatible uncensored API

Run Abliterator from AWS Lambda in Python: package the openai SDK for Linux, reuse the client across invocations, stream against the deadline, retry SQS batches.

Reviewed AWS LambdaPython

Quick answer

Package openai with your function, create OpenAI(base_url="https://abliterator.ai/v1", api_key=os.environ["ABL_API_KEY"]) at module level so warm invocations reuse it, and raise the function timeout well above the 3-second default.

Lambda runs plain Python, so the official openai package works once it is in the deployment package. The Lambda-specific parts are packaging for Linux, client reuse between invocations, timeouts and event-source behavior; see AWS's Python handler guide. Each handler below was run locally with a fake event and context against a stand-in server.

Package the SDK for Linux

Build on any OS by asking pip for Linux wheels, so pydantic-core matches Lambda's architecture:

pip install openai --target package --platform manylinux2014_x86_64 --only-binary=:all: --python-version 3.13
cp lambda_function.py package/
(cd package && zip -r ../function.zip .)

Use manylinux2014_aarch64 for arm64 functions. Set ABL_API_KEY in the function's environment variables and the timeout to 60 seconds or more.

An API Gateway handler

lambda_function.py, behind an HTTP API:

import json
import os

from openai import OpenAI

client = OpenAI(base_url="https://abliterator.ai/v1", api_key=os.environ["ABL_API_KEY"], timeout=50, max_retries=1)


def lambda_handler(event, context):
    body = json.loads(event.get("body") or "{}")
    r = client.chat.completions.create(
        model="deepseek-v4.1-flash-abliterated",
        messages=[
            {"role": "system", "content": "Explain CloudTrail events to a cloud security analyst: what happened and whether it is risky."},
            {"role": "user", "content": json.dumps(body.get("event", {}))},
        ],
        max_tokens=400,
    )
    return {
        "statusCode": 200,
        "headers": {"Content-Type": "application/json"},
        "body": json.dumps({"explanation": r.choices[0].message.content, "cost": r.usage.model_extra.get("cost")}),
    }

The client is created at import time, so a warm container reuses its connection pool. Keep the SDK timeout below the function timeout so you get a clean error instead of a killed invocation.

Stream against the deadline

A Python function cannot stream its response, but it can read Abliterator's stream and stop before Lambda kills it. context.get_remaining_time_in_millis() tells you how long is left:

import os

from openai import OpenAI

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


def lambda_handler(event, context):
    stream = client.chat.completions.create(
        model="kimi-k3.1-pro-abliterated",
        messages=[{"role": "user", "content": event.get("prompt", "Write an incident postmortem template.")}],
        stream=True,
    )
    parts, truncated = [], False
    for chunk in stream:
        if context.get_remaining_time_in_millis() < 3000:
            truncated = True
            stream.close()
            break
        if chunk.choices and chunk.choices[0].delta.content:
            parts.append(chunk.choices[0].delta.content)
    return {"text": "".join(parts), "truncated": truncated}

Closing the stream cancels the request, so you pay only for tokens generated before the cut-off.

SQS batches with partial failures

For queue-driven labeling, enable ReportBatchItemFailures on the event source mapping and report only the messages that should be retried:

import json
import os

import openai
from openai import OpenAI

client = OpenAI(base_url="https://abliterator.ai/v1", api_key=os.environ["ABL_API_KEY"], max_retries=0)


def lambda_handler(event, context):
    failures = []
    for record in event["Records"]:
        try:
            ticket = json.loads(record["body"])
            r = client.chat.completions.create(
                model="deepseek-v4.1-flash-abliterated",
                messages=[
                    {"role": "system", "content": "Label the abuse report: spam, scam, harassment or other. One word."},
                    {"role": "user", "content": ticket["text"]},
                ],
                max_tokens=5,
            )
            print(json.dumps({"id": ticket["id"], "label": r.choices[0].message.content.strip()}))
        except (openai.RateLimitError, openai.APIConnectionError, openai.InternalServerError):
            failures.append({"itemIdentifier": record["messageId"]})
        except openai.BadRequestError as err:
            print(json.dumps({"messageId": record["messageId"], "skipped": err.message}))
    return {"batchItemFailures": failures}

Rate-limit and upstream errors go back to the queue, and a 400 for one malformed ticket is logged and skipped. A 401 or 402 is not caught: it fails the whole batch, which is right, because the key or the balance needs fixing before anything can succeed.

Troubleshooting

  • Task timed out after 3.00 seconds. That is Lambda's default timeout. Raise it in the function configuration.
  • Runtime.ImportModuleError: No module named 'openai'. The SDK is not in the zip root. Install with --target package and zip the contents of package/.
  • No module named 'pydantic_core._pydantic_core'. Wheels were built for your laptop, not Lambda. Use the --platform and --only-binary flags above.
  • KeyError: 'ABL_API_KEY' on cold start. The environment variable is not set on this function or alias version.
  • Bursts of 429. SQS and API Gateway can scale Lambda faster than your plan's limits (/docs/rate-limits). Set reserved or maximum concurrency.

Frequently asked questions

Can a Python Lambda stream tokens to the caller?

Not with the managed Python runtime; Lambda response streaming is built in only for Node.js. Python functions can still read Abliterator's stream internally, as the deadline example shows, and return the result.

Where should the Abliterator key live in Lambda?

An encrypted environment variable is the simplest. For rotation and auditing, store it in Secrets Manager and read it once at cold start, keeping the value in a module-level variable.

How do I avoid 429s when SQS scales Lambda up?

Cap the event source's maximum concurrency at or below your plan's concurrent-request limit, and return 429-failed messages in batchItemFailures so SQS retries only those.