# Qai API documentation

Qai is an OpenAI-compatible API for text, image and video generation. Point any OpenAI SDK at `https://llm.quickcasa.ai/v1` with your Qai API key and the requests, streaming and errors work the way they do with OpenAI.

These docs are also available as [Markdown](https://q-ai.ca/docs.md) and as an [OpenAPI 3.1 spec](https://q-ai.ca/openapi.json), and there are [step-by-step guides](https://q-ai.ca/integrations) for common SDKs and tools.

## Authentication

All API requests require authentication via an API key. You can pass your key using either the `Authorization` header (OpenAI-style) or the `x-api-key` header.

#### Option 1: Bearer Token (recommended)

```
Authorization: Bearer YOUR_QAI_API_KEY
```

#### Option 2: API Key Header

```
x-api-key: YOUR_QAI_API_KEY
```

## Base URL

All API requests should be made to:

```
https://llm.quickcasa.ai
```

Because the API is OpenAI-compatible, you can use the official OpenAI SDK by simply changing the `base_url` and `api_key`.

## Error Handling

Errors follow the OpenAI error format:

```json
{
  "error": {
    "message": "Invalid API key",
    "type": "invalid_request_error",
    "code": "unauthorized"
  }
}
```

Common HTTP status codes:

- **400** - Bad request (missing or invalid parameters)
- **401** - Unauthorised (invalid or missing API key)
- **429** - Rate limit exceeded
- **502** - Generation service error
- **503** - Service temporarily unavailable

---

## List Models

GET /v1/models

Returns a list of all available models.

```bash
curl https://llm.quickcasa.ai/v1/models \
  -H "Authorization: Bearer YOUR_QAI_API_KEY"
```

#### Response

```json
{
  "object": "list",
  "data": [
    { "id": "qai-hello-world", "object": "model", "owned_by": "qai", "type": "text" },
    { "id": "qai-flash", "object": "model", "owned_by": "qai", "type": "text" },
    { "id": "qai-pro", "object": "model", "owned_by": "qai", "type": "text" },
    { "id": "qai-max", "object": "model", "owned_by": "qai", "type": "text" },
    { "id": "qai-think", "object": "model", "owned_by": "qai", "type": "text" },
    { "id": "qai-uncensored", "object": "model", "owned_by": "qai", "type": "text" },
    { "id": "qai-imagine-turbo", "object": "model", "owned_by": "qai", "type": "image" },
    { "id": "qai-imagine-quality", "object": "model", "owned_by": "qai", "type": "image" },
    { "id": "qai-imagine-uncensored-turbo", "object": "model", "owned_by": "qai", "type": "image" },
    { "id": "qai-imagine-uncensored", "object": "model", "owned_by": "qai", "type": "image" },
    { "id": "qai-imagine-uncensored-pro", "object": "model", "owned_by": "qai", "type": "image" },
    { "id": "qai-motion", "object": "model", "owned_by": "qai", "type": "video" }
  ]
}
```

---

## Chat Completions

POST /v1/chat/completions

Generate a text completion from a conversation. Fully compatible with the OpenAI chat completions API.

#### Request Body

| Parameter | Type | Description |
| --- | --- | --- |
| model required | string | One of `qai-hello-world` (free), `qai-flash`, `qai-pro`, `qai-max`, `qai-think`, or `qai-uncensored` (adult fiction and frank answers) |
| messages required | array | Array of message objects with `role` and `content` |
| stream optional | boolean | Enable Server-Sent Events streaming. Default: `false` |
| temperature optional | number | Sampling temperature (0&ndash;2). Default: `1` |
| max_tokens optional | integer | Maximum tokens to generate |
| top_p optional | number | Nucleus sampling threshold |
| stop optional | string \| array | Stop sequence(s) |
| also accepted optional | various | `max_completion_tokens`, `frequency_penalty`, `presence_penalty`, `seed`, `response_format`, `tools`, `tool_choice`, `parallel_tool_calls`, `logprobs`, `top_logprobs` and `user`, with their OpenAI meanings |

Message content can be a string or an array of `text` and `image_url` parts. Fields not listed here are ignored, and other content part types are refused with a 400.

#### Example: Non-streaming

```bash
curl https://llm.quickcasa.ai/v1/chat/completions \
  -H "Authorization: Bearer YOUR_QAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qai-flash",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "What is QuickCasa?"}
    ],
    "temperature": 0.7
  }'
```

#### Example: Streaming

```bash
curl https://llm.quickcasa.ai/v1/chat/completions \
  -H "Authorization: Bearer YOUR_QAI_API_KEY" \
  -H "Content-Type: application/json" \
  -N \
  -d '{
    "model": "qai-pro",
    "messages": [
      {"role": "user", "content": "Write a haiku about apartments."}
    ],
    "stream": true
  }'
```

#### Response

```json
{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "created": 1700000000,
  "model": "qai-flash",
  "choices": [{
    "index": 0,
    "message": {
      "role": "assistant",
      "content": "QuickCasa is a property management platform..."
    },
    "finish_reason": "stop"
  }],
  "usage": {
    "prompt_tokens": 25,
    "completion_tokens": 42,
    "total_tokens": 67
  }
}
```

---

## Image Generation

POST /v1/images/generations

Generate images from a text prompt. Compatible with the OpenAI images API.

#### Request Body

| Parameter | Type | Description |
| --- | --- | --- |
| model required | string | `qai-imagine-turbo` (fast), `qai-imagine-quality` (detailed), or `qai-imagine-uncensored` / `-turbo` / `-pro` (adult / NSFW, base64 only) |
| prompt required | string | A text description of the desired image |
| n optional | integer | Number of images to generate, from 1 to 10. Default: `1` |
| size optional | string | Accepted so OpenAI clients work unchanged. The output dimensions are set by the model. |
| response_format optional | string | `url` or `b64_json`. Default: `url`. Uncensored imagine tiers accept `b64_json` only. |

If some of the images in a request fail, the ones that succeeded are returned and only those are billed.

#### Example

```bash
curl https://llm.quickcasa.ai/v1/images/generations \
  -H "Authorization: Bearer YOUR_QAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qai-imagine-turbo",
    "prompt": "A modern apartment building at golden hour, photorealistic",
    "response_format": "b64_json"
  }'
```

#### Response

```json
{
  "created": 1700000000,
  "data": [
    {
      "b64_json": "iVBORw0KGgoAAAANSUhEUg..."
    }
  ]
}
```

---

## Video Generation

POST /v1/videos/generations

Generate short videos from a text prompt. This is a QuickCasa-specific endpoint (not part of the OpenAI spec). Videos are generated by the qai-motion model. Generation runs as a job: the request returns a job id straight away, and you poll for the result.

#### Request Body

| Parameter | Type | Description |
| --- | --- | --- |
| model required | string | `qai-motion` |
| prompt required | string | A text description of the desired video |
| size optional | string | Resolution hint as `WxH`. The model uses its own default when this is left out. |
| duration optional | number | Requested length in seconds. You are billed on the length of the video you get back, rounded to the nearest second. |
| fps optional | integer | Frame rate hint. The model uses its own default when this is left out. |

#### Example

```bash
curl https://llm.quickcasa.ai/v1/videos/generations \
  -H "Authorization: Bearer YOUR_QAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qai-motion",
    "prompt": "Aerial drone shot of a luxury condo complex, cinematic",
    "duration": 6
  }'
```

#### Response (202)

```json
{
  "id": "3f0c2a9e-6b1d-4c7a-9a52-1f4e8d2b7c10",
  "status": "processing"
}
```

#### Poll for the result

GET /v1/videos/generations/{id}

Poll every 5 to 10 seconds with the same API key. While the video is being made you get `{"id", "status": "processing"}`. When it is ready:

```json
{
  "id": "3f0c2a9e-6b1d-4c7a-9a52-1f4e8d2b7c10",
  "status": "completed",
  "result": {
    "created": 1700000000,
    "data": [
      {
        "url": "https://llm.quickcasa.ai/media/temp/abc123",
        "content_type": "video/mp4",
        "duration_seconds": 6
      }
    ]
  }
}
```

**Note:** A clip usually takes a few minutes. A failed job returns HTTP 502 with `status: "failed"`, and a job that has not finished after 30 minutes is cancelled. Only the key's own company can poll a job.

---

## Uncensored terms

`qai-uncensored` and the uncensored imagine tiers stay off until the account accepts two statements: that the caller is 18 or older, and that the models will not be used for illegal activity. One accept covers every key on the company. Tick both boxes at [/uncensored-terms](https://q-ai.ca/uncensored-terms), or call the endpoint below.

GET /v1/uncensored-terms

Returns whether this account has already accepted the current terms.

POST /v1/uncensored-terms

Stores both attestations. Both fields must be `true`.

#### Request Body

| Parameter | Type | Description |
| --- | --- | --- |
| iAmAnAdult required | boolean | Must be `true`. Confirms the caller is 18 years of age or older. |
| noIllegalActivity required | boolean | Must be `true`. Confirms the models will not be used for illegal activity. |

```bash
curl -X POST https://llm.quickcasa.ai/v1/uncensored-terms \
  -H "Authorization: Bearer $QC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"iAmAnAdult":true,"noIllegalActivity":true}'
```

---

## Python SDK

Use the official `openai` Python package. Just point it at our base URL.

```bash
pip install openai
```

#### Chat Completion

```python
from openai import OpenAI

client = OpenAI(
    base_url="https://llm.quickcasa.ai/v1",
    api_key="YOUR_QAI_API_KEY",
)

response = client.chat.completions.create(
    model="qai-flash",
    messages=[
        {"role": "user", "content": "Hello!"}
    ],
)

print(response.choices[0].message.content)
```

#### Streaming

```python
stream = client.chat.completions.create(
    model="qai-pro",
    messages=[{"role": "user", "content": "Tell me a story."}],
    stream=True,
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")
```

#### Image Generation

```python
image = client.images.generate(
    model="qai-imagine-turbo",
    prompt="A cozy studio apartment with warm lighting",
    size="1024x1024",
    response_format="b64_json",
)

print(image.data[0].b64_json[:50])
```

---

## Node.js SDK

Use the official `openai` npm package.

```bash
npm install openai
```

#### Chat Completion

```typescript
import OpenAI from 'openai';

const client = new OpenAI({
  baseURL: 'https://llm.quickcasa.ai/v1',
  apiKey: 'YOUR_QAI_API_KEY',
});

const response = await client.chat.completions.create({
  model: 'qai-flash',
  messages: [
    { role: 'user', content: 'Hello!' },
  ],
});

console.log(response.choices[0].message.content);
```

#### Streaming

```typescript
const stream = await client.chat.completions.create({
  model: 'qai-pro',
  messages: [{ role: 'user', content: 'Tell me a story.' }],
  stream: true,
});

for await (const chunk of stream) {
  const content = chunk.choices[0]?.delta?.content;
  if (content) {
    process.stdout.write(content);
  }
}
```

#### Video Generation (fetch)

```typescript
// Video generation uses a custom endpoint, so use fetch directly
const response = await fetch('https://llm.quickcasa.ai/v1/videos/generations', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_QAI_API_KEY',
  },
  body: JSON.stringify({
    model: 'qai-motion',
    prompt: 'Aerial tour of a modern apartment complex',
    duration: 6,
  }),
});

const { id } = await response.json();

// Poll until the job finishes
let job;
do {
  await new Promise((resolve) => setTimeout(resolve, 5000));
  const poll = await fetch(`https://llm.quickcasa.ai/v1/videos/generations/${id}`, {
    headers: { 'Authorization': 'Bearer YOUR_QAI_API_KEY' },
  });
  job = await poll.json();
} while (job.status === 'processing');

