# Sessions

Create a session so an agent remembers the conversation, attach to your own conversation ids, list and page through sessions and their history, delete one, and record a rating.

A session is the memory of an agent conversation. The agent routes answer only the latest user message in `messages`; everything said before is kept by the session, so passing the same `session_id` on each call is what makes a conversation. Sessions are created by the key's owner, listed for that owner and deleted only by that owner; their history is readable by any key in the tenant that knows the id.

**Who can use it:** creating, deleting and rating a session need **Chat**, and listing sessions or reading a history accepts **Chat** or **Read agents**. The chat turn that uses a session needs **Chat** as well.

## The routes

| Method and path | What it does |
| --- | --- |
| `POST /public/v1/sessions` | Create a session, or attach to an id of your own |
| `GET /public/v1/sessions` | List the caller's sessions |
| `GET /public/v1/sessions/<session-id>/history` | Read a session's messages, oldest first, in pages |
| `DELETE /public/v1/sessions/<session-id>` | Delete a session and its history |
| `POST /public/v1/feedback` | Record a rating and a comment against a session |

## Two ways to start a session

| | Create first | Bring your own id |
| --- | --- | --- |
| What you send | `POST /public/v1/sessions` with `agentId`, `title`, `context`, `state`, optionally `chatId` | Any stable string as `session_id` on the chat route |
| What happens | A session is created, 201, and its `id` returned | The session is created on the first turn under that id, which comes back as `session_id` |
| Reach for it when | You want a title, `state` or `context` on the session before the first turn | Your application already has an id per thread |

With `chatId` the route does get-or-create: the first call creates, later calls return the existing row unchanged, both with 201, and later `title`, `context` and `state` are ignored. Use a UUID for `chatId`: a value that is not one is stored under a different derived id from the one the chat, history and delete routes derive from the same string, so your turns land in a second row.

## Create a session and talk through it

The create body is in camel case, unlike the rest of the API: `agentId`, `title`, `context`, `state` and `chatId`.

**cURL**

```bash
curl -X POST "https://<your tenant host>/public/v1/sessions" \
  -H "Authorization: Bearer kapi_..." \
  -H "Content-Type: application/json" \
  -d '{"agentId": "support-assistant", "title": "Refund question from the web form"}'

curl -X POST "https://<your tenant host>/public/v1/chat" \
  -H "Authorization: Bearer kapi_..." \
  -H "Content-Type: application/json" \
  -d '{"agent_id": "support-assistant", "session_id": "<session-id>",
       "messages": [{"role": "user", "content": "What does our refund policy say about digital goods?"}]}'
```

**Python**

```python

BASE = "https://<your tenant host>/public/v1"
HEADERS = {"Authorization": "Bearer kapi_..."}

session = requests.post(f"{BASE}/sessions", headers=HEADERS,
                        json={"agentId": "support-assistant", "title": "Refund question from the web form"}).json()

def ask(text):
    r = requests.post(f"{BASE}/chat", headers=HEADERS, json={
        "agent_id": "support-assistant", "session_id": session["id"],
        "messages": [{"role": "user", "content": text}]})
    r.raise_for_status()
    return r.json()["message"]["content"]

print(ask("What does our refund policy say about digital goods?"))
print(ask("And for annual plans?"))
```

**TypeScript**

```typescript
const BASE = "https://<your tenant host>/public/v1";
const headers = { Authorization: "Bearer kapi_...", "Content-Type": "application/json" };

const session = await (await fetch(`${BASE}/sessions`, {
  method: "POST", headers,
  body: JSON.stringify({ agentId: "support-assistant", title: "Refund question from the web form" }),
})).json();

async function ask(text: string): Promise<string> {
  const r = await fetch(`${BASE}/chat`, {
    method: "POST", headers,
    body: JSON.stringify({ agent_id: "support-assistant", session_id: session.id,
                           messages: [{ role: "user", content: text }] }),
  });
  return (await r.json()).message.content;
}

console.log(await ask("What does our refund policy say about digital goods?"));
console.log(await ask("And for annual plans?"));
```

