# Knowledge and agent

POST /knowledge/search returns passages from your knowledge base. POST /agent/turn returns your agent's reply. What each sends back, and what the agent turn does not do.

Source: https://docs.omazy.ai/reference/core-api/knowledge-and-agent/

Two routes that use what you have already taught your agent.

`/knowledge/search` gives you the raw passages and leaves the answer to you.
`/agent/turn` gives you the answer your agent would give, brief and all. Reach
for the first when you are writing your own prompt, and the second when you
want the same voice your customers already hear.

Both run against the app's agent. That is its published agent, or its newest
draft when nothing is published yet. An app with no agent answers `404`.

## Search the knowledge base

```
POST /knowledge/search
```

Scope: `kb:search`.

It runs the same retrieval that grounds your agent's replies in live chat, so
what comes back here is what the agent would have been shown.

```sh
curl https://mw.omazy.ai/api/v1/core/knowledge/search \
  -H "Authorization: Bearer $OMAZY_CORE_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "query": "How long do refunds take?", "top_k": 3 }'
```

| Field | Type | Notes |
|---|---|---|
| `query` | string | Required. At most `2000` bytes. |
| `top_k` | integer | How many passages to return. Default `8`, at most `20`. |
| `language` | string | The language of the conversation, such as `en` or `bn`. |
| `app` | string | The app's handle. Needed only when the workspace has more than one app. |

A `top_k` above `20` is lowered to `20` without an error.

```json
{
  "success": true,
  "data": {
    "passages": [
      {
        "document_id": "0f6c2f0a-6d0b-4a53-8a34-0c0b2a1b7e55",
        "title": "Refund policy",
        "content": "Refunds are returned to the original payment method within 7 working days.",
        "language": "en",
        "score": 0.83
      }
    ]
  }
}
```

| Field | Notes |
|---|---|
| `document_id` | The document the passage came from. |
| `title` | That document's title. |
| `content` | The passage text. |
| `language` | The passage's language, when it is known. |
| `score` | Relevance. Higher is closer. Compare scores within one response only. |

No match is not an error. You get `200` with an empty `passages` array, and
your code should treat that as "we do not know" and not ask a model to improvise.

The search has `60` seconds to answer. Your query is embedded to run it, and
that small cost is recorded as Core API usage like any other model call.

This route reads the knowledge base. To add to it from your backend, see
[Knowledge documents](/reference/core-api/knowledge-documents/). Documents also
go in through the console, as described in [Knowledge](/how-to/agent/knowledge/).

## Run one turn of your agent

```
POST /agent/turn
```

Scope: `agent:run`.

One message in, one reply out, produced the way your agent produces it: the
brief, the knowledge base, guided flows and connected tools all take part. There
is no widget and no visitor. Your server is the other side of the conversation.

```sh
curl https://mw.omazy.ai/api/v1/core/agent/turn \
  -H "Authorization: Bearer $OMAZY_CORE_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "message": "Do you deliver on Fridays?" }'
```