console.log(job.result.data[0].url);
```

---

## cURL Quick Reference

#### Text

```bash
curl -X POST https://llm.quickcasa.ai/v1/chat/completions \
  -H "Authorization: Bearer $QC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"qai-flash","messages":[{"role":"user","content":"Hi!"}]}'
```

#### Image

```bash
curl -X POST https://llm.quickcasa.ai/v1/images/generations \
  -H "Authorization: Bearer $QC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"qai-imagine-turbo","prompt":"sunset over a city skyline"}'
```

#### Video

```bash
curl -X POST https://llm.quickcasa.ai/v1/videos/generations \
  -H "Authorization: Bearer $QC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"qai-motion","prompt":"walkthrough of a modern kitchen","duration":6}'
```

---

## Streaming

Every Qai text model supports Server-Sent Events streaming. Set `stream: true` on your chat completions request and Qai forwards tokens as they are generated. The response uses the standard OpenAI streaming envelope, so any client library that already handles OpenAI streaming works with Qai unmodified.

Streamed responses include a final usage chunk with prompt and completion token counts, so streaming and non-streaming billing land at the same precision. If a particular model variant ever skips the usage chunk, Qai falls back to a token estimate so billing never silently records zero.

```
from openai import OpenAI

client = OpenAI(base_url="https://llm.quickcasa.ai/v1", api_key="YOUR_QAI_API_KEY")

