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.
1. Install the SDK
Section titled “1. Install the SDK”In a Worker project with TypeScript (for example one made with
npm create cloudflare@latest):
npm install https://github.com/omazyai/omazy-sdk/releases/download/v0.5.3/omazyai-sdk-0.5.3.tgzThe 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.
2. Keep the token as a secret
Section titled “2. Keep the token as a secret”npx wrangler secret put OMAZY_CORE_TOKENPaste the token when asked. For wrangler dev, put it in .dev.vars, which
Wrangler reads locally and which belongs in .gitignore:
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.
3. Stream a completion
Section titled “3. Stream a completion”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.deltaevents carry text as the model writes it. Onedoneevent carries the whole result. If the stream reports an error, or ends beforedone, the loop throws anOmazyError, 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 asopenai/gpt-4o-mini; see Which model runs. max_tokensis the most one answer can cost you. Set it to what the answer needs.- The
catchkeeps the error’scodeandrequestId. The code is what you branch on; the request id is what Omazy needs to find the call.
4. Run it
Section titled “4. Run it”npx wrangler devcurl -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.
5. Read usage
Section titled “5. Read usage”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 includedreport.totals.cache_hits // answered from the cache: freereport.totals.cost_usd // what the calls costreport.totals.ai_turns // what your plan countsThe fields are listed on Client libraries.
6. Choose the cache
Section titled “6. Choose the cache”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.
The same call in Python or Go
Section titled “The same call in Python or Go”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)}import osfrom omazy import Omazy
omazy = Omazy(os.environ["OMAZY_CORE_TOKEN"])
for ev in omazy.ai.stream( [{"role": "user", "content": "What is a webhook?"}], system="You answer in one sentence.", cache_ttl=300,): if ev["type"] == "delta": print(ev["text"], end="", flush=True) else: print("\n", ev["result"]["usage"], ev["result"].get("cache_hit", False))c := omazy.New(os.Getenv("OMAZY_CORE_TOKEN"))
res, err := c.AI.Stream(ctx, omazy.CompleteRequest{ System: "You answer in one sentence.", Messages: []omazy.Message{{Role: "user", Content: "What is a webhook?"}}, CacheTTL: omazy.CacheFor(5 * time.Minute), // omazy.NoCache() for live data}, func(text string) { fmt.Print(text) })if err != nil { return err}fmt.Println(res.Usage, res.CacheHit)- Knowledge: answer from your own documents
- Many customers: one workspace and one token per customer
- Production checklist: before real traffic
Omazy CX documentation. One voice. Every channel. Always on.
Founded by Mosthofa Imran · imran@omazy.ai
© 2026 Omazy CX