orbit-agent-chat 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,23 @@
1
+ node_modules/
2
+ .pnpm-store/
3
+ .env
4
+ .DS_Store
5
+ dist/
6
+ .vinxi/
7
+ .nitro/
8
+ .tanstack/
9
+ routeTree.gen.ts
10
+ *.log
11
+
12
+ # Subagent-driven-development scratch: per-plan ledgers, task briefs, review
13
+ # packages. Regenerated on demand; the record that matters is git history.
14
+ .superpowers/
15
+
16
+ .local/
17
+
18
+ # Python SDK
19
+ sdks/python/dist/
20
+ .venv/
21
+ __pycache__/
22
+ *.egg-info/
23
+ .pytest_cache/
@@ -0,0 +1,96 @@
1
+ Metadata-Version: 2.5
2
+ Name: orbit-agent-chat
3
+ Version: 0.1.0
4
+ Summary: Python SDK for the Orbit Agent Chat API: hand an AI Agent conversation to human support staff.
5
+ Project-URL: Repository, https://github.com/zilliztech/orbit
6
+ Project-URL: Source, https://github.com/zilliztech/orbit/tree/main/sdks/python
7
+ Requires-Python: >=3.9
8
+ Requires-Dist: httpx<1,>=0.27
9
+ Description-Content-Type: text/markdown
10
+
11
+ # orbit-agent-chat
12
+
13
+ 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.
14
+
15
+ Requires Python 3.9+. The only dependency is `httpx`.
16
+
17
+ ## Install
18
+
19
+ ```bash
20
+ pip install orbit-agent-chat
21
+ # or: uv add orbit-agent-chat
22
+ ```
23
+
24
+ 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`).
25
+
26
+ ## Use
27
+
28
+ ```python
29
+ from orbit_agent_chat import HistoryItem, OrbitAgentChatClient, OrbitAgentChatError
30
+
31
+ with OrbitAgentChatClient("https://support.example.com", api_token) as client:
32
+ result = client.create_chat(
33
+ title="Cannot reset my password",
34
+ description="The reset email never arrives.",
35
+ session_id="sess-123", # your Agent's session
36
+ uuid="user-uuid-456", # your Agent's end user
37
+ history=[HistoryItem("user", "I can't log in"), HistoryItem("assistant", "Let me hand you to a human")],
38
+ )
39
+ chat = result.chat # result.replayed is True when the idempotency key was seen before
40
+
41
+ token = client.issue_token(chat.id) # give token.token to the browser
42
+ page = client.list_messages(chat.id, after=0, limit=100)
43
+ client.send_message(chat.id, "One more detail: it happens on mobile")
44
+ client.close_chat(chat.id)
45
+ ```
46
+
47
+ `AsyncOrbitAgentChatClient` has the same methods as coroutines; use `async with` or `await client.aclose()`:
48
+
49
+ ```python
50
+ async with AsyncOrbitAgentChatClient("https://support.example.com", api_token) as client:
51
+ result = await client.create_chat(title="...", description="...", session_id="...", uuid="...")
52
+ ```
53
+
54
+ ### What goes into a chat
55
+
56
+ `create_chat` also takes three optional arguments:
57
+
58
+ - `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.
59
+ - `note`: context for Orbit staff, at most 2 000 characters.
60
+ - `payload`: a JSON object for Orbit staff (for example your Agent's state), at most 65 536 bytes once serialised.
61
+
62
+ `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.
63
+
64
+ ### Your own httpx client
65
+
66
+ 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.
67
+
68
+ ## Idempotency
69
+
70
+ `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`.
71
+
72
+ ## Retries
73
+
74
+ 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.
75
+
76
+ | Call | Retried on |
77
+ | --- | --- |
78
+ | `create_chat`, `issue_token`, `close_chat`, `list_messages` | network failure, 429, 502, 503, 504 |
79
+ | `send_message` | 429 only |
80
+
81
+ 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.
82
+
83
+ ## Errors
84
+
85
+ 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>`.
86
+
87
+ | `code` | Status | Meaning |
88
+ | --- | --- | --- |
89
+ | `agent_chat_closed` | 409 | The chat or its ticket is closed; no more messages |
90
+ | `agent_chat_not_found` | 404 | Unknown chat, or it belongs to another API client |
91
+ | `agent_chat_idempotency_mismatch` | 409 | The idempotency key was used with different content |
92
+ | `agent_chat_stream_limit` | 429 | Too many concurrent streams for the chat |
93
+
94
+ ## Handing the chat to the browser
95
+
96
+ 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.
@@ -0,0 +1,86 @@
1
+ # orbit-agent-chat
2
+
3
+ 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.
4
+
5
+ Requires Python 3.9+. The only dependency is `httpx`.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pip install orbit-agent-chat
11
+ # or: uv add orbit-agent-chat
12
+ ```
13
+
14
+ 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`).
15
+
16
+ ## Use
17
+
18
+ ```python
19
+ from orbit_agent_chat import HistoryItem, OrbitAgentChatClient, OrbitAgentChatError
20
+
21
+ with OrbitAgentChatClient("https://support.example.com", api_token) as client:
22
+ result = client.create_chat(
23
+ title="Cannot reset my password",
24
+ description="The reset email never arrives.",
25
+ session_id="sess-123", # your Agent's session
26
+ uuid="user-uuid-456", # your Agent's end user
27
+ history=[HistoryItem("user", "I can't log in"), HistoryItem("assistant", "Let me hand you to a human")],
28
+ )
29
+ chat = result.chat # result.replayed is True when the idempotency key was seen before
30
+
31
+ token = client.issue_token(chat.id) # give token.token to the browser
32
+ page = client.list_messages(chat.id, after=0, limit=100)
33
+ client.send_message(chat.id, "One more detail: it happens on mobile")
34
+ client.close_chat(chat.id)
35
+ ```
36
+
37
+ `AsyncOrbitAgentChatClient` has the same methods as coroutines; use `async with` or `await client.aclose()`:
38
+
39
+ ```python
40
+ async with AsyncOrbitAgentChatClient("https://support.example.com", api_token) as client:
41
+ result = await client.create_chat(title="...", description="...", session_id="...", uuid="...")
42
+ ```
43
+
44
+ ### What goes into a chat
45
+
46
+ `create_chat` also takes three optional arguments:
47
+
48
+ - `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.
49
+ - `note`: context for Orbit staff, at most 2 000 characters.
50
+ - `payload`: a JSON object for Orbit staff (for example your Agent's state), at most 65 536 bytes once serialised.
51
+
52
+ `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.
53
+
54
+ ### Your own httpx client
55
+
56
+ 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.
57
+
58
+ ## Idempotency
59
+
60
+ `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`.
61
+
62
+ ## Retries
63
+
64
+ 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.
65
+
66
+ | Call | Retried on |
67
+ | --- | --- |
68
+ | `create_chat`, `issue_token`, `close_chat`, `list_messages` | network failure, 429, 502, 503, 504 |
69
+ | `send_message` | 429 only |
70
+
71
+ 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.
72
+
73
+ ## Errors
74
+
75
+ 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>`.
76
+
77
+ | `code` | Status | Meaning |
78
+ | --- | --- | --- |
79
+ | `agent_chat_closed` | 409 | The chat or its ticket is closed; no more messages |
80
+ | `agent_chat_not_found` | 404 | Unknown chat, or it belongs to another API client |
81
+ | `agent_chat_idempotency_mismatch` | 409 | The idempotency key was used with different content |
82
+ | `agent_chat_stream_limit` | 429 | Too many concurrent streams for the chat |
83
+
84
+ ## Handing the chat to the browser
85
+
86
+ 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.
@@ -0,0 +1,17 @@
1
+ from ._errors import OrbitAgentChatError
2
+ from ._models import Chat, ChatToken, CreateChatResult, HistoryItem, Message, MessagesPage
3
+ from .async_client import AsyncOrbitAgentChatClient
4
+ from .client import OrbitAgentChatClient
5
+
6
+ __all__ = [
7
+ "AsyncOrbitAgentChatClient",
8
+ "Chat",
9
+ "ChatToken",
10
+ "CreateChatResult",
11
+ "HistoryItem",
12
+ "Message",
13
+ "MessagesPage",
14
+ "OrbitAgentChatClient",
15
+ "OrbitAgentChatError",
16
+ ]
17
+ __version__ = "0.1.0"
@@ -0,0 +1,32 @@
1
+ from typing import Any, Optional
2
+
3
+
4
+ class OrbitAgentChatError(Exception):
5
+ """An error from the Agent Chat API, or a network failure (status 0, code ``network_error``)."""
6
+
7
+ def __init__(
8
+ self,
9
+ *,
10
+ status: int,
11
+ code: str,
12
+ message: str,
13
+ request_id: Optional[str] = None,
14
+ details: Any = None,
15
+ retry_after: Optional[float] = None,
16
+ ) -> None:
17
+ super().__init__(message)
18
+ self.status = status
19
+ self.code = code
20
+ self.message = message
21
+ self.request_id = request_id
22
+ self.details = details
23
+ #: Seconds, from the ``retry-after`` header; None when absent or unparseable.
24
+ self.retry_after = retry_after
25
+
26
+ def __repr__(self) -> str:
27
+ return "OrbitAgentChatError(status=%r, code=%r, message=%r, request_id=%r)" % (
28
+ self.status,
29
+ self.code,
30
+ self.message,
31
+ self.request_id,
32
+ )
@@ -0,0 +1,124 @@
1
+ """Public data types. The camelCase <-> snake_case mapping lives only in this module."""
2
+ from dataclasses import dataclass
3
+ from typing import Any, Dict, List, Literal, Mapping, Optional, Sequence
4
+
5
+
6
+ @dataclass(frozen=True)
7
+ class Chat:
8
+ id: str
9
+ ticket_id: str
10
+ ticket_number: str
11
+ session_id: str
12
+ uuid: str
13
+ status: Literal["open", "closed"]
14
+ created_at: str
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Message:
19
+ seq: int
20
+ id: str
21
+ role: Literal["history", "user", "staff"]
22
+ body: str
23
+ created_at: str
24
+ author_name: Optional[str] = None
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class CreateChatResult:
29
+ chat: Chat
30
+ replayed: bool
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class ChatToken:
35
+ token: str
36
+ expires_at: str
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class MessagesPage:
41
+ chat: Chat
42
+ messages: List[Message]
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class HistoryItem:
47
+ role: Literal["user", "assistant"]
48
+ content: str
49
+ created_at: Optional[str] = None
50
+
51
+
52
+ def chat_from_json(data: Mapping[str, Any]) -> Chat:
53
+ return Chat(
54
+ id=data["id"],
55
+ ticket_id=data["ticketId"],
56
+ ticket_number=data["ticketNumber"],
57
+ session_id=data["sessionId"],
58
+ uuid=data["uuid"],
59
+ status=data["status"],
60
+ created_at=data["createdAt"],
61
+ )
62
+
63
+
64
+ def message_from_json(data: Mapping[str, Any]) -> Message:
65
+ return Message(
66
+ seq=data["seq"],
67
+ id=data["id"],
68
+ role=data["role"],
69
+ body=data["body"],
70
+ created_at=data["createdAt"],
71
+ author_name=data.get("authorName"),
72
+ )
73
+
74
+
75
+ def history_item_to_json(item: HistoryItem) -> Dict[str, Any]:
76
+ out = {"role": item.role, "content": item.content} # type: Dict[str, Any]
77
+ if item.created_at is not None:
78
+ out["createdAt"] = item.created_at
79
+ return out
80
+
81
+
82
+ def create_chat_body(
83
+ *,
84
+ title: str,
85
+ description: str,
86
+ session_id: str,
87
+ uuid: str,
88
+ idempotency_key: str,
89
+ requester_email: Optional[str],
90
+ history: Optional[Sequence[HistoryItem]],
91
+ note: Optional[str],
92
+ payload: Optional[Mapping[str, Any]],
93
+ ) -> Dict[str, Any]:
94
+ body = {
95
+ "title": title,
96
+ "description": description,
97
+ "sessionId": session_id,
98
+ "uuid": uuid,
99
+ "idempotencyKey": idempotency_key,
100
+ } # type: Dict[str, Any]
101
+ if requester_email is not None:
102
+ body["requesterEmail"] = requester_email
103
+ if history is not None:
104
+ body["history"] = [history_item_to_json(h) for h in history]
105
+ if note is not None:
106
+ body["note"] = note
107
+ if payload is not None:
108
+ body["payload"] = dict(payload)
109
+ return body
110
+
111
+
112
+ def create_result_from_json(data: Mapping[str, Any]) -> CreateChatResult:
113
+ return CreateChatResult(chat=chat_from_json(data["chat"]), replayed=bool(data.get("replayed", False)))
114
+
115
+
116
+ def token_from_json(data: Mapping[str, Any]) -> ChatToken:
117
+ return ChatToken(token=data["token"], expires_at=data["expiresAt"])
118
+
119
+
120
+ def page_from_json(data: Mapping[str, Any]) -> MessagesPage:
121
+ return MessagesPage(
122
+ chat=chat_from_json(data["chat"]),
123
+ messages=[message_from_json(m) for m in data["messages"]],
124
+ )
@@ -0,0 +1,129 @@
1
+ """Pure helpers shared by the sync and async clients (no I/O, no sleeping)."""
2
+ import json
3
+ import random
4
+ from typing import Any, Dict, Mapping, Optional
5
+ from urllib.parse import quote
6
+
7
+ import httpx
8
+
9
+ from ._errors import OrbitAgentChatError
10
+
11
+ BASE_BACKOFF_SECONDS = 0.5
12
+ MAX_BACKOFF_SECONDS = 8.0
13
+ # The longest a 429's retry-after is honoured; a larger value waits this long.
14
+ MAX_RETRY_AFTER_SECONDS = 60.0
15
+
16
+ SEND_MESSAGE = "send_message"
17
+ OTHER = "other"
18
+
19
+
20
+ def build_request(
21
+ *,
22
+ base_url: str,
23
+ api_token: str,
24
+ method: str,
25
+ path: str,
26
+ json_body: Optional[Mapping[str, Any]] = None,
27
+ params: Optional[Mapping[str, Any]] = None,
28
+ extra_headers: Optional[Mapping[str, str]] = None,
29
+ ) -> Dict[str, Any]:
30
+ """Keyword arguments for ``httpx.Client.request`` / ``AsyncClient.request``."""
31
+ headers = {"Authorization": "Bearer " + api_token, "Accept": "application/json"}
32
+ if extra_headers:
33
+ headers.update(extra_headers)
34
+ request = {
35
+ "method": method,
36
+ "url": base_url.rstrip("/") + path,
37
+ "headers": headers,
38
+ } # type: Dict[str, Any]
39
+ if json_body is not None:
40
+ request["json"] = json_body
41
+ if params:
42
+ request["params"] = dict(params)
43
+ return request
44
+
45
+
46
+ def chat_path(chat_id: str, suffix: str = "") -> str:
47
+ return "/api/agent-chats/" + quote(chat_id, safe="") + suffix
48
+
49
+
50
+ def is_retryable(method_kind: str, status: Optional[int]) -> bool:
51
+ """``status`` None means no response arrived (network failure).
52
+
53
+ ``send_message`` retries only 429: the server cannot tell a retried post from a new one,
54
+ so anything that may have been processed would duplicate the message.
55
+ """
56
+ if method_kind == SEND_MESSAGE:
57
+ return status == 429
58
+ return status is None or status in (429, 502, 503, 504)
59
+
60
+
61
+ def backoff_seconds(attempt: int, retry_after: Optional[float] = None) -> float:
62
+ """Seconds to wait before retry number ``attempt`` (0-based)."""
63
+ if retry_after is not None:
64
+ return min(retry_after, MAX_RETRY_AFTER_SECONDS)
65
+ delay = min(BASE_BACKOFF_SECONDS * (2**attempt), MAX_BACKOFF_SECONDS)
66
+ return delay * (0.8 + 0.4 * random.random())
67
+
68
+
69
+ def _parse_retry_after(value: Optional[str]) -> Optional[float]:
70
+ if value is None:
71
+ return None
72
+ try:
73
+ seconds = float(value.strip())
74
+ except ValueError:
75
+ return None
76
+ # float() accepts "nan" / "inf"; neither is a usable wait.
77
+ if seconds != seconds or seconds < 0 or seconds == float("inf"):
78
+ return None
79
+ return seconds
80
+
81
+
82
+ def _retry_after_from_details(details: Any) -> Optional[float]:
83
+ """The error body's ``details.retry_after`` (seconds), used when the header is absent or invalid."""
84
+ if not isinstance(details, dict):
85
+ return None
86
+ seconds = details.get("retry_after")
87
+ if isinstance(seconds, bool) or not isinstance(seconds, (int, float)):
88
+ return None
89
+ seconds = float(seconds)
90
+ if seconds != seconds or seconds < 0 or seconds == float("inf"):
91
+ return None
92
+ return seconds
93
+
94
+
95
+ def parse_error(response: httpx.Response) -> OrbitAgentChatError:
96
+ """Builds an error from a non-2xx response; tolerates a body that is not Orbit's error JSON."""
97
+ code = "http_%d" % response.status_code
98
+ message = response.reason_phrase or "HTTP %d" % response.status_code
99
+ request_id = response.headers.get("x-request-id")
100
+ details = None # type: Any
101
+ try:
102
+ parsed = json.loads(response.text)
103
+ error = parsed.get("error") if isinstance(parsed, dict) else None
104
+ if isinstance(error, dict):
105
+ if isinstance(error.get("code"), str):
106
+ code = error["code"]
107
+ if isinstance(error.get("message"), str):
108
+ message = error["message"]
109
+ if isinstance(error.get("request_id"), str):
110
+ request_id = error["request_id"]
111
+ if error.get("details") is not None:
112
+ details = error["details"]
113
+ except ValueError:
114
+ pass # Not JSON (for example a proxy's HTML 502): keep the http_<status> fallback.
115
+ retry_after = _parse_retry_after(response.headers.get("retry-after"))
116
+ if retry_after is None:
117
+ retry_after = _retry_after_from_details(details)
118
+ return OrbitAgentChatError(
119
+ status=response.status_code,
120
+ code=code,
121
+ message=message,
122
+ request_id=request_id,
123
+ details=details,
124
+ retry_after=retry_after,
125
+ )
126
+
127
+
128
+ def network_error(cause: Exception) -> OrbitAgentChatError:
129
+ return OrbitAgentChatError(status=0, code="network_error", message=str(cause) or cause.__class__.__name__)
@@ -0,0 +1,138 @@
1
+ import asyncio
2
+ import uuid as _uuid
3
+ from typing import Any, Dict, Mapping, Optional, Sequence
4
+
5
+ import httpx
6
+
7
+ from . import _models as m
8
+ from ._transport import (
9
+ OTHER,
10
+ SEND_MESSAGE,
11
+ backoff_seconds,
12
+ build_request,
13
+ chat_path,
14
+ is_retryable,
15
+ network_error,
16
+ parse_error,
17
+ )
18
+
19
+
20
+ class AsyncOrbitAgentChatClient:
21
+ """Asynchronous client for the Orbit Agent Chat API; same behaviour as the sync client."""
22
+
23
+ def __init__(
24
+ self,
25
+ base_url: str,
26
+ api_token: str,
27
+ *,
28
+ timeout: float = 10.0,
29
+ max_retries: int = 3,
30
+ http_client: Optional[httpx.AsyncClient] = None,
31
+ ) -> None:
32
+ self._base_url = base_url
33
+ self._api_token = api_token
34
+ self._max_retries = max_retries
35
+ self._owns_client = http_client is None
36
+ self._http = http_client if http_client is not None else httpx.AsyncClient(timeout=timeout)
37
+
38
+ async def __aenter__(self) -> "AsyncOrbitAgentChatClient":
39
+ return self
40
+
41
+ async def __aexit__(self, *exc_info: Any) -> None:
42
+ await self.aclose()
43
+
44
+ async def aclose(self) -> None:
45
+ """Closes the underlying HTTP client unless it was passed in."""
46
+ if self._owns_client:
47
+ await self._http.aclose()
48
+
49
+ async def _request(
50
+ self,
51
+ kind: str,
52
+ method: str,
53
+ path: str,
54
+ *,
55
+ json_body: Optional[Mapping[str, Any]] = None,
56
+ params: Optional[Mapping[str, Any]] = None,
57
+ extra_headers: Optional[Mapping[str, str]] = None,
58
+ ) -> Dict[str, Any]:
59
+ request = build_request(
60
+ base_url=self._base_url,
61
+ api_token=self._api_token,
62
+ method=method,
63
+ path=path,
64
+ json_body=json_body,
65
+ params=params,
66
+ extra_headers=extra_headers,
67
+ )
68
+ retries = 0
69
+ while True:
70
+ try:
71
+ response = await self._http.request(**request)
72
+ except httpx.TransportError as cause:
73
+ if is_retryable(kind, None) and retries < self._max_retries:
74
+ await asyncio.sleep(backoff_seconds(retries))
75
+ retries += 1
76
+ continue
77
+ raise network_error(cause) from cause
78
+ if response.is_success:
79
+ return response.json()
80
+ error = parse_error(response)
81
+ if is_retryable(kind, response.status_code) and retries < self._max_retries:
82
+ wait = backoff_seconds(retries, error.retry_after if response.status_code == 429 else None)
83
+ await asyncio.sleep(wait)
84
+ retries += 1
85
+ continue
86
+ raise error
87
+
88
+ async def create_chat(
89
+ self,
90
+ *,
91
+ title: str,
92
+ description: str,
93
+ session_id: str,
94
+ uuid: str,
95
+ idempotency_key: Optional[str] = None,
96
+ requester_email: Optional[str] = None,
97
+ history: Optional[Sequence[m.HistoryItem]] = None,
98
+ note: Optional[str] = None,
99
+ payload: Optional[Mapping[str, Any]] = None,
100
+ ) -> m.CreateChatResult:
101
+ # One key for the whole call, so a retry after a lost response replays instead of duplicating.
102
+ key = idempotency_key or _uuid.uuid4().hex
103
+ body = m.create_chat_body(
104
+ title=title,
105
+ description=description,
106
+ session_id=session_id,
107
+ uuid=uuid,
108
+ idempotency_key=key,
109
+ requester_email=requester_email,
110
+ history=history,
111
+ note=note,
112
+ payload=payload,
113
+ )
114
+ data = await self._request(
115
+ OTHER, "POST", "/api/agent-chats", json_body=body, extra_headers={"Idempotency-Key": key}
116
+ )
117
+ return m.create_result_from_json(data)
118
+
119
+ async def issue_token(self, chat_id: str) -> m.ChatToken:
120
+ """Issues a 15-minute chat token for the browser."""
121
+ return m.token_from_json(await self._request(OTHER, "POST", chat_path(chat_id, "/tokens")))
122
+
123
+ async def close_chat(self, chat_id: str) -> m.Chat:
124
+ data = await self._request(OTHER, "POST", chat_path(chat_id, "/close"))
125
+ return m.chat_from_json(data["chat"])
126
+
127
+ async def list_messages(self, chat_id: str, *, after: int = 0, limit: int = 100) -> m.MessagesPage:
128
+ data = await self._request(
129
+ OTHER, "GET", chat_path(chat_id, "/messages"), params={"after": after, "limit": limit}
130
+ )
131
+ return m.page_from_json(data)
132
+
133
+ async def send_message(self, chat_id: str, body: str) -> m.Message:
134
+ """Posts a customer message. Never retried except on 429, so a message is not duplicated."""
135
+ data = await self._request(
136
+ SEND_MESSAGE, "POST", chat_path(chat_id, "/messages"), json_body={"body": body}
137
+ )
138
+ return m.message_from_json(data["message"])
@@ -0,0 +1,135 @@
1
+ import time
2
+ import uuid as _uuid
3
+ from typing import Any, Dict, Mapping, Optional, Sequence
4
+
5
+ import httpx
6
+
7
+ from . import _models as m
8
+ from ._transport import (
9
+ OTHER,
10
+ SEND_MESSAGE,
11
+ backoff_seconds,
12
+ build_request,
13
+ chat_path,
14
+ is_retryable,
15
+ network_error,
16
+ parse_error,
17
+ )
18
+
19
+
20
+ class OrbitAgentChatClient:
21
+ """Synchronous client for the Orbit Agent Chat API (server-side: it holds an API token)."""
22
+
23
+ def __init__(
24
+ self,
25
+ base_url: str,
26
+ api_token: str,
27
+ *,
28
+ timeout: float = 10.0,
29
+ max_retries: int = 3,
30
+ http_client: Optional[httpx.Client] = None,
31
+ ) -> None:
32
+ self._base_url = base_url
33
+ self._api_token = api_token
34
+ self._max_retries = max_retries
35
+ self._owns_client = http_client is None
36
+ self._http = http_client if http_client is not None else httpx.Client(timeout=timeout)
37
+
38
+ def __enter__(self) -> "OrbitAgentChatClient":
39
+ return self
40
+
41
+ def __exit__(self, *exc_info: Any) -> None:
42
+ self.close()
43
+
44
+ def close(self) -> None:
45
+ """Closes the underlying HTTP client unless it was passed in."""
46
+ if self._owns_client:
47
+ self._http.close()
48
+
49
+ def _request(
50
+ self,
51
+ kind: str,
52
+ method: str,
53
+ path: str,
54
+ *,
55
+ json_body: Optional[Mapping[str, Any]] = None,
56
+ params: Optional[Mapping[str, Any]] = None,
57
+ extra_headers: Optional[Mapping[str, str]] = None,
58
+ ) -> Dict[str, Any]:
59
+ request = build_request(
60
+ base_url=self._base_url,
61
+ api_token=self._api_token,
62
+ method=method,
63
+ path=path,
64
+ json_body=json_body,
65
+ params=params,
66
+ extra_headers=extra_headers,
67
+ )
68
+ retries = 0
69
+ while True:
70
+ try:
71
+ response = self._http.request(**request)
72
+ except httpx.TransportError as cause:
73
+ if is_retryable(kind, None) and retries < self._max_retries:
74
+ time.sleep(backoff_seconds(retries))
75
+ retries += 1
76
+ continue
77
+ raise network_error(cause) from cause
78
+ if response.is_success:
79
+ return response.json()
80
+ error = parse_error(response)
81
+ if is_retryable(kind, response.status_code) and retries < self._max_retries:
82
+ wait = backoff_seconds(retries, error.retry_after if response.status_code == 429 else None)
83
+ time.sleep(wait)
84
+ retries += 1
85
+ continue
86
+ raise error
87
+
88
+ def create_chat(
89
+ self,
90
+ *,
91
+ title: str,
92
+ description: str,
93
+ session_id: str,
94
+ uuid: str,
95
+ idempotency_key: Optional[str] = None,
96
+ requester_email: Optional[str] = None,
97
+ history: Optional[Sequence[m.HistoryItem]] = None,
98
+ note: Optional[str] = None,
99
+ payload: Optional[Mapping[str, Any]] = None,
100
+ ) -> m.CreateChatResult:
101
+ # One key for the whole call, so a retry after a lost response replays instead of duplicating.
102
+ key = idempotency_key or _uuid.uuid4().hex
103
+ body = m.create_chat_body(
104
+ title=title,
105
+ description=description,
106
+ session_id=session_id,
107
+ uuid=uuid,
108
+ idempotency_key=key,
109
+ requester_email=requester_email,
110
+ history=history,
111
+ note=note,
112
+ payload=payload,
113
+ )
114
+ data = self._request(
115
+ OTHER, "POST", "/api/agent-chats", json_body=body, extra_headers={"Idempotency-Key": key}
116
+ )
117
+ return m.create_result_from_json(data)
118
+
119
+ def issue_token(self, chat_id: str) -> m.ChatToken:
120
+ """Issues a 15-minute chat token for the browser."""
121
+ return m.token_from_json(self._request(OTHER, "POST", chat_path(chat_id, "/tokens")))
122
+
123
+ def close_chat(self, chat_id: str) -> m.Chat:
124
+ return m.chat_from_json(self._request(OTHER, "POST", chat_path(chat_id, "/close"))["chat"])
125
+
126
+ def list_messages(self, chat_id: str, *, after: int = 0, limit: int = 100) -> m.MessagesPage:
127
+ data = self._request(
128
+ OTHER, "GET", chat_path(chat_id, "/messages"), params={"after": after, "limit": limit}
129
+ )
130
+ return m.page_from_json(data)
131
+
132
+ def send_message(self, chat_id: str, body: str) -> m.Message:
133
+ """Posts a customer message. Never retried except on 429, so a message is not duplicated."""
134
+ data = self._request(SEND_MESSAGE, "POST", chat_path(chat_id, "/messages"), json_body={"body": body})
135
+ return m.message_from_json(data["message"])
File without changes
@@ -0,0 +1,27 @@
1
+ [project]
2
+ name = "orbit-agent-chat"
3
+ version = "0.1.0"
4
+ description = "Python SDK for the Orbit Agent Chat API: hand an AI Agent conversation to human support staff."
5
+ readme = "README.md"
6
+ requires-python = ">=3.9"
7
+ dependencies = ["httpx>=0.27,<1"]
8
+
9
+ [project.urls]
10
+ Repository = "https://github.com/zilliztech/orbit"
11
+ Source = "https://github.com/zilliztech/orbit/tree/main/sdks/python"
12
+
13
+ [dependency-groups]
14
+ dev = ["pytest>=8"]
15
+
16
+ [build-system]
17
+ requires = ["hatchling"]
18
+ build-backend = "hatchling.build"
19
+
20
+ [tool.hatch.build.targets.wheel]
21
+ packages = ["orbit_agent_chat"]
22
+
23
+ [tool.hatch.build.targets.sdist]
24
+ include = ["orbit_agent_chat", "README.md", "pyproject.toml"]
25
+
26
+ [tool.pytest.ini_options]
27
+ testpaths = ["tests"]