# Quickstart on Cloudflare Workers

Install the Omazy SDK in a Worker, keep the token as a Worker secret, stream a completion to the browser, read what it used, and choose how long a reply may come from the cache.

Source: https://docs.omazy.ai/build-on-omazy/quickstart-cloudflare-workers/

import { Tabs, TabItem } from '@astrojs/starlight/components'

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](/reference/core-api/authentication/#getting-one). For
the usage step at the end, add `usage:read`.

## 1. Install the SDK

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

```sh
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.

## 2. Keep the token as a secret

```sh
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`:

```sh
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

`src/index.ts`:

```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](/reference/core-api/completions/#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.

## 4. Run it

```sh
npx wrangler dev
```

```sh
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:

```json
{"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:

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

Deploy with `npx wrangler deploy`.

## 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.

```ts
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](/reference/core-api/client-libraries/).

## 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

<Tabs syncKey="sdk-lang">
<TabItem label="TypeScript">

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

</TabItem>
<TabItem label="Python">

```python
import os
from 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))
```

</TabItem>
<TabItem label="Go">

```go
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)
```

</TabItem>
</Tabs>

## Next

- [Knowledge](/build-on-omazy/knowledge/): answer from your own documents
- [Many customers](/build-on-omazy/many-customers/): one workspace and one token per customer
- [Production checklist](/build-on-omazy/production-checklist/): before real traffic
