# Call Omazy from your own backend

From a Core API token to a streamed answer grounded in your knowledge base, in one file of TypeScript, with the failures handled.

Source: https://docs.omazy.ai/guides/call-omazy-from-your-backend/

Nordwell is the furniture shop from [Build your agent](/guides/build-your-agent/).
Their agent answers on the website and on WhatsApp. Nordwell is invented. The
API calls on this page are the real ones.

Nordwell now has a developer, Tariq, and a customer account area he built
himself. On the order page he wants a small box: ask a question about delivery
and get an answer, written from the same delivery information the agent
already uses. He wants his own prompt, because an answer beside an order should
be three sentences and not a conversation. He wants it to appear as it is
written, not after a pause.

That is three calls and about a hundred lines. This guide builds it in the order
the pieces depend on each other.

| Step | What you have at the end |
|---|---|
| 1. Get a token | A credential on your server, and proof that it works |
| 2. Search the knowledge base | The passages that answer the question |
| 3. Build the prompt | Instructions with those passages inside |
| 4. Stream the completion | The answer arriving piece by piece |
| 5. Serve it | An endpoint your own page can call |
| 6. Handle what goes wrong | A feature that fails politely |

## Before you start: is this the right tool?

Tariq had a simpler option. `POST /agent/turn` returns the agent's own reply in
one call, with the brief and the knowledge base already applied. He did not use
it for two reasons that are specific to his page. The agent's reply is not
streamed. And it speaks in the agent's voice, with its length and its follow-up
questions, where he wanted his own.

If neither of those matters to you, use the agent turn and stop here. It is
described in [Knowledge and agent](/reference/core-api/knowledge-and-agent/).

## 1. Get a token

Core API tokens are issued by the Omazy team today. There is no screen for it.
Tariq asked for a token for Nordwell's workspace and said what the server
needed to do: search the knowledge base and run completions. He got back a
token carrying two scopes, `kb:search` and `ai:complete`, and nothing else.

Ask for only what you will call. A token that can search and complete cannot
place a phone call, and if it ever leaks, that is the difference between an
awkward afternoon and a bad week.

The token is shown once. Tariq put it in the server's environment:

```sh
export OMAZY_CORE_TOKEN="cai_<prefix>.<the-rest-of-your-token>"
```

It stays there. It does not go in the page, in the mobile app, or in the
repository. The browser will talk to Tariq's server, and only his server will
talk to Omazy.

Then he checked it:

```sh
curl https://mw.omazy.ai/api/v1/core/whoami \
  -H "Authorization: Bearer $OMAZY_CORE_TOKEN"
```

```json
{
  "success": true,
  "data": {
    "workspace_id": "5b0c1c5e-8f0e-4a55-9a51-2f6d1f3f6a10",
    "app_slug": "account-area",
    "scopes": ["kb:search", "ai:complete"],
    "status": "active"
  }
}
```

The right workspace and the two scopes he asked for. Thirty seconds spent here
saves an hour of wondering later whether a `403` is his code or his token.

## 2. Search the knowledge base

Everything from here goes in one file, `delivery-answer.ts`. It starts with the
address, the header, and one way to turn a failed response into an error that
keeps its code.

```ts
import { createServer } from 'node:http'

const CORE = 'https://mw.omazy.ai/api/v1/core'

const headers = {
  Authorization: `Bearer ${process.env.OMAZY_CORE_TOKEN}`,
  'Content-Type': 'application/json',
}

class OmazyError extends Error {
  status: number
  code: string
  constructor(status: number, code: string, message: string) {
    super(message)
    this.status = status
    this.code = code
  }
}

async function failure(res: Response): Promise<OmazyError> {
  const body = await res.json().catch(() => null)
  return new OmazyError(
    res.status,
    body?.error?.code ?? 'UNKNOWN',
    body?.error?.message ?? `HTTP ${res.status}`,
  )
}
```

Keeping `code` matters. Step 6 branches on it, and a plain `Error` with a
message would leave nothing reliable to branch on.

Now the search. It is the same retrieval that grounds the agent's replies in
live chat, so Tariq's box and Nordwell's agent read from one source.