| Field | Type | Notes |
|---|---|---|
| `message` | string | Required. At most `8000` bytes. |
| `session_id` | string | A UUID. Send back the one the first turn returned. |
| `history` | array | Earlier turns, oldest first. At most `200`. |
| `language` | string | Locks the reply language, such as `bn`. |
| `caller_id` | string | A phone number for the person, if you have one. |
| `context` | object | Where the person is, at most `2048` bytes. See [Tell the agent where the person is](#tell-the-agent-where-the-person-is). |
| `stream` | boolean | `true` sends the reply as it is written. See [Stream the reply](#stream-the-reply). |
| `app` | string | The app's handle. Needed only when the workspace has more than one app. |

Each `history` entry is `{ "role": "user" | "assistant", "text": "..." }`. The
field is `text` here, not `content` as it is in a completion.

```json
{
  "success": true,
  "data": {
    "session_id": "2f1c7c1e-0a5e-4a4f-9d55-7a2f3f0f8c11",
    "text": "Yes. Friday deliveries run from 10am to 6pm.",
    "quick_replies": ["Delivery charges", "Track my order"],
    "sources": 2,
    "model": "openai/gpt-4o",
    "usage": { "input_tokens": 1840, "output_tokens": 22, "cached_input_tokens": 0 }
  }
}
```

| Field | Notes |
|---|---|
| `session_id` | The id of this conversation. Keep it and send it on the next turn. |
| `text` | The reply. |
| `quick_replies` | Suggested next messages, when the agent offered any. |
| `image_url` | An image the agent attached, when there is one. |
| `sources` | How many knowledge sources the reply cited. A count, not a list. |
| `model` | The model that answered. |
| `tool_fired` | `true` when the agent called a connected tool. |
| `flow_fired` | `true` when a guided flow answered in place of the model. |
| `usage` | Tokens for the turn. |

`quick_replies`, `image_url`, `model`, `tool_fired` and `flow_fired` are left
out when they are empty or false.

A turn can fire a tool or a flow, so running it twice can do something twice.
If you may have to send a turn again, send it with an
[`Idempotency-Key`](/reference/core-api/errors-and-limits/#sending-a-request-again).
A repeat with the same key returns the first reply, runs nothing and does not
use a second AI turn.

### Tell the agent where the person is

`context` is one JSON object about the person's situation: the screen or page
they are on, the record they are looking at, the desk they are standing at. It
is the same object a widget page sends with `setContext`, and the agent reads it
the same way: flattened to `key: value` lines, at most 24 keys, each value cut
at 160 characters, and framed as a hint. It never gives the agent permission to
do anything, and the agent is told not to quote figures from it.

```json
{
  "message": "Is my meeting today?",
  "context": { "interaction": "voice", "place": "front desk", "kiosk": "lobby-1" }
}
```

`"interaction": "voice"` tells the agent the reply will be heard, not read, so it
answers in short spoken sentences with no lists or links. A context that is not
an object, or is larger than `2048` bytes, is refused with `400` before the
agent runs.

### Stream the reply

With `"stream": true` the reply arrives as Server-Sent Events while the agent
writes it, with the same frames a [streamed completion](/reference/core-api/completions/)
uses:

```
event: delta
data: {"text":"Yes. Friday deliveries "}

event: delta
data: {"text":"run from 10am to 6pm."}

event: done
data: {"session_id":"2f1c7c1e-0a5e-4a4f-9d55-7a2f3f0f8c11","text":"Yes. Friday deliveries run from 10am to 6pm.","quick_replies":["Book a delivery"],"sources":2,"model":"openai/gpt-4o","usage":{"input_tokens":1840,"output_tokens":22,"cached_input_tokens":0}}
```

- A `delta` is the next piece of the reply, for showing or speaking early. The
  agent's own markup for quick replies and images is held back, so a piece is
  safe to read aloud.
- `done` comes once, last, and is the whole turn: the object a turn without
  `stream` returns in `data`. Keep the text from `done`. It is the one the agent
  finished with, and it can differ from the pieces put together.
- `error` comes once, last, in place of `done`, with `code`, `message` and
  `request_id`, the same codes a refused call carries.
- When the agent's settings turn streaming off, or turn on masking of personal
  data in replies, no `delta` is sent and `done` carries the turn. A reply is
  masked only once it is whole, so it never leaves in pieces.
- An agent with connected tools sends its whole reply in one `delta` for now, whether or not it calls a tool on that turn: its tool loop does not stream a turn made through this route yet. The pieces arrive as they are written only for an agent without tools. A turn a guided flow answered also arrives as one piece.
- A refusal before the stream starts is the usual status code and error
  envelope. A failure after it starts is an `error` frame on a `200`.
- A streamed turn uses one AI turn once it has sent `done`. One that ends in an
  `error` frame uses none. An `Idempotency-Key` does not replay a streamed answer.

Streaming moves the first words earlier by the time the reply takes to write,
often a few hundred milliseconds on a short reply. The time before the first
word is the agent reading its knowledge and the model starting.

### What the agent turn does not do

These are real limits of the route as it stands. Design around them.

**It does not remember.** Omazy stores nothing about the conversation between
turns. The agent sees exactly the `history` you send and the new `message`.
Leave `history` out on the second turn and the agent has never met this person.
Keeping the transcript, and resending it, is your job.

```json
{
  "session_id": "2f1c7c1e-0a5e-4a4f-9d55-7a2f3f0f8c11",
  "message": "And how much is it?",
  "history": [
    { "role": "user", "text": "Do you deliver on Fridays?" },
    { "role": "assistant", "text": "Yes. Friday deliveries run from 10am to 6pm." }
  ]
}
```

**`session_id` is a label, not a memory.** Reusing it ties the turns of one
conversation together. It does not bring the earlier turns back. Leave it out
and each turn gets a fresh one.

**It cannot ask the person to confirm a change.** A connected tool set to ask
before it writes cannot finish through this route, because the confirmation
needs a conversation stored on Omazy. Run such tools from your own code, or use
the widget. A turn has `120` seconds, and one that uses tools can take a good
part of that, so do not put this call behind a short timeout.

**The conversation does not appear in your inbox.** Nothing is saved, so there
is nothing for a teammate to open or take over. If you need a human to be able
to step in, the conversation belongs in the [widget](/how-to/widget/) or
another channel.

**You get a count of sources, not the sources.** If you need the passages
themselves, call `/knowledge/search` with the same question.

For a prompt you control line by line, use
[`/ai/complete`](/reference/core-api/completions/) and bring your own context.
The guide [Call Omazy from your own backend](/guides/call-omazy-from-your-backend/)
does exactly that.
