# Knowledge

Write your product's knowledge into Omazy from your backend, know when it is ready, search it, and keep a local copy that answers first so most questions never cross the network.

Source: https://docs.omazy.ai/build-on-omazy/knowledge/

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

Each workspace has a knowledge base. Your backend writes documents into it,
Omazy splits them into passages and indexes them, and a search returns the
passages that answer a question. The same knowledge grounds the workspace's
agent, so your own prompts and the agent never disagree about the facts.

| Scope | Lets a token |
|---|---|
| `kb:write` | Add, change and delete documents, upload files, crawl a website |
| `kb:read` | List and read documents, export what changed |
| `kb:search` | Search |

A customer's token made through the Enterprise API holds all three.

## Write documents

```ts
export async function publishPolicy(omazy: Omazy, policy: { id: string; revision: number; title: string; text: string }) {
  return omazy.knowledge.documents.create(
    { title: policy.title, content: policy.text, language: 'en' },
    // One key per revision: a retry after a dropped connection adds nothing twice.
    { idempotencyKey: `policy-${policy.id}-r${policy.revision}` },
  )
}

export async function changePolicy(omazy: Omazy, documentId: string, text: string) {
  return omazy.knowledge.documents.update(documentId, { content: text })
}

export async function uploadHandbook(omazy: Omazy, pdf: ArrayBuffer) {
  return omazy.knowledge.importFile(pdf, {
    filename: 'staff-handbook.pdf',
    contentType: 'application/pdf',
    idempotencyKey: 'handbook-2026-11',
  })
}
```

- **Give each new document an idempotency key** made from your own ids, such
  as the policy id and its revision. Then the client retries the request after
  a dropped connection, and the platform adds the document once. Without a
  key, a create is sent once and never retried, because a second one would
  add a second document.
- **Change a document with `update`.** Send only the fields that change. The
  document is indexed again, and the old text stays searchable until the new
  text is ready. The same change sent twice leaves the same document, so the
  client retries a change, and a delete, after a dropped connection. A delete
  retried after the first one went through answers `NOT_FOUND`: read it as gone.
