# AI Gateway

The AI Gateway speaks OpenAI's API: point the OpenAI SDK, or any OpenAI-compatible client, at `https://harakumo.com/api/ai/v1` with a Harakumo API key, and pick any model by its id. Every answer says which model answered, what it cost (`usage.cost`, in dollars) and its request id. Usage is paid from the plan's included AI credit first, where the plan has one, then the Balance: on a paid plan, the Balance of the workspace that pays for the plan, for every workspace it covers, under that workspace's spending limit; on Hobby, the workspace's own.

`harakumo-1` (alias `auto`) is a router: it tries vendor models in order within a tier (fast, balanced or deep) until one answers, and is billed at the price of the model that answered — Claude Sonnet leads the balanced tier. Name a model to pin it; `llama-3.3-70b` and `kimi-k2.6` run on Harakumo's edge inference. A model you name is answered by that model or refused (503 `model_unavailable`), never by another under its name; use `harakumo-1` to fail over. Every cheap and mid-price model is on by default (Kimi K2.6 once a live call has confirmed it); Claude Opus is off until an admin turns it on in Dashboard → AI Gateway. `GET /api/ai/v1/models` (SDK `hk.ai.listModels()`, connector `list_ai_models`) lists each model with its price, limits, `supported_parameters` and `enabled`.

## In plain words

AI models from several companies through one account. Your app asks a question and gets an answer. What it uses is paid from your balance, once any AI your plan includes is used up.

For example: A shop turns a few bullet points into a product description.

## Quickstart: the OpenAI SDK

Use the OpenAI SDK you already know. The base URL is `https://harakumo.com/api/ai/v1` (`hk.ai.baseURL` in the Harakumo SDK) and the key is a Harakumo API key, kept on your server. `chat.completions`, `embeddings` and `models` work, streaming included. Each reply also carries a `harakumo` field: the provider, the cost, the request id and any fallback taken.

**JavaScript**

```js
import OpenAI from 'openai';

const ai = new OpenAI({ apiKey: process.env.HARAKUMO_API_KEY, baseURL: 'https://harakumo.com/api/ai/v1' });

const r = await ai.chat.completions.create({
  model: 'harakumo-1',                       // or any id from ai.models.list()
  messages: [{ role: 'user', content: 'What is an edge function?' }],
});
console.log(r.choices[0].message.content, r.usage.cost);

const stream = await ai.chat.completions.create({
  model: 'claude-sonnet-5', stream: true, stream_options: { include_usage: true },
  messages: [{ role: 'user', content: 'Tell me a story.' }],
});
for await (const chunk of stream) process.stdout.write(chunk.choices[0]?.delta?.content || '');
```

**Python**

```python
import os
from openai import OpenAI

ai = OpenAI(api_key=os.environ["HARAKUMO_API_KEY"], base_url="https://harakumo.com/api/ai/v1")
r = ai.chat.completions.create(model="harakumo-1", messages=[{"role": "user", "content": "Hi"}])
print(r.choices[0].message.content)
```

**AI SDK**

```js
import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
import { generateText } from 'ai';

const harakumo = createOpenAICompatible({
  name: 'harakumo', baseURL: 'https://harakumo.com/api/ai/v1', apiKey: process.env.HARAKUMO_API_KEY,
});
const { text } = await generateText({ model: harakumo('harakumo-1'), prompt: 'Hi' });
```

## Tools and JSON output

Tool calling (`tools`, `tool_choice`, `parallel_tool_calls`, and `tool` messages answering them) and JSON output (`response_format` `json_object` or `json_schema`) are taken on `/api/ai/v1/chat/completions` only by the models whose `supported_parameters` in `GET /api/ai/v1/models` list them. A model is listed only once it has passed a live tool loop and JSON check through the gateway; until then a request with them is a 400 `unsupported_parameter` naming the models that can. Check the list before writing code that depends on them. `harakumo-1` asked for either is routed only among the models that can (503 `no_model_available` when none switched on here can).