## The session object

| Field | Meaning |
| --- | --- |
| `id` | The value to pass as `session_id` |
| `agent_id`, `title` | What you set at creation. `agent_id` defaults to the tenant's default agent; an empty `title` is set from the first user message, then replaced by a generated one |
| `status` | Always `active` for sessions made through the API; `archived` and `expired` exist but are set only from the Work Room |
| `message_count`, `last_message_at`, `updated_at` | Grow with each turn; `message_count` counts messages that carry text |
| `state`, `context` | Free-form objects kept with the session |
| `expires_at` | Always null; sessions do not expire on the current build |
| `is_starred`, `created_at`, `tenant_id`, `user_id` | Housekeeping |

## List and page

`GET /public/v1/sessions` returns `sessions`, `total` and `has_more`, most recently active first. Filter with `status` and `agent_id`; page with `limit` (default 20) and `offset`. `next_cursor` is always null. Only the caller's own sessions are listed, and only those with a message, so a session created and not yet used does not appear.

## Read the history

`GET /public/v1/sessions/<session-id>/history` returns `session_id`, `messages` oldest first, `has_more` and `mode`. `limit` defaults to 50. To read the earlier page, pass the first message's `id` as `before`; `next_cursor` is always null. Each message carries `id`, `role` (`user`, `assistant`, `system` or `tool`), `content`, `tool_calls` and `tool_call_id` on tool turns, `agent_id` and `agent_name`, `metadata` (where citations and guardrail flags such as `guardrail_blocked` ride), `feedback` and `timestamp`. The route checks the tenant, not the owner: any key in the tenant that holds the id reads the messages, and an unknown id answers 200 with an empty list rather than 404.

## Delete

`DELETE /public/v1/sessions/<session-id>` removes the session and its messages for good and answers 204. A session that belongs to another user, or does not exist, answers 404, never 403.

## Record a rating

`POST /public/v1/feedback` takes `session_id`, an integer `rating` and an optional `comment`, and answers 201 with `status` set to `recorded`. The rating is stored as a label: 4 and above is `good`, 2 and below `bad`, 3 `neutral`; the integer is not range-checked, so keep to 1 to 5 yourself. The feedback attaches to the session, not to a message, so it never shows in a history message's `feedback`. The session must exist in the key's tenant; it need not be the owner's.

## Limits and behaviour

- Resending earlier turns in `messages` does not replay them; everything but the latest user message is discarded.
- The agent is shown up to the last forty messages of the session when it answers. Whether it sees them at all depends on its memory setting: an agent whose memory is set to none keeps the transcript but does not show it to the model, and an agent created through `POST /public/v1/agents` has that setting by default on the current build.
- There is no lock on a session. Two turns sent at once both run; nothing answers 409.
- Every turn is also recorded as a run on the agent's Traces tab in Studio.
- The registry-path chat route accepts `session_id` the same way and ignores `stream`.

## Troubleshooting

- **404 on delete for an id you hold**: the session was created by another user's key, or is already gone.
- **History is empty for an id that has turns**: the id belongs to another tenant or was mistyped; the route does not distinguish the two.
- **A session you created is not in the list**: it has no messages yet. It appears after its first turn.
- **Turns land in a different session from the one you created**: `chatId` was not a UUID. Use a UUID, or skip create and send your id as `session_id` on the chat route only.
- **The agent does not remember the previous question**: the second call sent no `session_id` or a different one, or the agent's memory is set to none.
- **422 on create**: a value has the wrong type; `agentId` and `title` are strings, `context` and `state` are objects.

## Related

- [Chat from your application](/developers/guides/chat-from-your-application)
- [Agent chat or model completion](/developers/guides/agent-chat-or-model-completion)
- Sessions
- Analytics and feedback

Source: https://docs.katonic.ai/developers/guides/sessions