stream = client.chat.completions.create(
    model="qai-pro",
    messages=[{"role": "user", "content": "Tell me a story."}],
    stream=True,
)

for chunk in stream:
    delta = chunk.choices[0].delta.content
    if delta:
        print(delta, end="", flush=True)
```

```
const stream = await client.chat.completions.create({
  model: 'qai-pro',
  messages: [{ role: 'user', content: 'Tell me a story.' }],
  stream: true,
});

for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? '');
}
```

---

## Migrating from OpenAI

If you have an existing app on the OpenAI API, the migration is exactly two changes:

#### 1. Change the base URL

Point your OpenAI client at `https://llm.quickcasa.ai/v1` instead of `https://api.openai.com/v1`.

#### 2. Swap the model name

Pick the Qai tier that matches your old model. Rough equivalents:

- `gpt-4o-mini` > `qai-flash`
- `gpt-4o` > `qai-pro` or `qai-max`
- `gpt-4.1` > `qai-max`
- `o1`, `o3` > `qai-think`
- `dall-e-3` > `qai-imagine-quality`

Everything else - streaming, function calling, JSON mode, system prompts, tool calls - works identically.

```
  const client = new OpenAI({
-   baseURL: 'https://api.openai.com/v1',
+   baseURL: 'https://llm.quickcasa.ai/v1',
    apiKey: process.env.QAI_API_KEY,
  });

  await client.chat.completions.create({
-   model: 'gpt-4o',
+   model: 'qai-pro',
    messages: [...],
  });
```

