Skip to content
API explorerProductOpen console

Completions

POST /ai/complete

One model call through the gateway. Scope: ai:complete.

You send the conversation, the model answers, and you get the text and the token count back. Nothing is stored between calls. A second call knows about the first only if you send the first one’s messages again.

{
"system": "You are a support engineer. Answer briefly.",
"messages": [
{ "role": "user", "content": "Our export job fails at midnight. Why?" }
],
"max_tokens": 600,
"temperature": 0.2
}
Field Type Notes
messages array Required. The conversation, oldest first. See below.
system string Instructions for the model. They go here, not in a message.
max_tokens integer Ceiling on the reply. Default 1024, at most 8192.
temperature number 0 to 2. Left out, the model profile’s own setting applies.
tools array Tools the model may ask you to run. See Tools.
tool_choice string auto, any or none. Left out, it behaves as auto.
model string Run on this model instead. See Which model runs.
profile string Run on another model profile. See Which model runs.
stream boolean true answers as Server-Sent Events. See Streaming.
cache_ttl integer 0, or 60 to 2592000 seconds. See Response cache.
app string The app’s handle. Needed only when the workspace has more than one app.

Each message has a role and a content string.

Message field Notes
role user or assistant. Nothing else is accepted.
content The text of the turn.
tool_calls On an assistant turn, the tool calls the model made.
tool_results On the user turn that follows, your answers to those calls.

There is no system role. A message with one is refused with a 400 that tells you to put instructions in system. A message must carry something: text, tool calls or tool results.

{
"success": true,
"data": {
"text": "The job starts before the nightly backup releases its lock.",
"stop_reason": "stop",
"model": "openai/gpt-4o",
"usage": { "input_tokens": 41, "output_tokens": 14, "cached_input_tokens": 0 }
}
}
Field Notes
text The reply. Empty when the model only called tools.
tool_calls Present when the model wants tools run. Each has id, name and input.
stop_reason Why the model stopped, exactly as the provider reported it.
model The model the call was sent to.
usage input_tokens, output_tokens and cached_input_tokens for this call.
cache_hit true when the reply came from the response cache. Left out otherwise.

stop_reason is passed through from the provider, and providers do not agree on its vocabulary. One says stop where another says end_turn. Do not use it to decide whether to run tools. Check whether tool_calls is present instead.

A request that breaks one of these is refused with 400 BAD_REQUEST before any model is called, so a malformed request costs nothing.

Limit Value
Messages per call 200
Tools per call 64
Total text per call 400000 bytes
max_tokens 8192
temperature 0 to 2
Time allowed for the call 120 seconds

Total text is system, plus every message’s content, plus every tool result’s content. It is counted in UTF-8 bytes, although the error message says characters. English text is one byte a character. Bangla, Arabic and most other scripts are two or three, so they reach the ceiling sooner than a character count suggests.

Per-token rate limits are on Errors and limits.

You describe tools, the model decides when to call one, and you run it. Omazy relays the call and never executes anything. That keeps your systems behind your own server, where their credentials already are.

A tool has a name, an optional description, and an input_schema that is a JSON Schema object.

{
"messages": [{ "role": "user", "content": "Where is order 8841?" }],
"tools": [
{
"name": "order_status",
"description": "Look up the current status of an order by its number.",
"input_schema": {
"type": "object",
"properties": { "order_id": { "type": "string" } },
"required": ["order_id"]
}
}
]
}

The description is what the model reads to decide whether this is the right tool. Write it for that reader.

When the model wants the tool, the reply carries tool_calls:

{
"text": "",
"tool_calls": [
{ "id": "call_1", "name": "order_status", "input": { "order_id": "8841" } }
],
"stop_reason": "tool_calls",
"model": "openai/gpt-4o",
"usage": { "input_tokens": 88, "output_tokens": 19, "cached_input_tokens": 0 }
}

Run the tool yourself. Then call again with the whole conversation: the original messages, the assistant turn exactly as it came back, and a user turn holding your results. Send the same tools again too.

{
"messages": [
{ "role": "user", "content": "Where is order 8841?" },
{
"role": "assistant",
"content": "",
"tool_calls": [
{ "id": "call_1", "name": "order_status", "input": { "order_id": "8841" } }
]
},
{
"role": "user",
"content": "",
"tool_results": [
{ "call_id": "call_1", "content": "{\"status\":\"out for delivery\"}" }
]
}
],
"tools": [
{
"name": "order_status",
"description": "Look up the current status of an order by its number.",
"input_schema": {
"type": "object",
"properties": { "order_id": { "type": "string" } },
"required": ["order_id"]
}
}
]
}

A tool result has three fields.

Field Notes
call_id The id of the call it answers.
content The result, as a string. Serialise JSON yourself.
is_error true when the tool failed. The model then knows not to trust content as data.

Repeat until a reply arrives with no tool_calls. Put a ceiling on the number of rounds. A model that keeps calling the same tool is spending your budget on every lap.

tool_choice steers this. auto lets the model decide, any requires it to call a tool, and none forbids it.

The AI gateway in front of the model keeps the replies it gave. When the same request arrives again, byte for byte, it can answer with the stored reply in a few milliseconds without calling the model. The match is on the whole request: the system text, every message, any knowledge passages and tool results you sent, and the model. Change any of it and it is a new request.