- **Kinds.** `text` is the default. `faq`, `structured`, `pricing` and
  `catalog` take structured fields in `data`. See
  [Knowledge documents](/reference/core-api/knowledge-documents/#add-a-document).
- **Files.** `importFile` takes a PDF, a spreadsheet, an image or text, up to
  20 MB, and turns it into a document.

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

```ts
const doc = await omazy.knowledge.documents.create(
  { title: 'Refund policy', content: 'Refunds are returned within 5 working days.' },
  { idempotencyKey: 'policy-refunds-r3' },
)
```

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

```python
doc = omazy.knowledge.documents.create(
    title="Refund policy",
    content="Refunds are returned within 5 working days.",
    idempotency_key="policy-refunds-r3",
)
```

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

```go
doc, err := c.Knowledge.CreateDocument(omazy.WithIdempotencyKey(ctx, "policy-refunds-r3"), omazy.DocumentInput{
	Title:   "Refund policy",
	Content: "Refunds are returned within 5 working days.",
})
```

</TabItem>
</Tabs>

## Know when it is ready

A document is not searchable the moment you write it. Its `index.status` goes
from `queued` to `indexing` to `ready`, usually within a few seconds. Search
catches up a second or two after `ready`.

The simplest way to know is to read it again:

```ts
/** Waits until the agent can use a document. Usually a few seconds. */
export async function waitUntilReady(omazy: Omazy, id: string, timeoutMs = 60_000): Promise<KnowledgeDocument> {
  const until = Date.now() + timeoutMs
  for (;;) {
    const doc = await omazy.knowledge.documents.get(id)
    if (doc.index.status === 'ready') return doc
    if (doc.index.status === 'failed') throw new Error(`indexing failed: ${doc.index.error ?? 'no reason given'}`)
    if (Date.now() > until) throw new Error('still indexing; check again later')
    await new Promise((r) => setTimeout(r, 2000))
  }
}
```

A `failed` document is tried again by Omazy every few minutes. `index.error`
says why it failed, so a bad file can be fixed at its source.

A token can also have an events address, where Omazy posts `kb.updated` when a
document is indexed, fails or is deleted. A workspace owner sets it from the
console. For a workspace your account created there is no owner who can set
it yet, so poll as above. See
[Events](/reference/core-api/knowledge-documents/#events) for the event's
shape.

## Search

```ts
export async function search(omazy: Omazy, question: string): Promise<KnowledgePassage[]> {
  return omazy.knowledge.search(question, { top_k: 4 })
}
```

A search ranks passages by meaning, not by matching words. `top_k` defaults to
`8` and is at most `20`. Ask for what the prompt needs: four good passages beat
eight where the last four are about something else, and every passage is input
you pay for.

An empty list is an answer: the knowledge base does not know. Say so, rather
than asking a model to fill the gap.

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

```ts
const passages = await omazy.knowledge.search('Can I return a sofa?', { top_k: 4 })
```

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

```python
passages = omazy.knowledge.search("Can I return a sofa?", top_k=4)
```

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

```go
passages, err := c.Knowledge.Search(ctx, "Can I return a sofa?", omazy.SearchOptions{TopK: 4})
```

</TabItem>
</Tabs>

## A local copy, searched first

A search is a network call. For a product that answers in real time, such as
a kiosk or a voice line, every call inside a turn adds to the time before the
person hears anything. A product in production answers most knowledge
questions in about 12 ms from a local index in its own Worker, and calls
Omazy's search only when the local index finds nothing.

`knowledge.export` is built for that. It returns the documents that changed
after a version, with the exact passages search uses, and the version to ask
from next time.

```ts
type Chunk = { document_id: string; title: string; text: string }

/** Brings the local copy up to date. Run it on a schedule and after each write. */
export async function syncLocalCopy(env: Env, omazy: Omazy) {
  const kept = await env.KB.get('version')
  let since = kept === null ? undefined : Number(kept)
  let cursor: string | undefined

  for (;;) {
    const page = await omazy.knowledge.export({ since, cursor })
    if (page.resync) {
      // Too much was deleted to list. Drop the copy and start from nothing.
      await clearLocalCopy(env)
      since = undefined
      cursor = undefined
      continue
    }
    for (const doc of page.documents) {
      if (!doc.is_active) await env.KB.delete(`doc:${doc.id}`)
      else {
        const chunks: Chunk[] = doc.chunks.map((c) => ({ document_id: doc.id, title: doc.title, text: c.text }))
        await env.KB.put(`doc:${doc.id}`, JSON.stringify(chunks))
      }
    }
    for (const gone of page.deleted) await env.KB.delete(`doc:${gone.id}`)
    if (!page.next_cursor) {
      // The version is the same on every page. Keep it for next time.
      await env.KB.put('version', String(page.version))
      return
    }
    cursor = page.next_cursor
  }
}

declare function clearLocalCopy(env: Env): Promise<void>

/** Your own matcher over the local copy: keywords, a small vector index, anything fast. */
declare function searchLocal(env: Env, question: string): Promise<Chunk[]>

export async function passagesFor(env: Env, omazy: Omazy, question: string): Promise<string[]> {
  const local = await searchLocal(env, question)
  if (local.length > 0) return local.map((c) => c.text)
  // Nothing local: ask Omazy's search, which ranks by meaning.
  return (await omazy.knowledge.search(question, { top_k: 4 })).map((p) => p.content)
}
```

How it works:

1. The first sync has no version. It pages through everything and keeps the
   version at the end. The version is the same on every page.
2. Later syncs pass that version as `since`, and get only what changed: new and
   changed documents in `documents`, removed ones in `deleted`.
3. A document with `is_active: false` was switched off. It has no passages, so
   drop it.
4. `resync: true` means more was deleted than one export can list. Drop the
   copy and start again.
5. A document can come back unchanged, because it was indexed again. Storing
   the same document twice must be harmless, as it is above.

Run the sync on a schedule (a Cron Trigger every few minutes is plenty) and
after your own writes, once the document is `ready`. A change shows in an
export about two seconds after it is indexed.

The local matcher is yours. Keywords over the passage text, a small vector
index, or a hand-written table of the twenty questions people ask most: all
fine, as long as it says "nothing" when it has nothing, so the fallback runs.

### With events

When the token has an events address, a `kb.updated` event can start the sync
instead of the clock. `readSigned` from `@omazyai/sdk/server` checks the
signature over the raw body before parsing it.

```ts
export async function onEvent(request: Request, env: Env, omazy: Omazy): Promise<Response> {
  const signed = await readSigned<KnowledgeUpdatedEvent>(request, env.OMAZY_SIGNING_SECRET)
  if (!signed.ok) return new Response(null, { status: signed.status })
  const delivery = request.headers.get('x-omazy-delivery') ?? signed.body.id
  if (await env.KB.get(`seen:${delivery}`)) return new Response(null, { status: 204 })
  await syncLocalCopy(env, omazy)
  await env.KB.put(`seen:${delivery}`, '1', { expirationTtl: 86_400 })
  return new Response(null, { status: 204 })
}
```

The same event can arrive twice, because Omazy retries until it gets a `2xx`.
The delivery id drops the repeat.

## Reference

- [Knowledge documents](/reference/core-api/knowledge-documents/): every route and field
- [Knowledge and agent](/reference/core-api/knowledge-and-agent/): search and the agent turn