```ts
type Passage = {
  document_id: string
  title: string
  content: string
  language?: string
  score: number
}

async function searchKnowledge(question: string): Promise<Passage[]> {
  const res = await fetch(`${CORE}/knowledge/search`, {
    method: 'POST',
    headers,
    body: JSON.stringify({ query: question, top_k: 4 }),
  })
  if (!res.ok) throw await failure(res)
  const body = await res.json()
  return body.data.passages
}
```

`top_k` is `4` on purpose. The default is `8` and the ceiling is `20`, and more
passages is not more accuracy. Every passage is input the model has to read and
you have to pay for, and the fifth-best match is usually about something else.

For "Do you deliver on Fridays?" the response looks like this:

```json
{
  "success": true,
  "data": {
    "passages": [
      {
        "document_id": "0f6c2f0a-6d0b-4a53-8a34-0c0b2a1b7e55",
        "title": "Delivery days and times",
        "content": "We deliver Monday to Saturday. Friday deliveries run from 10am to 6pm.",
        "language": "en",
        "score": 0.86
      }
    ]
  }
}
```

## 3. Build the prompt

The passages go into `system`, with the instruction that makes them matter.

```ts
function systemPrompt(passages: Passage[]): string {
  const context = passages
    .map((p, i) => `[${i + 1}] ${p.title}\n${p.content}`)
    .join('\n\n')

  return [
    'You answer delivery questions for Nordwell customers.',
    'Use only the passages below. If they do not answer the question, say so and offer to pass it to the team.',
    'Answer in at most three sentences.',
    '',
    context,
  ].join('\n')
}
```

The second line is the one doing the work. Without it, a model handed a passage
about delivery days will cheerfully answer a question about delivery prices
from what it knows about furniture shops in general. "Use only the passages" is
what turns retrieval into grounding.

The instructions go in `system`, not in a message. A completion accepts only
`user` and `assistant` messages and refuses anything else.

## 4. Stream the completion

`"stream": true` turns the response into Server-Sent Events: `delta` frames
carrying text, then one `done` frame carrying the full result, or one `error`
frame.

```ts
type Completion = {
  text: string
  stop_reason: string
  model: string
  usage: { input_tokens: number; output_tokens: number; cached_input_tokens: number }
}

async function streamCompletion(
  request: Record<string, unknown>,
  onText: (piece: string) => void,
): Promise<Completion> {
  const res = await fetch(`${CORE}/ai/complete`, {
    method: 'POST',
    headers,
    body: JSON.stringify({ ...request, stream: true }),
  })
  if (!res.ok || !res.body) throw await failure(res)

  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 })

    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 OmazyError(200, 'STREAM_ERROR', payload.message)
    }
  }
  throw new OmazyError(200, 'STREAM_ERROR', 'the stream ended without a done frame')
}
```

Three details in there are easy to get wrong.

The buffer. A chunk from the network is not a frame. It can end halfway through
one, or carry three. Only text up to a blank line is a complete frame, and the
rest waits for the next chunk.

The decoder's `stream: true`. A chunk can also end halfway through a character,
which happens constantly in Bangla and never in an English test. That option
makes the decoder hold the half until the rest arrives.

The last line. A dropped connection ends the stream with no `done` and no
`error`. Returning quietly at that point would hand the customer half a
sentence as if it were the answer.

Now the two halves meet:

```ts
async function answer(question: string, onText: (piece: string) => void) {
  const passages = await searchKnowledge(question)

  // Nothing found is an answer in itself. Do not ask a model to fill the gap.
  if (passages.length === 0) {
    onText('I could not find that in our delivery information. I will pass your question to the team.')
    return { grounded: false, usage: null }
  }

  const result = await streamCompletion(
    {
      system: systemPrompt(passages),
      messages: [{ role: 'user', content: question }],
      max_tokens: 300,
      temperature: 0.2,
    },
    onText,
  )

  return { grounded: true, usage: result.usage }
}
```

Tariq did not name a model. The completion runs on the model Nordwell's agent
answers on, so when Rina changes the agent's model in the console, this box
moves with it and nobody has to remember that it exists.

The empty case is handled before the model is called. An empty `passages` array
is a `200`, not an error, and it is the most useful thing the search can tell
you: we do not know. Sending the question on anyway buys a confident guess.