No model has passed that live check yet, so today every request with `tools` or a JSON `response_format` is a 400 `unsupported_parameter`. The example below works once `GET /api/ai/v1/models` lists `tools` in the `supported_parameters` of the model it names.

`json_object` needs the word JSON in a message, and a conversation that carries tool calls must send `tools`. Strict schema adherence is guaranteed only where the model's vendor guarantees it; elsewhere the output is JSON shaped by the schema.

**Tools (OpenAI SDK; only on a model that lists tools)**

```js
// Works only on a model whose supported_parameters in ai.models.list() include 'tools'.
const tools = [{ type: 'function', function: {
  name: 'order_status', description: 'Look up an order by its id',
  parameters: { type: 'object', properties: { orderId: { type: 'string' } }, required: ['orderId'] },
} }];
const messages = [{ role: 'user', content: 'Where is order 881?' }];
const first = await ai.chat.completions.create({ model: 'claude-sonnet-5', messages, tools });
const call = first.choices[0].message.tool_calls?.[0];
if (call) {
  messages.push(first.choices[0].message, { role: 'tool', tool_call_id: call.id, content: JSON.stringify({ status: 'shipped' }) });
  const done = await ai.chat.completions.create({ model: 'claude-sonnet-5', messages, tools });
  console.log(done.choices[0].message.content);
}
```

## Streaming and errors on /api/ai/v1

- With `stream: true` the answer comes as `chat.completion.chunk` events and ends with `data: [DONE]`. The last content chunk carries `harakumo` (provider, cost, request id); `stream_options: { include_usage: true }` adds OpenAI's own usage chunk (no choices, `usage` with `cost`) before `[DONE]`.
- A stream that fails after it started arrives as one more data chunk in OpenAI's error shape, code `stream_error`, whose `metadata` has `tokens_in`, `tokens_out`, `cost` and `request_id`: you are charged only for what was delivered, and nothing when the model failed before answering.
- Refusals come in OpenAI's error shape, `{ "error": { "message", "type", "code", "param", "metadata"? } }`, with the codes below; `metadata` holds the rest of the answer (`buy_url` and `available_usd` on a 402, `retry_after` on a 429). Only 408, 429 and 5xx answers are worth retrying.

## Parameters on /api/ai/v1/chat/completions

| Parameter | What the gateway does |
| --- | --- |
| model, messages, max_tokens / max_completion_tokens, temperature, stream, stream_options.include_usage | Honoured on every model. |
| tools, tool_choice, parallel_tool_calls | Honoured on models that support tools (supported_parameters in GET /api/ai/v1/models); 400 on the others, naming the ones that do. |
| response_format | `text` everywhere; `json_object` and `json_schema` on models that support them. `json_object` needs the word JSON in a message. |
| user, metadata, seed, store: false | Accepted, with no effect. |
| n: 1, top_p: 1, frequency_penalty: 0, presence_penalty: 0, logprobs: false | Accepted only at these values. |
| stop, logit_bias, top_logprobs, functions, function_call, audio, modalities, prediction, reasoning_effort, service_tier, web_search_options | Refused (400 `unsupported_parameter`). |

> Anything else is refused with 400 unsupported_parameter, never silently ignored. Only 408, 429 and 5xx answers are worth retrying.

## The native endpoint

`POST /api/ai/chat` is Harakumo's own shape, which the SDK's `hk.ai.chat` and `hk.ai.stream` use: every answer reports the model that answered, the provider, tokens, latency, why it stopped and exactly what it cost. It takes text only: tools and JSON output (`tools`, `tool_choice`, `response_format` other than text) are refused here with 400 `unsupported_parameter`; use `/api/ai/v1/chat/completions` for them.

**curl**

