olbrain-python-sdk 0.3.0__py3-none-any.whl → 0.3.2__py3-none-any.whl

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.
olbrain/AGENTS.md ADDED
@@ -0,0 +1,167 @@
1
+ # olbrain-python-sdk — reference for coding assistants
2
+
3
+ This file ships inside the installed package (`site-packages/olbrain/AGENTS.md`).
4
+ It is the complete, offline reference for the public API. Everything here is
5
+ taken from the source. If it disagrees with the web docs, this file is right.
6
+
7
+ Find it from Python with:
8
+ `python -c "import olbrain, os; print(os.path.join(os.path.dirname(olbrain.__file__), 'AGENTS.md'))"`
9
+
10
+ The Python SDK covers **conversational agents** only (`AgentClient`). Workflow
11
+ runs, approvals and research agents are available only in the JavaScript SDK
12
+ (`@olbrain/js-sdk`, class `Olbrain`).
13
+
14
+ ## Install and import
15
+
16
+ ```bash
17
+ pip install olbrain-python-sdk # import name: olbrain. Requires Python 3.7+ and requests.
18
+ ```
19
+
20
+ ```python
21
+ from olbrain import AgentClient, ChatResponse, OlbrainError
22
+ ```
23
+
24
+ ## Quick start
25
+
26
+ ```python
27
+ import os
28
+ from olbrain import AgentClient
29
+
30
+ with AgentClient(agent_id="your-agent-id", api_key=os.environ["OLBRAIN_API_KEY"]) as client:
31
+ session_id = client.create_session(title="Support chat", user_id="u_42")
32
+ reply = client.send_and_wait(session_id, "Hello!")
33
+ if reply.success:
34
+ print(reply.text)
35
+ else:
36
+ print("agent error:", reply.error)
37
+ ```
38
+
39
+ The client is synchronous and uses `requests`.
40
+
41
+ ## `AgentClient(agent_id, api_key, agent_url=None)`
42
+
43
+ - `agent_id`: required. An empty value raises `ValueError`.
44
+ - `api_key`: must start with `sk_live_`, `org_live_`, `sk_` or `org_`, or the
45
+ constructor raises `ValueError`. `ak_` keys are **not** accepted here.
46
+ - `agent_url`: optional. Defaults to `https://olbrain-agent-cloud-768934887465.us-central1.run.app`.
47
+
48
+ Every call is a `POST {agent_url}/api/agent/webhook` with headers
49
+ `Authorization: Bearer <api_key>` and `X-Agent-ID: <agent_id>`. The client is a
50
+ context manager, and `__exit__` calls `close()`.
51
+
52
+ ### Methods
53
+
54
+ | Method | Returns | Notes |
55
+ |---|---|---|
56
+ | `create_session(on_message=None, title=None, user_id=None, metadata=None, mode="production", description=None)` | `str` session id | Sends `title` (default `"New Session"`) to the agent **as the first message**. `mode` must be `"development"`, `"testing"` or `"production"`, otherwise `ValueError`. `description` is stored as `metadata["session_description"]`. If you pass `on_message`, it also calls `listen()`. Timeout 30 s. |
57
+ | `send_and_wait(session_id, message, user_id=None, metadata=None, model=None, timeout=120)` | `ChatResponse` | Waits for the reply. `timeout` is in **seconds**. `model` overrides the agent's model. Empty or whitespace-only messages raise `ValueError`. |
58
+ | `send(session_id, message, user_id=None, metadata=None, model=None, mode="production")` | `dict` (raw JSON) | Same request, but returns the raw response dict (`response`, `token_usage`, `success`, …). It still blocks, with a 120 s timeout. |
59
+ | `listen(session_id, on_message)` | `None` | Starts a background daemon thread that reads SSE from `GET {agent_url}/sessions/{id}/stream`. It reconnects with backoff from 5 s up to 60 s. Calling it again for the same session does nothing. |
60
+ | `run()` | `None` | Blocks until Ctrl+C, then calls `close()`. Use it to keep a script alive for `listen` callbacks. |
61
+ | `close()` | `None` | Stops all streams. |
62
+ | `get_session(session_id)` | `SessionInfo` | Needs backend support (webhook `action: get_session_info`). |
63
+ | `update_session(session_id, title=None, metadata=None, status=None)` | `SessionInfo` | `status` must be `"active"` or `"archived"`. |
64
+ | `delete_session(session_id)` | `dict` | Also stops that session's stream. |
65
+ | `get_session_stats(session_id)` | `dict` | |
66
+ | `get_messages(session_id, limit=20, offset=0)` | `dict` | The messages list and pagination info, as the backend returns them. |
67
+
68
+ The five session-management methods (`get_session` through `get_messages`)
69
+ depend on webhook `action`s that not every backend implements. They raise if
70
+ the backend refuses. Only `create_session`, `send_and_wait` and `send` are
71
+ guaranteed to work.
72
+
73
+ ### Streaming callback
74
+
75
+ `on_message` gets the **raw dict** from each SSE frame that has a `content`
76
+ key. Frames whose `type` is `ping` or `connected` are skipped. The callback
77
+ runs on the stream thread, so keep it fast and don't raise from it.
78
+
79
+ ```python
80
+ def on_message(msg: dict):
81
+ print(f"{msg.get('role')}: {msg['content']}")
82
+
83
+ client = AgentClient(agent_id="…", api_key="sk_live_…")
84
+ sid = client.create_session(on_message=on_message, title="Streaming chat")
85
+ client.send(sid, "Tell me a story")
86
+ client.run() # blocks; Ctrl+C to stop
87
+ ```
88
+
89
+ ## Data classes (`olbrain.session`, re-exported from `olbrain`)
90
+
91
+ ```python
92
+ @dataclass
93
+ class ChatResponse:
94
+ text: str
95
+ session_id: str
96
+ success: bool = True
97
+ token_usage: Optional[TokenUsage] = None # None if the server sent none
98
+ model_used: Optional[str] = None
99
+ response_time_ms: Optional[int] = None
100
+ metadata: Optional[dict] = None
101
+ error: Optional[str] = None
102
+ # ChatResponse.from_dict(data, session_id=""), .to_dict()
103
+
104
+ @dataclass
105
+ class TokenUsage:
106
+ prompt_tokens: int = 0
107
+ completion_tokens: int = 0
108
+ total_tokens: int = 0
109
+ cost: float = 0.0
110
+
111
+ @dataclass
112
+ class SessionInfo:
113
+ session_id: str
114
+ title: str = ""
115
+ status: str = "active" # "active" | "archived"
116
+ created_at: str = ""
117
+ updated_at: str = ""
118
+ message_count: int = 0
119
+ user_id: Optional[str] = None
120
+ channel: str = "api"
121
+ metadata: dict = {}
122
+ ```
123
+
124
+ `token_usage` can be `None`, so guard before reading it:
125
+ `reply.token_usage.total_tokens if reply.token_usage else 0`. Always check
126
+ `reply.success` too. A 200 response can carry `success=False` and an `error`.
127
+
128
+ Avoid the exported `Message` and `Session` classes. Nothing in the client
129
+ returns them, and `Session.get_stats()` always falls back to local data.
130
+
131
+ ## Errors (`olbrain.exceptions`)
132
+
133
+ All of them subclass `OlbrainError`, which has `.message`, `.error_code` and
134
+ `.details`.
135
+
136
+ | Condition | Raised |
137
+ |---|---|
138
+ | Bad constructor args, empty message, bad `mode`/`status` | `ValueError` (**not** `ValidationError`) |
139
+ | HTTP 401 | `AuthenticationError` |
140
+ | HTTP 404 whose detail mentions "session" | `SessionNotFoundError` (a subclass of `SessionError`) |
141
+ | Other HTTP 404 | `OlbrainError` ("Endpoint not found (404) …") |
142
+ | HTTP 429 | `RateLimitError` (`.retry_after` from `detail.retry_after`, may be `None`) |
143
+ | Any other non-200 (403, 5xx…) | `OlbrainError("Failed to <operation>: <status> - <detail>")` |
144
+ | Connection error or timeout | `NetworkError` |
145
+
146
+ ```python
147
+ from olbrain import AgentClient, AuthenticationError, RateLimitError, NetworkError, OlbrainError
148
+ import time
149
+
150
+ def ask(client, sid, text, tries=3):
151
+ for i in range(tries):
152
+ try:
153
+ return client.send_and_wait(sid, text)
154
+ except RateLimitError as e:
155
+ time.sleep(e.retry_after or 2 ** i)
156
+ except NetworkError:
157
+ time.sleep(2 ** i)
158
+ raise OlbrainError("gave up")
159
+ ```
160
+
161
+ `ValidationError` and `StreamingError` are exported, but the client never
162
+ raises them.
163
+
164
+ ## Logging
165
+
166
+ The SDK logs through `logging.getLogger("olbrain")`. Turn on
167
+ `logging.basicConfig(level=logging.DEBUG)` to see requests and stream events.
olbrain/__init__.py CHANGED
@@ -1,6 +1,8 @@
1
1
  """
2
2
  Olbrain Python SDK
3
- Simple client for Olbrain AI agents
3
+ Simple client for Olbrain AI agents with real-time message streaming
4
+
5
+ Full offline API reference: AGENTS.md next to this file.
4
6
 
5
7
  Example:
6
8
  >>> from olbrain import AgentClient
@@ -9,14 +11,15 @@ Example:
9
11
  >>>
10
12
  >>> # Create session and send messages
11
13
  >>> session_id = client.create_session(title="My Chat")
12
- >>> response = client.send(session_id, "Hello!")
13
- >>> print(response['response'])
14
+ >>> response = client.send_and_wait(session_id, "Hello!")
15
+ >>> print(response.text)
14
16
  >>>
15
- >>> # Parse response as ChatResponse object
16
- >>> from olbrain import ChatResponse
17
- >>> chat_response = ChatResponse.from_dict(response, session_id)
18
- >>> print(chat_response.text)
19
- >>> print(f"Tokens: {chat_response.token_usage.total_tokens}")
17
+ >>> # Or with real-time streaming
18
+ >>> def on_message(msg):
19
+ ... print(f"{msg['role']}: {msg['content']}")
20
+ >>> session_id = client.create_session(on_message=on_message, title="Streaming Chat")
21
+ >>> client.send(session_id, "Hello!")
22
+ >>> client.run() # Blocks, receives all messages
20
23
  """
21
24
 
22
25
  from .client import AgentClient
@@ -32,7 +35,7 @@ from .exceptions import (
32
35
  StreamingError
33
36
  )
34
37
 
35
- __version__ = "0.3.0"
38
+ __version__ = "0.3.2"
36
39
  __author__ = "Olbrain Team"
37
40
  __email__ = "support@olbrain.com"
38
41