Metadata-Version: 2.5
Name: orbit-agent-chat
Version: 0.2.0
Summary: Python SDK for the Orbit Agent Chat API: hand an AI Agent conversation to human support staff.
Project-URL: Repository, https://github.com/zilliztech/orbit
Project-URL: Source, https://github.com/zilliztech/orbit/tree/main/sdks/python
Requires-Python: >=3.9
Requires-Dist: httpx<1,>=0.27
Description-Content-Type: text/markdown

# orbit-agent-chat

Python SDK for the Orbit Agent Chat API. Your AI Agent's backend uses it to hand a conversation to human support staff: create a chat, issue a short-lived token for the browser, read and post messages, and close the chat. It runs server-side because it holds an Orbit API token with the `agent_chat:write` scope. Never ship that token to a browser.

Requires Python 3.9+. The only dependency is `httpx`.

## Install

```bash
pip install orbit-agent-chat
# or: uv add orbit-agent-chat
```

Releases (wheel and sdist) are published to PyPI from the Orbit repository's CI (tag `sdk-python-vX.Y.Z`). A build machine that cannot reach pypi.org can install through a PyPI mirror (`pip install -i <mirror> orbit-agent-chat`).

## Get an API token

The SDK authenticates with an Orbit API token that an Orbit administrator creates for your integration. Someone with the `tokens:write` permission does this in the Orbit console:

1. Open **API tokens** (`/internal/api-tokens`) and choose **New token**.
2. Set the type to **API Client**. Do not pick **AI Agent**: that type is for Orbit's own AI features and cannot hold the `agent_chat:write` scope.
3. Grant only the **`agent_chat:write`** scope. It is all the SDK needs to create, read, post to and close chats, and to issue chat tokens.
4. Name it after the integration (for example `Acme Agent - production`), create it, and copy the secret right away. Orbit shows it once and cannot show it again.
5. Store it in your backend's secret store and pass it as `api_token`. It never goes to a browser.

Use one token per integration and per environment. **Orbit identifies an integration by its token**: chats, idempotency keys and the customers Orbit creates for your users all belong to the token's identity.

- **To change the secret, use Rotate** on that token in the console. Rotate keeps the same token and identity and only replaces the secret; update your secret store, and the old secret stops working.
- **Never replace it with a newly created token.** A new token is a new integration as far as Orbit is concerned. Every existing chat would stop working (chat tokens are refused, old chats return 404), idempotency keys would start over, and the same Agent users would show up as new customers.
- **Revoking the token switches the integration off.** Calls with it fail with 401, and every chat token issued from it stops working too, so the browser stream ends with a fatal error.

If browsers talk to Orbit directly (the Node SDK does), an administrator must also allow your site's origin for Agent chat at **CORS origins** (`/internal/cors-origins`).

## Use

```python
from orbit_agent_chat import HistoryItem, OrbitAgentChatClient, OrbitAgentChatError

with OrbitAgentChatClient("https://support.example.com", api_token) as client:
    result = client.create_chat(
        title="Cannot reset my password",
        description="The reset email never arrives.",
        session_id="sess-123",  # your Agent's session
        uuid="user-uuid-456",  # your Agent's end user
        history=[HistoryItem("user", "I can't log in"), HistoryItem("assistant", "Let me hand you to a human")],
    )
    chat = result.chat  # result.replayed is True when the idempotency key was seen before

    token = client.issue_token(chat.id)  # give token.token to the browser
    page = client.list_messages(chat.id, after=0, limit=100)
    client.send_message(chat.id, "One more detail: it happens on mobile")
    client.close_chat(chat.id, reason="The user said the issue is resolved")  # reason is optional
```

The close reason (at most 500 characters) is shown only to Orbit staff, on the ticket page and in the audit log; the customer never sees it.

`AsyncOrbitAgentChatClient` has the same methods as coroutines; use `async with` or `await client.aclose()`:

```python
async with AsyncOrbitAgentChatClient("https://support.example.com", api_token) as client:
    result = await client.create_chat(title="...", description="...", session_id="...", uuid="...")
```

### What goes into a chat

`create_chat` also takes three optional arguments:

- `requester_email`: the end user's email as your Agent knows it. Orbit staff see it on the ticket's Agent chat card; nothing is emailed to it, and the ticket's requester stays a synthetic customer of your integration either way.
- `note`: context for Orbit staff, at most 2 000 characters.
- `payload`: a JSON object for Orbit staff (for example your Agent's state), at most 65 536 bytes once serialised.

`note` and `payload` are seen by Orbit staff only, never by the end user. `history` (the conversation so far, shown to both) is at most 500 items and 200 000 characters of `content` in total.

### Your own httpx client

Pass `http_client=httpx.Client(...)` (or `httpx.AsyncClient`) to control proxies and transports. A client you pass in is not closed by the SDK. The `timeout` argument (default 10 s) applies only to the client the SDK creates; when you pass `http_client`, set the timeout on that client.

## Idempotency

`create_chat` always sends an idempotency key, in the `Idempotency-Key` header and the body. Pass your own `idempotency_key` (for example one derived from your session) to make a create safe across your own restarts; without one the SDK generates a random key and reuses it for every retry of that call. Re-sending a key with the same content returns the original chat with `replayed=True`; the same key with different content is a 409 `agent_chat_idempotency_mismatch`.

## Retries

Up to `max_retries` (default 3) retries, waiting 0.5 s, 1 s, 2 s ... (capped at 8 s, plus or minus 20% jitter). A 429 waits for its `Retry-After` header, or the error body's `details.retry_after` when the header is missing, at most 60 s.

| Call | Retried on |
| --- | --- |
| `create_chat`, `issue_token`, `close_chat`, `list_messages` | network failure, 429, 502, 503, 504 |
| `send_message` | 429 only |

Other 4xx responses and 500 are never retried. `send_message` is not retried after a network failure or a 5xx because the request may already have been processed, and the API has no idempotency key for messages, so a retry could post the customer's message twice. If it fails with `network_error`, call `list_messages` to see whether it landed before sending again.

## Errors

Every failure raises `OrbitAgentChatError` with `status`, `code`, `message`, `request_id`, `details` and `retry_after` (seconds, or `None`). A failure to get any response (after retries) has `status == 0` and `code == "network_error"`; a non-JSON error body gets the code `http_<status>`.

| `code` | Status | Meaning |
| --- | --- | --- |
| `agent_chat_closed` | 409 | The chat or its ticket is closed; no more messages |
| `agent_chat_not_found` | 404 | Unknown chat, or it belongs to another API client |
| `agent_chat_idempotency_mismatch` | 409 | The idempotency key was used with different content |
| `agent_chat_stream_limit` | 429 | Too many concurrent streams for the chat |

## Handing the chat to the browser

The browser must never see your API token. After `create_chat`, call `issue_token(chat.id)` on your backend and return `token.token` (valid 15 minutes, `token.expires_at`) with `chat.id` to the page. The browser sends it as `Authorization: AgentChat <token>` to read and post messages and to open the realtime stream (the `@zilliz/orbit-agent-chat` Node/browser package does this and renews the token). When it expires, issue another from your backend. Chat tokens cannot create chats, issue tokens or close chats.