```bash
curl https://harakumo.com/api/ai/chat \
  -H "Authorization: Bearer $HARAKUMO_API_KEY" -H "content-type: application/json" \
  -d '{ "model": "harakumo-1", "system": "Answer in one sentence.",
        "messages": [{ "role": "user", "content": "What is an edge function?" }], "max_tokens": 300 }'
# → { "output", "modelUsed", "provider", "finishReason", "truncated", "tokensIn", "tokensOut", "cost", "latencyMs" }
```

**Streaming (server-sent events)**

```js
const res = await fetch('https://harakumo.com/api/ai/chat', {
  method: 'POST',
  headers: { authorization: 'Bearer ' + process.env.HARAKUMO_API_KEY, 'content-type': 'application/json' },
  body: JSON.stringify({ model: 'claude-sonnet-5', stream: true, messages: [{ role: 'user', content: 'Tell me a story.' }] }),
});
// Events: "meta" (the model answering), "delta" ({ text }), then "done"
// ({ finishReason, truncated, tokensIn, tokensOut, cost }) or "error".
for await (const chunk of res.body) process.stdout.write(new TextDecoder().decode(chunk));
```

**SDK**

```js
const answer = await hk.ai.chat({
  model: 'harakumo-1', system: 'Answer in one sentence.',
  messages: [{ role: 'user', content: 'What is an edge function?' }],
});
console.log(answer.output, answer.modelUsed, answer.cost);

for await (const ev of hk.ai.stream({ prompt: 'Tell me a story.' })) {
  if (ev.event === 'delta') process.stdout.write(ev.data.text);
  if (ev.event === 'done') console.log('\n', ev.data.cost);
}
```

## Request fields

| Field | Meaning |
| --- | --- |
| model | A model id, or `harakumo-1` / `auto` (the default when left out). `GET /api/ai/chat` lists the models this workspace can use and its limits. |
| messages or prompt | A chat history (`system`, `user`, `assistant` roles), or one prompt string. |
| system | A system prompt. |
| max_tokens | Default 4,096 (1,024 on Llama), up to 32,000 on vendor models (2,048 on the Llama edge models). Each model's own most is in `GET /api/ai/v1/models`; over it is a 400 naming the model. |
| temperature | 0–2 (Claude models are capped at 1). |
| tier | For harakumo-1: fast, balanced or deep. |
| stream | true for server-sent events. |
| projectId | Attribute the spend to a project (or send an X-Harakumo-Project header). A key limited to one project acts for its own project without it. |

> An answer that stopped at max_tokens has `truncated: true` and a note on how to get the rest. The parameter table above applies here too, except that fields it does not list are ignored rather than refused; tools and JSON output need `/api/ai/v1/chat/completions`.

## Embeddings