`max_tokens` is `300` because three sentences never need more, and because the
ceiling you set is the ceiling on what one request can cost.

## 5. Serve it

The browser calls Tariq's server. His server calls Omazy and passes the text
along as it arrives.

```ts
createServer(async (req, res) => {
  if (req.method !== 'POST' || req.url !== '/api/delivery-answer') {
    res.writeHead(404).end()
    return
  }

  // Check here that the request comes from a signed-in customer of yours.

  let raw = ''
  for await (const chunk of req) raw += chunk
  const { question } = JSON.parse(raw)

  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' })
  try {
    await answer(question, (piece) => res.write(piece))
  } catch (err) {
    const code = err instanceof OmazyError ? err.code : 'UNKNOWN'
    console.error('omazy call failed', code, err)
    res.write('\nSorry, I cannot answer that right now.')
  }
  res.end()
}).listen(3000)
```

The file is TypeScript with nothing but type annotations added, so Node 24 or
later runs it directly:

```sh
node delivery-answer.ts
```

```sh
curl -N http://localhost:3000/api/delivery-answer \
  -d '{ "question": "Do you deliver on Fridays?" }'
```

```
Yes. Friday deliveries run from 10am to 6pm.
```

The comment in the middle of the handler is not decoration. This endpoint
spends Nordwell's AI budget every time it is called, and it is on the public
internet. Whatever decides who may use the rest of the account area must decide
who may use this too. Omazy's rate limit protects Omazy. It will not stop a
stranger running your budget down through your own endpoint.

## 6. Handle what goes wrong

The handler above already fails politely. What is left is deciding which
failures deserve more than an apology.

They arrive in two ways, and the difference decides how much you can know.

**Before the stream starts**, a refusal is an ordinary status code with the
error envelope. `failure()` turns it into an `OmazyError` with the code intact.

| Status and code | What it means | What Tariq's code does |
|---|---|---|
| `401 UNAUTHORIZED`, `403 FORBIDDEN` | The token is wrong, revoked, or lacks a scope | Alerts the team. A deployment mistake, not a customer's problem |
| `429 RATE_LIMIT_EXCEEDED` | More AI calls from this token in ten minutes than your plan allows (`600` on the free plan) | Waits a few seconds and tries once more |
| `400 BAD_REQUEST` | The request is malformed or too large | Logs it. This one is a bug in his own code |

**After the stream starts**, the status line has already gone out as `200`. A
failure arrives as an `error` frame carrying a message and no code.
`STREAM_ERROR` is Tariq's own label for that case, not one of Omazy's.

Everything that goes wrong while the model is being called lands here: a
provider failure, a provider rate limit, and a spent budget.

The spent budget is the one Tariq most wanted to catch, because it is the one
that should change the page. A customer who types a question and gets an
apology every time has been shown a broken feature. One who never sees the box
has not.

On a streamed call he cannot catch it by code. The frame's message reads
`the workspace's AI budget is spent`, and a message is a sentence that may be
reworded. So every `STREAM_ERROR` is logged with its message and counted, and
the team is alerted when several arrive in a row. A person reads the message
and knows at once which kind of problem it is.

If your page must tell a spent budget apart in code, make the call without
`stream`. There it is a real `402 PAYMENT_REQUIRED`, at the price of the answer
arriving all at once. Retrying it cannot help. It clears when the budget does.

The full list of codes and limits is on
[Errors and limits](/reference/core-api/errors-and-limits/).

## What Tariq ended up with

One file, one token with two scopes, and no model vendor's key anywhere in
Nordwell's own code.

The answers on the order page come from the same delivery information as the
agent's, so when Rina corrects a delivery time in the knowledge base, both are
right from the next question. The spend appears in Nordwell's workspace as Core
API usage, apart from the agent's own conversations, under the same budget.

## Where to go next

- [Completions](/reference/core-api/completions/) for tools, so the box can
  look up the order it is sitting beside
- [Knowledge and agent](/reference/core-api/knowledge-and-agent/) for the agent
  turn, when you want the agent's own voice
- [Authentication](/reference/core-api/authentication/) for every scope