cache_ttl is your say over that for one call:

cache_ttl What happens
left out The gateway’s own setting applies.
0 The reply never comes from the cache. The model answers.
60 to 2592000 A reply stored for this request may be served again for that many seconds.

Send 0 on any request whose answer depends on something that changes while the request stays the same, for example a calendar or a booking you read just before. There is no way to clear a stored reply early; a short cache_ttl is how you keep one fresh.

A reply that came from the cache says "cache_hit": true. It cost nothing and does not use one of the plan’s AI turns. Its usage is the stored reply’s.

Three rules, in order.

  1. Nothing named. The call runs on the model profile your app’s agent answers on. You get the agent’s model, including a change somebody made to it in the console this morning.
  2. profile named. The call runs on that model profile instead. An unknown name is refused with 400.
  3. model named. The call runs on that model. It must be one your workspace may use: a model your plan includes, or a model listed on a provider your workspace has connected with its own credential. Anything else is refused with 403 FORBIDDEN and a message naming the model. A model id carries its provider, for example openai/gpt-4o-mini.

Most callers should name nothing. Then the agent and your backend move to a new model together, and one setting decides it. Name a model when a job has a real reason to differ, such as a cheap model for bulk classification.

temperature follows the same idea: yours if you send one, the profile’s otherwise.

See Providers and models for how a workspace connects its own provider.

Send "stream": true and the reply arrives as Server-Sent Events while the model writes, with Content-Type: text/event-stream.

event: delta
data: {"text":"The job starts "}
event: delta
data: {"text":"before the nightly backup releases its lock."}
event: done
data: {"text":"The job starts before the nightly backup releases its lock.","stop_reason":"stop","model":"openai/gpt-4o","usage":{"input_tokens":41,"output_tokens":14,"cached_input_tokens":0}}
Event Data Meaning
delta {"text": "..."} The next piece of the reply. Append it.
done The full result Sent once, last. The same object a non-streamed call returns in data.
error {"code": "...", "message": "...", "request_id": "..."} Sent once, last, in place of done.

Four things to know before you write the reader.

The frames are not wrapped in the envelope. A done frame is the result itself, with no success and no data around it.

Only text streams. Tool calls do not arrive in pieces. They are in the done frame, complete.

A refusal before the stream starts is ordinary JSON. A bad token, a missing scope, a rate limit or a malformed request answers with the usual status code and error envelope. Check the status before you start reading events.

A failure after the stream starts is an error frame on a 200. A spent budget, a model your workspace may not use and a provider failure all arrive this way, because the status line has already been sent. The frame carries the same code a refused call carries, such as PAYMENT_REQUIRED or UPSTREAM_REJECTED, so branch on it the same way. It also carries the request_id to quote when you tell us about a failure.

Some models do not stream. The call still works: the whole reply arrives as one delta, then done.

This runs on Node 18 or later, and on any runtime with fetch and ReadableStream. It has no dependencies.

type Usage = {
input_tokens: number
output_tokens: number
cached_input_tokens: number
}
type Completion = {
text: string
tool_calls?: { id: string; name: string; input: unknown }[]
stop_reason: string
model: string
usage: Usage
}
const CORE = 'https://mw.omazy.ai/api/v1/core'
export async function streamCompletion(
request: Record<string, unknown>,
onText: (piece: string) => void,
): Promise<Completion> {
const res = await fetch(`${CORE}/ai/complete`, {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.OMAZY_CORE_TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ ...request, stream: true }),
})
// Refused before the stream began: an ordinary error envelope.
if (!res.ok || !res.body) {
const failure = await res.json().catch(() => null)
const code = failure?.error?.code ?? `HTTP_${res.status}`
throw new Error(`${code}: ${failure?.error?.message ?? 'request failed'}`)
}
const reader = res.body.getReader()
const decoder = new TextDecoder()
let buffer = ''
for (;;) {
const { value, done } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
// A frame ends at a blank line. A network chunk can hold half a frame or
// several, so only complete frames leave the buffer.
let end = buffer.indexOf('\n\n')
while (end !== -1) {
const frame = buffer.slice(0, end)
buffer = buffer.slice(end + 2)
end = buffer.indexOf('\n\n')
let event = ''
let data = ''
for (const line of frame.split('\n')) {
if (line.startsWith('event: ')) event = line.slice(7)
else if (line.startsWith('data: ')) data += line.slice(6)
}
if (!data) continue
const payload = JSON.parse(data)
if (event === 'delta') onText(payload.text)
else if (event === 'done') return payload as Completion
else if (event === 'error') throw new Error(payload.message)
}
}
throw new Error('the stream ended without a done frame')
}

Use it like this:

const result = await streamCompletion(
{
system: 'You are a support engineer. Answer briefly.',
messages: [{ role: 'user', content: 'Our export job fails at midnight. Why?' }],
},
(piece) => process.stdout.write(piece),
)
console.log(`\n${result.usage.output_tokens} tokens from ${result.model}`)

The last line of the function matters. A connection that drops mid-reply ends the stream with neither done nor error, and a reader that treats that as success hands its caller half an answer.

If you are passing the stream on to a browser, your server is the right place to do it. Read the events here and send your own to the page. The token never leaves the server.

Omazy CX documentation. One voice. Every channel. Always on.

Founded by Mosthofa Imran · imran@omazy.ai