Skip to content
API explorerProductOpen console

Quickstart on Cloudflare Workers

At the end of this page you have a Worker with one route, POST /ask. It takes a question, streams the answer back as it is written, and logs what the call used. About fifteen minutes, most of it waiting for npm install.

You need an install token for a workspace, with the ai:complete scope. A workspace owner creates one in the console under Settings, API tokens: see Authentication. For the usage step at the end, add usage:read.

In a Worker project with TypeScript (for example one made with npm create cloudflare@latest):

Terminal window
npm install https://github.com/omazyai/omazy-sdk/releases/download/v0.5.3/omazyai-sdk-0.5.3.tgz

The package is @omazyai/sdk. It has no dependencies and needs no Node compatibility flag: it uses fetch, crypto.subtle and the Worker’s own WebSocket.

Terminal window
npx wrangler secret put OMAZY_CORE_TOKEN

Paste the token when asked. For wrangler dev, put it in .dev.vars, which Wrangler reads locally and which belongs in .gitignore:

Terminal window
OMAZY_CORE_TOKEN="cai_<prefix>.<the-rest-of-your-token>"

Never put the token in wrangler.toml, in vars, or in anything the browser loads. Anyone who has it can spend the workspace’s budget.

src/index.ts:

import { Omazy, OmazyError } from '@omazyai/sdk'
interface Env {
OMAZY_CORE_TOKEN: string
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url)
if (request.method !== 'POST' || url.pathname !== '/ask') {
return new Response('Not found', { status: 404 })
}
// Check here that the request comes from a signed-in user of yours.
const { question } = await request.json<{ question: string }>()
const omazy = new Omazy({ token: env.OMAZY_CORE_TOKEN })
const events = omazy.ai.stream({
system: 'You answer questions about our opening hours in at most three sentences.',
messages: [{ role: 'user', content: question }],
max_tokens: 300,
// The same question may be answered from the gateway's cache for five
// minutes. Send 0 instead when the request carries live data.
cache_ttl: 300,
})
const encoder = new TextEncoder()
const body = new ReadableStream<Uint8Array>({
async start(controller) {
try {
for await (const ev of events) {
if (ev.type === 'delta') {
controller.enqueue(encoder.encode(ev.text))
} else {
const { usage, model, cache_hit } = ev.result
console.log(JSON.stringify({ evt: 'omazy_usage', model, cache_hit: cache_hit ?? false, ...usage }))
}
}
} catch (err) {
const e = err instanceof OmazyError ? err : null
console.log(JSON.stringify({ evt: 'omazy_failed', code: e?.code ?? 'UNKNOWN', request_id: e?.requestId }))
controller.enqueue(encoder.encode('\nSorry, I cannot answer that right now.'))
}
controller.close()
},
})
return new Response(body, { headers: { 'content-type': 'text/plain; charset=utf-8' } })
},
} satisfies ExportedHandler<Env>

What each part does:

  • omazy.ai.stream() sends the request when you start reading it. delta events carry text as the model writes it. One done event carries the whole result. If the stream reports an error, or ends before done, the loop throws an OmazyError, so you never mistake half an answer for a whole one.
  • No model is named, so the call runs on the model the workspace’s agent answers on. Change it there and this route follows. To pin one, pass model, such as openai/gpt-4o-mini; see Which model runs.
  • max_tokens is the most one answer can cost you. Set it to what the answer needs.
  • The catch keeps the error’s code and requestId. The code is what you branch on; the request id is what Omazy needs to find the call.
Terminal window
npx wrangler dev
Terminal window
curl -N -X POST http://localhost:8787/ask \
-d '{ "question": "Are you open on Sunday?" }'

The text arrives in pieces. In the terminal running wrangler dev, one line says what the call used:

{"evt":"omazy_usage","model":"openai/gpt-4o","cache_hit":false,"input_tokens":31,"output_tokens":22,"cached_input_tokens":0}

With a wrong token the answer is the apology, and the log says why:

{"evt":"omazy_failed","code":"UNAUTHORIZED","request_id":"req_3d4e2b9552a045b69085f389a440bfe6"}

Deploy with npx wrangler deploy.

Every answer carries usage: input tokens, output tokens, and the input tokens the provider served from its prompt cache. Add them up per request if you bill your own customers by use.

For totals, ask Omazy. usage.get returns what the workspace used and what it cost, per UTC day, the last 30 days unless you give a range. It needs the usage:read scope.

const today = new Date().toISOString().slice(0, 10)
const report = await omazy.usage.get({ from: today, to: today })
report.totals.model_calls // calls to a model, cache hits included
report.totals.cache_hits // answered from the cache: free
report.totals.cost_usd // what the calls cost
report.totals.ai_turns // what your plan counts

The fields are listed on Client libraries.

The gateway in front of the model keeps the replies it gave. When the same request arrives again, byte for byte, it can answer from the store in a few milliseconds, at no cost, without using an AI turn. cache_ttl is your say over that for each call:

cache_ttl Means
left out The gateway’s own setting
0 Never from the cache. The model answers
60 to 2592000 A stored reply to this exact request may be served for that many seconds

The rule: send 0 on any request that carries live data. If the prompt includes a booking, a stock level or today’s calendar that you read just before, the same request can need a different answer a minute later. There is no way to clear a stored reply early, so a short cache_ttl is the only way to keep one fresh.

A reply from the cache has cache_hit: true on the result. Its usage is the stored reply’s.

import { Omazy } from '@omazyai/sdk'
const omazy = new Omazy({ token: process.env.OMAZY_CORE_TOKEN! })
for await (const ev of omazy.ai.stream({
system: 'You answer in one sentence.',
messages: [{ role: 'user', content: 'What is a webhook?' }],
cache_ttl: 300,
})) {
if (ev.type === 'delta') process.stdout.write(ev.text)
else console.log('\n', ev.result.usage, ev.result.cache_hit ?? false)
}

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

Founded by Mosthofa Imran · imran@omazy.ai