`POST /api/ai/v1/embeddings { model?, input, encoding_format? }` (the OpenAI SDK's `embeddings.create`) and the native `POST /api/ai/embeddings { input, model?, projectId? }` (SDK `hk.ai.embed`) return vectors from bge-small (384 dimensions), bge-base (768, the default) or bge-large (1,024). The models are English. They pair with Vector DB collections of the same size; Vector DB and AI Memory embed text for you with bge-base.

- Up to 100 inputs per call, each at most 2,000 characters: longer is a 400 `input_too_long` naming the input (`input[3]`), never cut. Split long text into chunks of about 1,000-1,500 characters.
- `encoding_format` is `float` (the default) or `base64`, which the OpenAI Node SDK asks for by default. `usage` has `prompt_tokens` and `cost`; `harakumo` has the request id and the dimensions.
- A model failure is a 502 `embedding_failed` and nothing is charged; with the AI Gateway switched off, 403 `ai_gateway_off`. A read-only key may embed (it is a read), charged to AI credits like any embedding.

## Price, limits and logs

- Hobby, Indie, Pro, Team and Scale include no AI usage: every request is pay as you go from the Balance (on a paid plan, the Balance of the workspace that pays for the plan, for every workspace it covers, under that workspace's spending limit; on Hobby, the workspace's own), at each model's per-token price: the model maker's list price plus 6%, and up to 5% more on third-party models to cover buying that usage (edge models never carry that 5%). On Hobby, vendor models need the owner's verified email. Workspaces that already have included AI keep it ($10 a month on a Pro subscription from before these plans and $100 a month on Enterprise), one amount per subscription shared by the workspaces it covers, used before the Balance. Team's $20 monthly usage credit pays for use past the plan, not for AI or domains, and what is not used does not carry over. `GET /api/ai/chat` lists the exact price of every model.
- Rate limit per workspace: 60 a minute on hobby, 120 a minute on indie, 600 a minute on pro, 2,000 a minute on team, 6,000 a minute on scale; chat and embeddings have separate buckets. Over it: 429 `ai_rate_limited` with Retry-After.
- Chat input up to 200,000 characters per request (413 over it); an embedding input is at most 2,000 characters (400 `input_too_long`).
- `GET /api/ai/requests` (SDK `hk.ai.requests`, connector `list_ai_requests`, CLI `harakumo ai log`) lists recent AI calls of every service, each with its `source` (gateway, vectors, memory or agent), `ref` (the collection, store or run) and request id: model, tokens, cost, speed, never the prompt or answer, kept 30 days. `requestId` finds the call behind a reply. It also has this month's spend by model, project and source, every charged call counted, failures included; with `projectId`, the list and the spend by model and by source are that project's, while the spend by project stays the workspace's. Billing → Balance has every AI charge this month by model.
- Switching models: `PUT /api/services/ai { "models": { "<id>": { "enabled": true } } }` (connector `update_service_config`) is merged per model id, so send only the ones you change; an unknown id or an `enabled` that is not true or false is a 400. With every model off, every request is refused, `harakumo-1` included (403 `ai_model_off`), and `harakumo-1` answers from Llama 3.3 70B only while Llama is switched on.
- A key limited to one project calls chat, the OpenAI-compatible URL, the playground, embeddings and the model list for its own project: leave `projectId` out, or name that project (naming another is refused). The spend is the workspace's, as with any key, and a read-only key cannot spend. `GET /api/ai/requests` covers the whole workspace and needs a workspace key.

## How a request is paid for

Before the model is called, Harakumo sets an estimate aside, sized from your input and `max_tokens` (for `harakumo-1`, at the price of the dearest model its tier may use; `GET /api/ai/chat` gives it as `hold_price_per_million`). Input is counted generously, one token per character outside plain ASCII plus a little per message, and an embedding is priced the same way. When the answer is back you are charged the exact cost of the model that answered, never more than was set aside, and the rest is released. The dashboard playground shows that estimate before you press Run.

- A stream that ends early, because you disconnected or the model stopped, is charged only for what was delivered; a failure arrives as an `error` event with code `stream_error`.
- Auto-reload, when the owner has turned it on, is tried before a 402 for credit. Requests made with an API key set it off only if the owner allowed that (Billing → Limits & alerts).
- If a request is lost on Harakumo's side before it is settled, the estimate set aside for it is settled automatically within about half an hour: at what it had delivered, or given back.

## When a request is refused

A refused or failed request costs nothing, with one exception: a model that spends its whole token budget without answering has used those tokens, and they are charged.

| Answer | When | Charged |
| --- | --- | --- |
| 402 `ai_credits_exhausted` | Included AI (on a plan that has it) and the Balance are both used up. | Nothing |
| 402 `ai_credits_insufficient` | Some credit is left, but less than this request's estimate. Lower `max_tokens`, shorten the prompt or choose a cheaper model. | Nothing |
| 402 `spend_limit_reached` | The estimate would take the month past the spending limit of the workspace whose Balance pays (on a paid plan, the paying workspace's). | Nothing |
| 402 `ai_request_too_large` | The estimate is more than one request may reserve: $2 on hobby, $10 on indie, $10 on pro, $10 on team, $10 on scale. | Nothing |
| 402 `email_unverified` | A vendor model on Hobby before the owner verified their email. `harakumo-1` answers from edge inference meanwhile. | Nothing |
| 403 `ai_gateway_off` / `ai_model_off` | The gateway, or this model, is switched off in Dashboard → AI Gateway. | Nothing |
| 404 `model_not_found` | No model has that id. `GET /api/ai/v1/models` lists them. | Nothing |
| 400 `unsupported_parameter` | A parameter the gateway, or this model, does not take (`param` names it). | Nothing |
| 503 `model_unavailable` | The model you named cannot be reached right now. It is never answered by another model under its name; use `harakumo-1` to fail over. | Nothing |
| 503 `no_model_available` | `harakumo-1` was asked for tools or JSON output and none of the models switched on here can give them. | Nothing |
| 429 `ai_rate_limited` | The per-minute limit. Wait Retry-After seconds. | Nothing |
| 400 or 413 `ai_request_refused` | The model refused the request itself (a parameter, or its size). It is not tried on other models, which would refuse it too. | Nothing |
| 422 `budget_exhausted` | The model used its whole `max_tokens` budget without an answer. Raise `max_tokens`. | The tokens it used |
| 502 `ai_unavailable` / `ai_provider_error` | No model could answer right now. Try again, or use `harakumo-1`, which fails over between vendors. | Nothing |

## Reference

**SDK**

```js
// The OpenAI SDK with a Harakumo key (hk.ai.baseURL is https://harakumo.com/api/ai/v1):
const ai = new OpenAI({ baseURL: hk.ai.baseURL, apiKey: process.env.HARAKUMO_API_KEY });
const { data } = await hk.ai.listModels();   // price, limits, supported_parameters, enabled

// Or the native endpoint:
const answer = await hk.ai.chat({ model: 'harakumo-1', prompt: 'Summarize edge functions.' });
console.log(answer.output, answer.modelUsed, answer.cost, answer.requestId);

for await (const ev of hk.ai.stream({ messages: [{ role: 'user', content: 'Write a haiku' }] })) {
  if (ev.event === 'delta') process.stdout.write(ev.data.text);
}

const { models, limits } = await hk.ai.models();                  // what this workspace can use, with prices
const { requests, month } = await hk.ai.requests({ limit: 20 });  // recent calls and this month's spend

// Embeddings for Vector DB (bge-small 384 · bge-base 768 · bge-large 1024):
const { embeddings, dimensions } = await hk.ai.embed(['fresh mango', 'ripe banana'], 'bge-base');
// hk.ai.generate({ prompt }) is the older name of a one-prompt chat.
```

**CLI**

```bash
harakumo ai "Write a haiku about the cloud" --model harakumo-1
harakumo ai models                    # price, context, tools and JSON output, on or off
harakumo ai log --source vectors      # recent AI calls of any service (never prompts or answers)
```

**REST**

```http
POST /api/ai/chat                   { "model", "messages" | "prompt", "system"?, "max_tokens"?, "temperature"?, "tier"?, "stream"?, "projectId"? }
GET  /api/ai/chat                   # the models and limits this workspace can use
POST /api/ai/v1/chat/completions    # OpenAI-compatible (base URL https://harakumo.com/api/ai/v1)
POST /api/ai/v1/embeddings          # OpenAI-compatible: { "model"?, "input", "encoding_format"? }
GET  /api/ai/v1/models              # OpenAI-compatible: price, context, limits, supported_parameters, enabled
POST /api/ai/playground             { "model", "prompt" }          # the one-shot alias
POST /api/ai/embeddings             { "input": ["…"], "model"?: "bge-base", "projectId"? }   → { embeddings, dimensions }
GET  /api/ai/requests?limit=&projectId=&requestId=&source=    # recent calls and this month's spend
```