---

## Best practices

#### Match the tier to the job

Do not default to qai-max for everything just because it is the most capable. A summarisation pipeline runs fine on qai-flash for a tenth of the cost. Use the dashboard's per-model breakdown to spot where you are over-spending.

#### Use one key per integration

Especially in production. Usage is tracked per key in the dashboard, so a misbehaving cron job shows up under its own name, and disabling that one key stops it without touching anything else.

#### Use the free sandbox during development

qai-hello-world is free and capped at 100 calls per API key per UTC day. Wire your dev environment to it - your real spend should only start when you go to production.

#### Stream when the user is waiting

For chat-style interactions, set stream=true. A 4-second response feels instant when the first token arrives in 200ms; it feels broken when nothing happens for 4 seconds.

#### Set `hostMedia: true` for production images and videos

Without it, generated media is temporary and auto-expires. With it, you get a permanent URL on the Qai CDN that you can embed directly into emails, apps, or social posts without re-hosting.

#### Pin to a model, not a default

Always pass an explicit `model` field. Do not assume a default. Models can rev, behaviours can shift, and being explicit means your tests are reproducible.

---

## Errors reference

Qai returns errors in OpenAI-compatible shape: `{ "error": { "message", "type", "code" } }`. Below is the full list of error codes you might see.

#### HTTP 400 - invalid_request_error

- `missing_field` - a required field (model, prompt) was not in your request body.
- `invalid_request` - a chat request field is missing or has the wrong type, or the model rejected the request. The `message` says which.
- `invalid_model` - the model id is not one Qai serves. Hit `GET /v1/models` for the live catalogue.
- `invalid_value` - a field has a value outside its range (for example `n` above 10).
- `context_length_exceeded` - the messages plus `max_tokens` are longer than the model can take.
- `content_filtered` - the request was blocked by content moderation.

#### HTTP 401 - invalid_request_error

- `unauthorized` - the Authorization header was missing, malformed, or referred to a key that does not exist or is disabled.

