olbrain-python-sdk 0.3.1__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 +167 -0
- olbrain/__init__.py +3 -1
- {olbrain_python_sdk-0.3.1.dist-info → olbrain_python_sdk-0.3.2.dist-info}/METADATA +13 -11
- olbrain_python_sdk-0.3.2.dist-info/RECORD +12 -0
- {olbrain_python_sdk-0.3.1.dist-info → olbrain_python_sdk-0.3.2.dist-info}/WHEEL +1 -1
- {olbrain_python_sdk-0.3.1.dist-info → olbrain_python_sdk-0.3.2.dist-info}/top_level.txt +0 -1
- olbrain_python_sdk-0.3.1.dist-info/RECORD +0 -15
- tests/__init__.py +0 -0
- tests/test_client.py +0 -131
- tests/test_exceptions.py +0 -50
- tests/test_session.py +0 -89
- {olbrain_python_sdk-0.3.1.dist-info → olbrain_python_sdk-0.3.2.dist-info}/licenses/LICENSE +0 -0
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
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
Olbrain Python SDK
|
|
3
3
|
Simple client for Olbrain AI agents with real-time message streaming
|
|
4
4
|
|
|
5
|
+
Full offline API reference: AGENTS.md next to this file.
|
|
6
|
+
|
|
5
7
|
Example:
|
|
6
8
|
>>> from olbrain import AgentClient
|
|
7
9
|
>>>
|
|
@@ -33,7 +35,7 @@ from .exceptions import (
|
|
|
33
35
|
StreamingError
|
|
34
36
|
)
|
|
35
37
|
|
|
36
|
-
__version__ = "0.3.
|
|
38
|
+
__version__ = "0.3.2"
|
|
37
39
|
__author__ = "Olbrain Team"
|
|
38
40
|
__email__ = "support@olbrain.com"
|
|
39
41
|
|
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: olbrain-python-sdk
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.2
|
|
4
4
|
Summary: Official Python SDK for Olbrain AI agents
|
|
5
|
-
Home-page: https://github.com/Olbrain/olbrain-
|
|
5
|
+
Home-page: https://github.com/Olbrain/olbrain-sdk
|
|
6
6
|
Author: Olbrain Team
|
|
7
7
|
Author-email: Olbrain Team <support@olbrain.com>
|
|
8
8
|
License: MIT
|
|
9
|
-
Project-URL: Homepage, https://github.com/Olbrain/olbrain-python
|
|
10
|
-
Project-URL: Bug Reports, https://github.com/Olbrain/olbrain-
|
|
11
|
-
Project-URL: Source, https://github.com/Olbrain/olbrain-
|
|
9
|
+
Project-URL: Homepage, https://github.com/Olbrain/olbrain-sdk/tree/main/packages/python
|
|
10
|
+
Project-URL: Bug Reports, https://github.com/Olbrain/olbrain-sdk/issues
|
|
11
|
+
Project-URL: Source, https://github.com/Olbrain/olbrain-sdk
|
|
12
12
|
Project-URL: Documentation, https://docs.olbrain.com/python-sdk
|
|
13
13
|
Keywords: olbrain,ai,agents,chatbot,nlp,artificial intelligence,sdk,api,conversation,streaming
|
|
14
14
|
Classifier: Development Status :: 4 - Beta
|
|
@@ -54,6 +54,8 @@ Dynamic: requires-python
|
|
|
54
54
|
|
|
55
55
|
Official Python SDK for integrating Olbrain AI agents into your applications.
|
|
56
56
|
|
|
57
|
+
> **Coding assistants:** the complete API reference ships in the package as [`olbrain/AGENTS.md`](olbrain/AGENTS.md) (`site-packages/olbrain/AGENTS.md`).
|
|
58
|
+
|
|
57
59
|
## Installation
|
|
58
60
|
|
|
59
61
|
```bash
|
|
@@ -66,8 +68,8 @@ For local development and testing:
|
|
|
66
68
|
|
|
67
69
|
```bash
|
|
68
70
|
# Clone the repository
|
|
69
|
-
git clone https://github.com/Olbrain/olbrain-
|
|
70
|
-
cd olbrain-python
|
|
71
|
+
git clone https://github.com/Olbrain/olbrain-sdk.git
|
|
72
|
+
cd olbrain-sdk/packages/python
|
|
71
73
|
|
|
72
74
|
# Create virtual environment
|
|
73
75
|
python3 -m venv venv
|
|
@@ -315,7 +317,7 @@ The SDK validates API keys. Valid prefixes are:
|
|
|
315
317
|
# Valid API key
|
|
316
318
|
client = AgentClient(
|
|
317
319
|
agent_id="your-agent-id",
|
|
318
|
-
api_key="
|
|
320
|
+
api_key="sk_live_your_api_key_here"
|
|
319
321
|
)
|
|
320
322
|
```
|
|
321
323
|
|
|
@@ -509,7 +511,7 @@ python examples/basic_usage.py
|
|
|
509
511
|
|
|
510
512
|
## Support
|
|
511
513
|
|
|
512
|
-
- **Issues**: [GitHub Issues](https://github.com/Olbrain/olbrain-
|
|
514
|
+
- **Issues**: [GitHub Issues](https://github.com/Olbrain/olbrain-sdk/issues)
|
|
513
515
|
- **Documentation**: See [examples/](examples/) directory
|
|
514
516
|
- **API Status**: Check [status page](https://olbrain.com/status)
|
|
515
517
|
|
|
@@ -524,6 +526,6 @@ Current version: **0.2.0**
|
|
|
524
526
|
## Links
|
|
525
527
|
|
|
526
528
|
- [PyPI Package](https://pypi.org/project/olbrain-python-sdk/)
|
|
527
|
-
- [GitHub Repository](https://github.com/Olbrain/olbrain-
|
|
528
|
-
- [Report Issues](https://github.com/Olbrain/olbrain-
|
|
529
|
+
- [GitHub Repository](https://github.com/Olbrain/olbrain-sdk)
|
|
530
|
+
- [Report Issues](https://github.com/Olbrain/olbrain-sdk/issues)
|
|
529
531
|
- [Olbrain Website](https://olbrain.com)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
olbrain/AGENTS.md,sha256=j_nmd_yiV-30LXyh7SZ8zCk-sA3FKtvsqEZrz5hviHk,7142
|
|
2
|
+
olbrain/__init__.py,sha256=LsPxdzx58m43HJt5v7folxwnFkjVK4__pwFUgUXoR3o,1547
|
|
3
|
+
olbrain/client.py,sha256=GdSXnzL4iCqy6H-oyou--5bDvq07ss-bxSp7RIQsBBY,26337
|
|
4
|
+
olbrain/exceptions.py,sha256=mYfXNFJkR-VTC2PTHTPDErvBhwYW7h1DAE1IOtG0Mh4,1592
|
|
5
|
+
olbrain/session.py,sha256=0Off9pW0dTKYL9hzFYwH35zeNT5R20M9UfOKlCybYuQ,6662
|
|
6
|
+
olbrain/streaming.py,sha256=hEJUWvRLU3LTeiJE5wVeGCHBbTC4hDPphpx8X4w_iyU,4980
|
|
7
|
+
olbrain/utils.py,sha256=NrOB61Zub7i-ITlfXPfwUFunRR9YXJIS3MYgqVvqigM,4262
|
|
8
|
+
olbrain_python_sdk-0.3.2.dist-info/licenses/LICENSE,sha256=_4Q6zZ9zlqqRkRm_ZNiGTkmrMeTJc88agU6c_O-c5sI,1068
|
|
9
|
+
olbrain_python_sdk-0.3.2.dist-info/METADATA,sha256=h2A-yxAK-NEgtBBu8ljcSWS44WAUEgl_7BNltAzScSk,15631
|
|
10
|
+
olbrain_python_sdk-0.3.2.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
11
|
+
olbrain_python_sdk-0.3.2.dist-info/top_level.txt,sha256=iAqbGCG4mlzbE-zLwW4AgQv5_CI9enWxgc7yA9PttvM,8
|
|
12
|
+
olbrain_python_sdk-0.3.2.dist-info/RECORD,,
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
olbrain/__init__.py,sha256=W2nT5z53zN-pYyb4ZmJHAiPxWjnUWgGzatylpd10Dac,1489
|
|
2
|
-
olbrain/client.py,sha256=GdSXnzL4iCqy6H-oyou--5bDvq07ss-bxSp7RIQsBBY,26337
|
|
3
|
-
olbrain/exceptions.py,sha256=mYfXNFJkR-VTC2PTHTPDErvBhwYW7h1DAE1IOtG0Mh4,1592
|
|
4
|
-
olbrain/session.py,sha256=0Off9pW0dTKYL9hzFYwH35zeNT5R20M9UfOKlCybYuQ,6662
|
|
5
|
-
olbrain/streaming.py,sha256=hEJUWvRLU3LTeiJE5wVeGCHBbTC4hDPphpx8X4w_iyU,4980
|
|
6
|
-
olbrain/utils.py,sha256=NrOB61Zub7i-ITlfXPfwUFunRR9YXJIS3MYgqVvqigM,4262
|
|
7
|
-
olbrain_python_sdk-0.3.1.dist-info/licenses/LICENSE,sha256=_4Q6zZ9zlqqRkRm_ZNiGTkmrMeTJc88agU6c_O-c5sI,1068
|
|
8
|
-
tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
-
tests/test_client.py,sha256=2wekWbWRpCt7Bq5JSoS8rVk6KesvDYB3yhrgx9AQkO4,5227
|
|
10
|
-
tests/test_exceptions.py,sha256=DYwcEWKlPYmKTmTw2zilGR8hi3LXMDGyp4oCElY-Mis,1631
|
|
11
|
-
tests/test_session.py,sha256=m8E4Z1bq4I2tIdH0SN5qAOGwHff2ykurA_ksSC-VMOQ,2945
|
|
12
|
-
olbrain_python_sdk-0.3.1.dist-info/METADATA,sha256=DqMi8i9U0tAjJBRi6JZXRLZ_dhnGE3bgRTZUpbAIxSY,15544
|
|
13
|
-
olbrain_python_sdk-0.3.1.dist-info/WHEEL,sha256=YCfwYGOYMi5Jhw2fU4yNgwErybb2IX5PEwBKV4ZbdBo,91
|
|
14
|
-
olbrain_python_sdk-0.3.1.dist-info/top_level.txt,sha256=ecRnkShHqLzk3-IqzP2apQqeKk47kkh4L_6vJFzksIk,14
|
|
15
|
-
olbrain_python_sdk-0.3.1.dist-info/RECORD,,
|
tests/__init__.py
DELETED
|
File without changes
|
tests/test_client.py
DELETED
|
@@ -1,131 +0,0 @@
|
|
|
1
|
-
"""
|
|
2
|
-
Basic tests for AgentClient
|
|
3
|
-
"""
|
|
4
|
-
import pytest
|
|
5
|
-
import requests_mock
|
|
6
|
-
from olbrain import AgentClient
|
|
7
|
-
from olbrain.exceptions import AuthenticationError, AgentNotFoundError
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
class TestAgentClient:
|
|
11
|
-
def test_client_initialization(self):
|
|
12
|
-
"""Test AgentClient initialization with default parameters."""
|
|
13
|
-
client = AgentClient(agent_id="test-agent", api_key="sk_live_test-key")
|
|
14
|
-
assert client.agent_id == "test-agent"
|
|
15
|
-
assert client.api_key == "sk_live_test-key"
|
|
16
|
-
assert client.agent_url == "https://agent-test-agent-768934887465.us-central1.run.app"
|
|
17
|
-
|
|
18
|
-
def test_client_initialization_with_custom_url(self):
|
|
19
|
-
"""Test AgentClient initialization with custom URL."""
|
|
20
|
-
custom_url = "https://custom-agent-url.com"
|
|
21
|
-
client = AgentClient(
|
|
22
|
-
agent_id="test-agent",
|
|
23
|
-
api_key="sk_live_test-key",
|
|
24
|
-
agent_url=custom_url
|
|
25
|
-
)
|
|
26
|
-
assert client.agent_url == custom_url
|
|
27
|
-
|
|
28
|
-
@requests_mock.Mocker()
|
|
29
|
-
def test_create_session_success(self, m):
|
|
30
|
-
"""Test successful session creation."""
|
|
31
|
-
client = AgentClient(agent_id="test-agent", api_key="sk_live_test-key")
|
|
32
|
-
|
|
33
|
-
# Mock the session creation endpoint
|
|
34
|
-
m.post(
|
|
35
|
-
f"{client.agent_url}/sessions",
|
|
36
|
-
json={"session_id": "test-session-123"},
|
|
37
|
-
status_code=200
|
|
38
|
-
)
|
|
39
|
-
|
|
40
|
-
session = client.create_session()
|
|
41
|
-
assert session.session_id == "test-session-123"
|
|
42
|
-
assert session.client == client
|
|
43
|
-
|
|
44
|
-
@requests_mock.Mocker()
|
|
45
|
-
def test_create_session_auth_error(self, m):
|
|
46
|
-
"""Test session creation with authentication error."""
|
|
47
|
-
client = AgentClient(agent_id="test-agent", api_key="sk_live_invalid-key")
|
|
48
|
-
|
|
49
|
-
# Mock authentication error
|
|
50
|
-
m.post(
|
|
51
|
-
f"{client.agent_url}/sessions",
|
|
52
|
-
json={"error": "Invalid API key"},
|
|
53
|
-
status_code=401
|
|
54
|
-
)
|
|
55
|
-
|
|
56
|
-
with pytest.raises(AuthenticationError):
|
|
57
|
-
client.create_session()
|
|
58
|
-
|
|
59
|
-
@requests_mock.Mocker()
|
|
60
|
-
def test_get_session_success(self, m):
|
|
61
|
-
"""Test successful session retrieval."""
|
|
62
|
-
client = AgentClient(agent_id="test-agent", api_key="sk_live_test-key")
|
|
63
|
-
session_id = "existing-session-123"
|
|
64
|
-
|
|
65
|
-
# Mock the session retrieval endpoint
|
|
66
|
-
m.get(
|
|
67
|
-
f"{client.agent_url}/sessions/{session_id}",
|
|
68
|
-
json={"session_id": session_id, "history": []},
|
|
69
|
-
status_code=200
|
|
70
|
-
)
|
|
71
|
-
|
|
72
|
-
session = client.get_session(session_id)
|
|
73
|
-
assert session.session_id == session_id
|
|
74
|
-
assert session.client == client
|
|
75
|
-
|
|
76
|
-
@requests_mock.Mocker()
|
|
77
|
-
def test_get_session_not_found(self, m):
|
|
78
|
-
"""Test session retrieval with session not found."""
|
|
79
|
-
client = AgentClient(agent_id="test-agent", api_key="sk_live_test-key")
|
|
80
|
-
session_id = "non-existent-session"
|
|
81
|
-
|
|
82
|
-
# Mock session not found error
|
|
83
|
-
m.get(
|
|
84
|
-
f"{client.agent_url}/sessions/{session_id}",
|
|
85
|
-
json={"error": "Session not found"},
|
|
86
|
-
status_code=404
|
|
87
|
-
)
|
|
88
|
-
|
|
89
|
-
with pytest.raises(AgentNotFoundError):
|
|
90
|
-
client.get_session(session_id)
|
|
91
|
-
|
|
92
|
-
# API Key Validation Tests
|
|
93
|
-
def test_api_key_with_sk_live_prefix_accepted(self):
|
|
94
|
-
"""Test that API keys with sk_live_ prefix are accepted."""
|
|
95
|
-
client = AgentClient(agent_id="test-agent", api_key="sk_live_test123456")
|
|
96
|
-
assert client.api_key == "sk_live_test123456"
|
|
97
|
-
|
|
98
|
-
def test_api_key_with_org_live_prefix_accepted(self):
|
|
99
|
-
"""Test that API keys with org_live_ prefix are accepted."""
|
|
100
|
-
client = AgentClient(agent_id="test-agent", api_key="org_live_test123456")
|
|
101
|
-
assert client.api_key == "org_live_test123456"
|
|
102
|
-
|
|
103
|
-
def test_api_key_with_sk_prefix_accepted(self):
|
|
104
|
-
"""Test that API keys with sk_ prefix are accepted (dev/test)."""
|
|
105
|
-
client = AgentClient(agent_id="test-agent", api_key="sk_test123456")
|
|
106
|
-
assert client.api_key == "sk_test123456"
|
|
107
|
-
|
|
108
|
-
def test_api_key_with_org_prefix_accepted(self):
|
|
109
|
-
"""Test that API keys with org_ prefix are accepted (dev/test)."""
|
|
110
|
-
client = AgentClient(agent_id="test-agent", api_key="org_test123456")
|
|
111
|
-
assert client.api_key == "org_test123456"
|
|
112
|
-
|
|
113
|
-
def test_api_key_with_ak_prefix_rejected(self):
|
|
114
|
-
"""Test that API keys with ak_ prefix are rejected."""
|
|
115
|
-
with pytest.raises(ValueError, match="Invalid API key"):
|
|
116
|
-
AgentClient(agent_id="test-agent", api_key="ak_test123456")
|
|
117
|
-
|
|
118
|
-
def test_api_key_with_invalid_prefix_rejected(self):
|
|
119
|
-
"""Test that API keys with invalid prefixes are rejected."""
|
|
120
|
-
with pytest.raises(ValueError, match="Invalid API key"):
|
|
121
|
-
AgentClient(agent_id="test-agent", api_key="invalid_key123")
|
|
122
|
-
|
|
123
|
-
def test_empty_api_key_rejected(self):
|
|
124
|
-
"""Test that empty API keys are rejected."""
|
|
125
|
-
with pytest.raises(ValueError, match="Invalid API key"):
|
|
126
|
-
AgentClient(agent_id="test-agent", api_key="")
|
|
127
|
-
|
|
128
|
-
def test_none_api_key_rejected(self):
|
|
129
|
-
"""Test that None API keys are rejected."""
|
|
130
|
-
with pytest.raises(ValueError, match="Invalid API key"):
|
|
131
|
-
AgentClient(agent_id="test-agent", api_key=None)
|
tests/test_exceptions.py
DELETED
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
"""
|
|
2
|
-
Basic tests for custom exceptions
|
|
3
|
-
"""
|
|
4
|
-
import pytest
|
|
5
|
-
from olbrain.exceptions import (
|
|
6
|
-
OlbrainError,
|
|
7
|
-
AuthenticationError,
|
|
8
|
-
AgentNotFoundError,
|
|
9
|
-
SessionError,
|
|
10
|
-
RateLimitError,
|
|
11
|
-
NetworkError
|
|
12
|
-
)
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
class TestExceptions:
|
|
16
|
-
def test_olbrain_error_base(self):
|
|
17
|
-
"""Test base OlbrainError exception."""
|
|
18
|
-
error = OlbrainError("Test error message")
|
|
19
|
-
assert str(error) == "Test error message"
|
|
20
|
-
assert isinstance(error, Exception)
|
|
21
|
-
|
|
22
|
-
def test_authentication_error(self):
|
|
23
|
-
"""Test AuthenticationError exception."""
|
|
24
|
-
error = AuthenticationError("Invalid API key")
|
|
25
|
-
assert str(error) == "Invalid API key"
|
|
26
|
-
assert isinstance(error, OlbrainError)
|
|
27
|
-
|
|
28
|
-
def test_agent_not_found_error(self):
|
|
29
|
-
"""Test AgentNotFoundError exception."""
|
|
30
|
-
error = AgentNotFoundError("Agent not found")
|
|
31
|
-
assert str(error) == "Agent not found"
|
|
32
|
-
assert isinstance(error, OlbrainError)
|
|
33
|
-
|
|
34
|
-
def test_session_error(self):
|
|
35
|
-
"""Test SessionError exception."""
|
|
36
|
-
error = SessionError("Session expired")
|
|
37
|
-
assert str(error) == "Session expired"
|
|
38
|
-
assert isinstance(error, OlbrainError)
|
|
39
|
-
|
|
40
|
-
def test_rate_limit_error(self):
|
|
41
|
-
"""Test RateLimitError exception."""
|
|
42
|
-
error = RateLimitError("Rate limit exceeded")
|
|
43
|
-
assert str(error) == "Rate limit exceeded"
|
|
44
|
-
assert isinstance(error, OlbrainError)
|
|
45
|
-
|
|
46
|
-
def test_network_error(self):
|
|
47
|
-
"""Test NetworkError exception."""
|
|
48
|
-
error = NetworkError("Connection timeout")
|
|
49
|
-
assert str(error) == "Connection timeout"
|
|
50
|
-
assert isinstance(error, OlbrainError)
|
tests/test_session.py
DELETED
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
"""
|
|
2
|
-
Basic tests for Session
|
|
3
|
-
"""
|
|
4
|
-
import pytest
|
|
5
|
-
import requests_mock
|
|
6
|
-
from olbrain import AgentClient, Session
|
|
7
|
-
from olbrain.exceptions import SessionError
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
class TestSession:
|
|
11
|
-
def test_session_initialization(self):
|
|
12
|
-
"""Test Session initialization."""
|
|
13
|
-
client = AgentClient(agent_id="test-agent", api_key="test-key")
|
|
14
|
-
session = Session(session_id="test-session", client=client)
|
|
15
|
-
|
|
16
|
-
assert session.session_id == "test-session"
|
|
17
|
-
assert session.client == client
|
|
18
|
-
assert session._message_cache == []
|
|
19
|
-
|
|
20
|
-
@requests_mock.Mocker()
|
|
21
|
-
def test_send_message_success(self, m):
|
|
22
|
-
"""Test successful message sending."""
|
|
23
|
-
client = AgentClient(agent_id="test-agent", api_key="test-key")
|
|
24
|
-
session = Session(session_id="test-session", client=client)
|
|
25
|
-
|
|
26
|
-
# Mock the message sending endpoint
|
|
27
|
-
m.post(
|
|
28
|
-
f"{client.agent_url}/sessions/test-session/messages",
|
|
29
|
-
json={
|
|
30
|
-
"response": "Hello! How can I help you?",
|
|
31
|
-
"message_id": "msg-123"
|
|
32
|
-
},
|
|
33
|
-
status_code=200
|
|
34
|
-
)
|
|
35
|
-
|
|
36
|
-
response = session.send_message("Hello")
|
|
37
|
-
assert response.text == "Hello! How can I help you?"
|
|
38
|
-
assert response.message_id == "msg-123"
|
|
39
|
-
|
|
40
|
-
@requests_mock.Mocker()
|
|
41
|
-
def test_send_message_error(self, m):
|
|
42
|
-
"""Test message sending with error."""
|
|
43
|
-
client = AgentClient(agent_id="test-agent", api_key="test-key")
|
|
44
|
-
session = Session(session_id="invalid-session", client=client)
|
|
45
|
-
|
|
46
|
-
# Mock session error
|
|
47
|
-
m.post(
|
|
48
|
-
f"{client.agent_url}/sessions/invalid-session/messages",
|
|
49
|
-
json={"error": "Session expired"},
|
|
50
|
-
status_code=400
|
|
51
|
-
)
|
|
52
|
-
|
|
53
|
-
with pytest.raises(SessionError):
|
|
54
|
-
session.send_message("Hello")
|
|
55
|
-
|
|
56
|
-
@requests_mock.Mocker()
|
|
57
|
-
def test_get_history_success(self, m):
|
|
58
|
-
"""Test successful history retrieval."""
|
|
59
|
-
client = AgentClient(agent_id="test-agent", api_key="test-key")
|
|
60
|
-
session = Session(session_id="test-session", client=client)
|
|
61
|
-
|
|
62
|
-
# Mock the history endpoint
|
|
63
|
-
mock_history = [
|
|
64
|
-
{
|
|
65
|
-
"message_info": {
|
|
66
|
-
"role": "user",
|
|
67
|
-
"content": "Hello"
|
|
68
|
-
}
|
|
69
|
-
},
|
|
70
|
-
{
|
|
71
|
-
"message_info": {
|
|
72
|
-
"role": "assistant",
|
|
73
|
-
"content": "Hi there!"
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
]
|
|
77
|
-
|
|
78
|
-
m.get(
|
|
79
|
-
f"{client.agent_url}/sessions/test-session/history",
|
|
80
|
-
json={"history": mock_history},
|
|
81
|
-
status_code=200
|
|
82
|
-
)
|
|
83
|
-
|
|
84
|
-
history = session.get_history()
|
|
85
|
-
assert len(history) == 2
|
|
86
|
-
assert history[0]["role"] == "user"
|
|
87
|
-
assert history[0]["content"] == "Hello"
|
|
88
|
-
assert history[1]["role"] == "assistant"
|
|
89
|
-
assert history[1]["content"] == "Hi there!"
|
|
File without changes
|