#### HTTP 403 - invalid_request_error

- `billing_not_enabled` - the account has no Qai billing set up, so paid models are off for its keys. Finish signup, or use the free qai-hello-world.
- `uncensored_terms_required` - this account has not accepted the uncensored terms yet. Tick both boxes at [/uncensored-terms](https://q-ai.ca/uncensored-terms), or POST both `iAmAnAdult` and `noIllegalActivity` to `/v1/uncensored-terms`.

#### HTTP 429 - rate_limit_error

- `rate_limit_exceeded` - too many requests from your address in the last minute. Retry with exponential backoff.
- `sandbox_quota_exceeded` - the free qai-hello-world tier's per-key per-UTC-day quota was hit. Wait until midnight UTC or switch to qai-flash.
- `upstream_busy` - the model is busy right now. Retry in a few seconds.

#### HTTP 502, 503 and 504 - api_error

- `upstream_error` - the model did not answer. Retry in a moment.
- `generation_failed` - a video job could not be generated (returned when you poll it).
- `model_unavailable` (503) - the model is temporarily unavailable. Retry shortly.
- `billing_check_unavailable` (503) - Qai could not confirm billing for the account just now. Retry in a few seconds.
- `uncensored_terms_unavailable` (503) - Qai could not confirm uncensored terms for the account just now. Retry in a few seconds.
- `upstream_timeout` (504) - the model took too long to answer.

#### HTTP 500 - api_error

- `internal_error` - something on our side broke. If you see this repeatedly, email [hi@quickcasa.ai](mailto:hi@quickcasa.ai) with the timestamp and we will dig in.

---

## Rate limits

Qai applies two layers of rate limiting:

#### Per address

Requests are limited to 100 per minute from each IP address, across every key and endpoint. If you exceed it, you get a 429 with `code: rate_limit_exceeded`. The response includes a `Retry-After` header.

#### Per-key sandbox quota

The free qai-hello-world tier is capped at 100 calls per API key per UTC day. When you hit the cap, that specific key returns 429 with `code: sandbox_quota_exceeded` until midnight UTC. Other models on the same key keep working.

#### How to handle 429s

1. Respect the `Retry-After` header when present.
2. Use exponential backoff with jitter for retries (start at 500ms, double up to 30s).
3. If you regularly hit the limit, email us about lifting it - we can usually raise it within a business day.

---

## Frequently asked questions

#### Is Qai really OpenAI-compatible?

Yes. Same endpoints, same request bodies, same streaming envelope, same error format. Drop in OpenAI's SDK, change the baseURL, and you are running on Qai. We test against the official openai-python and openai-node libraries.

#### Can I run Qai keys alongside OpenAI keys in the same app?

Of course - just instantiate two clients with different baseURLs. Some teams route cheap chat to Qai and reserve OpenAI for one specific feature they have already tuned. There is no exclusivity.

#### What is the actual latency?

It depends on the model and the prompt. qai-flash and qai-pro answer fastest; qai-max and qai-think trade speed for depth. qai-uncensored checks the full answer before the first token is sent. Image generation takes seconds and video generation takes minutes, so poll the video job rather than blocking a request on it.

#### What if a model is temporarily unavailable?

You will get a 502 or 503 with a clear error message. Outages are rare but they happen - it is on the roadmap to automatically retry a failed generation against the next-best tier (e.g. qai-max failing over to qai-pro) so your app does not feel them.

#### Does Qai store my prompts?

For text, we store the metadata needed for billing (model, token count, timestamp, API key id) but not the prompt or the completion. For SFW images and video, the prompt is kept with the generated file's record. Uncensored imagine tiers return base64 and never store the image.

#### How do I cancel?

Sign in, head to your dashboard, click "Manage account" then "Cancel subscription". You stop being billed at the end of the current cycle. If you want all your data deleted too, email us and we will wipe everything.

#### I lost my API key. How do I recover it?

Sign in, disable the lost key, and create a new one. Disabling takes effect on the next request.

#### Can I get higher rate limits?

Yes. Email [hi@quickcasa.ai](mailto:hi@quickcasa.ai) with your account email and what you are building. Most lifts happen within a business day.
