olbrain-python-sdk 0.2.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.
Files changed (31) hide show
  1. olbrain_python_sdk-0.2.0/.gitignore +79 -0
  2. olbrain_python_sdk-0.2.0/LICENSE +21 -0
  3. olbrain_python_sdk-0.2.0/MANIFEST.in +11 -0
  4. olbrain_python_sdk-0.2.0/PKG-INFO +357 -0
  5. olbrain_python_sdk-0.2.0/README.md +309 -0
  6. olbrain_python_sdk-0.2.0/examples/advanced_features.py +478 -0
  7. olbrain_python_sdk-0.2.0/examples/basic_usage.py +163 -0
  8. olbrain_python_sdk-0.2.0/examples/error_handling.py +449 -0
  9. olbrain_python_sdk-0.2.0/examples/session_management.py +213 -0
  10. olbrain_python_sdk-0.2.0/examples/streaming_responses.py +237 -0
  11. olbrain_python_sdk-0.2.0/olbrain/__init__.py +58 -0
  12. olbrain_python_sdk-0.2.0/olbrain/client.py +627 -0
  13. olbrain_python_sdk-0.2.0/olbrain/exceptions.py +64 -0
  14. olbrain_python_sdk-0.2.0/olbrain/session.py +202 -0
  15. olbrain_python_sdk-0.2.0/olbrain/streaming.py +137 -0
  16. olbrain_python_sdk-0.2.0/olbrain/utils.py +156 -0
  17. olbrain_python_sdk-0.2.0/olbrain_python_sdk.egg-info/PKG-INFO +357 -0
  18. olbrain_python_sdk-0.2.0/olbrain_python_sdk.egg-info/SOURCES.txt +29 -0
  19. olbrain_python_sdk-0.2.0/olbrain_python_sdk.egg-info/dependency_links.txt +1 -0
  20. olbrain_python_sdk-0.2.0/olbrain_python_sdk.egg-info/not-zip-safe +1 -0
  21. olbrain_python_sdk-0.2.0/olbrain_python_sdk.egg-info/requires.txt +15 -0
  22. olbrain_python_sdk-0.2.0/olbrain_python_sdk.egg-info/top_level.txt +2 -0
  23. olbrain_python_sdk-0.2.0/pyproject.toml +92 -0
  24. olbrain_python_sdk-0.2.0/requirements.txt +3 -0
  25. olbrain_python_sdk-0.2.0/setup.cfg +4 -0
  26. olbrain_python_sdk-0.2.0/setup.py +85 -0
  27. olbrain_python_sdk-0.2.0/test_agent.py +143 -0
  28. olbrain_python_sdk-0.2.0/tests/__init__.py +0 -0
  29. olbrain_python_sdk-0.2.0/tests/test_client.py +91 -0
  30. olbrain_python_sdk-0.2.0/tests/test_exceptions.py +50 -0
  31. olbrain_python_sdk-0.2.0/tests/test_session.py +89 -0
@@ -0,0 +1,79 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ *.egg-info/
24
+ .installed.cfg
25
+ *.egg
26
+
27
+ # PyInstaller
28
+ *.manifest
29
+ *.spec
30
+
31
+ # Installer logs
32
+ pip-log.txt
33
+ pip-delete-this-directory.txt
34
+
35
+ # Unit test / coverage reports
36
+ htmlcov/
37
+ .tox/
38
+ .nox/
39
+ .coverage
40
+ .coverage.*
41
+ .cache
42
+ nosetests.xml
43
+ coverage.xml
44
+ *.cover
45
+ *.py,cover
46
+ .hypothesis/
47
+ .pytest_cache/
48
+
49
+ # Translations
50
+ *.mo
51
+ *.pot
52
+
53
+ # Environments
54
+ .env
55
+ .venv
56
+ env/
57
+ venv/
58
+ ENV/
59
+ env.bak/
60
+ venv.bak/
61
+
62
+ # IDE
63
+ .idea/
64
+ .vscode/
65
+ *.swp
66
+ *.swo
67
+ *~
68
+
69
+ # Jupyter Notebook
70
+ .ipynb_checkpoints
71
+
72
+ # mypy
73
+ .mypy_cache/
74
+ .dmypy.json
75
+ dmypy.json
76
+
77
+ # OS
78
+ .DS_Store
79
+ Thumbs.db
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Olbrain Team
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,11 @@
1
+ # Include important files in the package distribution
2
+ include README.md
3
+ include LICENSE
4
+ include requirements.txt
5
+ include pyproject.toml
6
+ recursive-include olbrain *.py
7
+ recursive-exclude * __pycache__
8
+ recursive-exclude * *.py[co]
9
+ global-exclude .DS_Store
10
+ global-exclude *.pyc
11
+ global-exclude *.pyo
@@ -0,0 +1,357 @@
1
+ Metadata-Version: 2.4
2
+ Name: olbrain-python-sdk
3
+ Version: 0.2.0
4
+ Summary: Official Python SDK for Olbrain AI agents
5
+ Home-page: https://github.com/Olbrain/olbrain-python-sdk
6
+ Author: Olbrain Team
7
+ Author-email: Olbrain Team <support@olbrain.com>
8
+ License: MIT
9
+ Project-URL: Homepage, https://github.com/Olbrain/olbrain-python-sdk
10
+ Project-URL: Bug Reports, https://github.com/Olbrain/olbrain-python-sdk/issues
11
+ Project-URL: Source, https://github.com/Olbrain/olbrain-python-sdk
12
+ Project-URL: Documentation, https://docs.olbrain.com/python-sdk
13
+ Keywords: olbrain,ai,agents,chatbot,nlp,artificial intelligence,sdk,api,conversation,streaming
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.7
20
+ Classifier: Programming Language :: Python :: 3.8
21
+ Classifier: Programming Language :: Python :: 3.9
22
+ Classifier: Programming Language :: Python :: 3.10
23
+ Classifier: Programming Language :: Python :: 3.11
24
+ Classifier: Programming Language :: Python :: 3.12
25
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
26
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
27
+ Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
28
+ Requires-Python: >=3.7
29
+ Description-Content-Type: text/markdown
30
+ License-File: LICENSE
31
+ Requires-Dist: requests>=2.25.0
32
+ Requires-Dist: urllib3>=1.26.0
33
+ Provides-Extra: dev
34
+ Requires-Dist: pytest>=6.0.0; extra == "dev"
35
+ Requires-Dist: pytest-asyncio>=0.18.0; extra == "dev"
36
+ Requires-Dist: pytest-cov>=2.12.0; extra == "dev"
37
+ Requires-Dist: black>=22.0.0; extra == "dev"
38
+ Requires-Dist: flake8>=4.0.0; extra == "dev"
39
+ Requires-Dist: mypy>=0.910; extra == "dev"
40
+ Requires-Dist: requests-mock>=1.9.0; extra == "dev"
41
+ Provides-Extra: async
42
+ Requires-Dist: aiohttp>=3.8.0; extra == "async"
43
+ Requires-Dist: aiofiles>=0.7.0; extra == "async"
44
+ Dynamic: author
45
+ Dynamic: home-page
46
+ Dynamic: license-file
47
+ Dynamic: requires-python
48
+
49
+ # Olbrain Python SDK
50
+
51
+ [![PyPI version](https://badge.fury.io/py/olbrain-python-sdk.svg)](https://badge.fury.io/py/olbrain-python-sdk)
52
+ [![Python Support](https://img.shields.io/pypi/pyversions/olbrain-python-sdk.svg)](https://pypi.org/project/olbrain-python-sdk/)
53
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
54
+
55
+ Official Python SDK for integrating Olbrain AI agents into websites and mobile apps. Provides a simple interface for session management, messaging, and real-time streaming.
56
+
57
+ ## Features
58
+
59
+ - **Simple Integration**: Just provide `agent_id` and `api_key`
60
+ - **Session Management**: Full CRUD operations for sessions
61
+ - **Synchronous & Streaming**: Both request-response and real-time streaming patterns
62
+ - **Message History**: Retrieve conversation history with pagination
63
+ - **Token Tracking**: Monitor token usage and costs
64
+ - **Model Override**: Switch models per-message
65
+ - **Error Handling**: Comprehensive exception hierarchy
66
+
67
+ ## Installation
68
+
69
+ ```bash
70
+ pip install olbrain-python-sdk
71
+ ```
72
+
73
+ ### Development Installation
74
+
75
+ ```bash
76
+ git clone https://github.com/olbrain/olbrain-python-sdk.git
77
+ cd olbrain-python-sdk
78
+ pip install -e ".[dev]"
79
+ ```
80
+
81
+ ## Quick Start
82
+
83
+ ### Basic Usage (Synchronous)
84
+
85
+ ```python
86
+ from olbrain import AgentClient
87
+
88
+ # Initialize client
89
+ client = AgentClient(
90
+ agent_id="your-agent-id",
91
+ api_key="ak_your_api_key"
92
+ )
93
+
94
+ # Create a session
95
+ session_id = client.create_session(title="My Chat", user_id="user-123")
96
+
97
+ # Send message and get response
98
+ response = client.send_and_wait(session_id, "Hello! How can you help me?")
99
+ print(f"Agent: {response.text}")
100
+ print(f"Tokens used: {response.token_usage.total_tokens}")
101
+
102
+ # Clean up
103
+ client.close()
104
+ ```
105
+
106
+ ### Real-Time Streaming
107
+
108
+ ```python
109
+ from olbrain import AgentClient
110
+
111
+ client = AgentClient(agent_id="your-agent-id", api_key="ak_your_api_key")
112
+
113
+ # Define callback for incoming messages
114
+ def on_message(msg):
115
+ print(f"[{msg['role']}]: {msg['content']}")
116
+
117
+ # Create session with streaming enabled
118
+ session_id = client.create_session(on_message=on_message, title="Streaming Chat")
119
+
120
+ # Send message - response arrives via callback
121
+ client.send(session_id, "Tell me a story")
122
+
123
+ # Block and process messages (Ctrl+C to exit)
124
+ client.run()
125
+ ```
126
+
127
+ ### Session Management
128
+
129
+ ```python
130
+ from olbrain import AgentClient
131
+
132
+ client = AgentClient(agent_id="your-agent-id", api_key="ak_your_api_key")
133
+
134
+ # Create session with metadata
135
+ session_id = client.create_session(
136
+ title="Support Chat",
137
+ user_id="customer-456",
138
+ metadata={"source": "website", "page": "/help"},
139
+ mode="production", # or "development", "testing"
140
+ description="Customer support conversation"
141
+ )
142
+
143
+ # Get session details
144
+ info = client.get_session(session_id)
145
+ print(f"Title: {info.title}")
146
+ print(f"Status: {info.status}")
147
+ print(f"Messages: {info.message_count}")
148
+
149
+ # Update session
150
+ client.update_session(session_id, title="Renamed Chat")
151
+
152
+ # Get message history
153
+ result = client.get_messages(session_id, limit=20)
154
+ for msg in result['messages']:
155
+ print(f"{msg['role']}: {msg['content']}")
156
+
157
+ # Get session statistics
158
+ stats = client.get_session_stats(session_id)
159
+ print(f"Total tokens: {stats['stats'].get('total_tokens')}")
160
+
161
+ # Archive session when done
162
+ client.delete_session(session_id)
163
+ ```
164
+
165
+ ### Model Override
166
+
167
+ ```python
168
+ # Use a specific model for a message
169
+ response = client.send(
170
+ session_id,
171
+ "Explain quantum computing",
172
+ model="gpt-4" # Override the agent's default model
173
+ )
174
+ ```
175
+
176
+ ### Error Handling
177
+
178
+ ```python
179
+ from olbrain import AgentClient
180
+ from olbrain.exceptions import (
181
+ AuthenticationError,
182
+ SessionNotFoundError,
183
+ RateLimitError,
184
+ NetworkError,
185
+ OlbrainError
186
+ )
187
+
188
+ try:
189
+ client = AgentClient(agent_id="your-agent-id", api_key="ak_your_key")
190
+ session_id = client.create_session()
191
+ response = client.send_and_wait(session_id, "Hello!")
192
+
193
+ except AuthenticationError:
194
+ print("Invalid API key")
195
+ except SessionNotFoundError:
196
+ print("Session does not exist")
197
+ except RateLimitError as e:
198
+ print(f"Rate limited. Retry after {e.retry_after} seconds")
199
+ except NetworkError as e:
200
+ print(f"Network error: {e}")
201
+ except OlbrainError as e:
202
+ print(f"Error: {e}")
203
+ ```
204
+
205
+ ### Context Manager
206
+
207
+ ```python
208
+ from olbrain import AgentClient
209
+
210
+ with AgentClient(agent_id="your-agent-id", api_key="ak_your_key") as client:
211
+ session_id = client.create_session(title="Quick Chat")
212
+ response = client.send_and_wait(session_id, "Hello!")
213
+ print(response.text)
214
+ # Client automatically closed
215
+ ```
216
+
217
+ ## API Reference
218
+
219
+ ### AgentClient
220
+
221
+ Main client class for interacting with Olbrain agents.
222
+
223
+ #### Constructor
224
+
225
+ ```python
226
+ AgentClient(
227
+ agent_id: str, # Agent identifier (required)
228
+ api_key: str, # API key starting with 'ak_' (required)
229
+ agent_url: str = None # Custom URL (auto-constructed if not provided)
230
+ )
231
+ ```
232
+
233
+ #### Methods
234
+
235
+ | Method | Description |
236
+ |--------|-------------|
237
+ | `create_session(on_message, title, user_id, metadata, mode, description)` | Create a new session |
238
+ | `send(session_id, message, user_id, metadata, model, mode)` | Send message (async via callback) |
239
+ | `send_and_wait(session_id, message, user_id, metadata, model, timeout)` | Send message and wait for response |
240
+ | `listen(session_id, on_message)` | Start listening to a session |
241
+ | `get_session(session_id)` | Get session details |
242
+ | `update_session(session_id, title, metadata, status)` | Update session |
243
+ | `delete_session(session_id)` | Archive a session |
244
+ | `get_session_stats(session_id)` | Get session statistics |
245
+ | `get_messages(session_id, limit, offset)` | Get message history |
246
+ | `run()` | Block and process message callbacks |
247
+ | `close()` | Clean up resources |
248
+
249
+ ### Data Classes
250
+
251
+ #### ChatResponse
252
+
253
+ ```python
254
+ @dataclass
255
+ class ChatResponse:
256
+ text: str # Response text
257
+ session_id: str # Session identifier
258
+ success: bool # Success status
259
+ token_usage: Optional[TokenUsage] # Token usage info
260
+ model_used: Optional[str] # Model that generated response
261
+ response_time_ms: Optional[int] # Response time
262
+ error: Optional[str] # Error message if failed
263
+ ```
264
+
265
+ #### TokenUsage
266
+
267
+ ```python
268
+ @dataclass
269
+ class TokenUsage:
270
+ prompt_tokens: int # Input tokens
271
+ completion_tokens: int # Output tokens
272
+ total_tokens: int # Total tokens
273
+ cost: float # Cost in USD
274
+ ```
275
+
276
+ #### SessionInfo
277
+
278
+ ```python
279
+ @dataclass
280
+ class SessionInfo:
281
+ session_id: str # Session identifier
282
+ title: str # Session title
283
+ status: str # 'active' or 'archived'
284
+ created_at: str # Creation timestamp
285
+ updated_at: str # Last update timestamp
286
+ message_count: int # Number of messages
287
+ user_id: Optional[str] # User identifier
288
+ channel: str # Channel type
289
+ metadata: Dict # Session metadata
290
+ ```
291
+
292
+ ### Exceptions
293
+
294
+ | Exception | Description |
295
+ |-----------|-------------|
296
+ | `OlbrainError` | Base exception class |
297
+ | `AuthenticationError` | Invalid API key |
298
+ | `SessionNotFoundError` | Session does not exist |
299
+ | `SessionError` | Session operation failed |
300
+ | `RateLimitError` | Rate limit exceeded (has `retry_after`) |
301
+ | `NetworkError` | Network connectivity issues |
302
+ | `ValidationError` | Input validation failed |
303
+ | `StreamingError` | Streaming error |
304
+
305
+ ## Configuration
306
+
307
+ ### Environment Variables
308
+
309
+ ```bash
310
+ export OLBRAIN_API_KEY="ak_your_api_key"
311
+ export OLBRAIN_AGENT_ID="your-agent-id"
312
+ export OLBRAIN_AGENT_URL="https://custom-url.com" # Optional
313
+ ```
314
+
315
+ ### Logging
316
+
317
+ ```python
318
+ import logging
319
+ logging.basicConfig(level=logging.DEBUG)
320
+ ```
321
+
322
+ ## Examples
323
+
324
+ See the [examples/](examples/) directory:
325
+
326
+ - `basic_usage.py` - Core SDK features
327
+ - `session_management.py` - Session CRUD operations
328
+ - `streaming_responses.py` - Real-time streaming
329
+
330
+ ## Changelog
331
+
332
+ ### v0.2.0
333
+
334
+ - Added session management methods (`get_session`, `update_session`, `delete_session`)
335
+ - Added `get_session_stats` and `get_messages` for analytics
336
+ - Added `send_and_wait` for synchronous request-response
337
+ - Enhanced `create_session` with `user_id`, `metadata`, `mode`, `description`
338
+ - Enhanced `send` with `user_id`, `metadata`, `model` override
339
+ - Added `TokenUsage` and `SessionInfo` data classes
340
+ - Added `SessionNotFoundError` exception
341
+ - Improved error handling with `_handle_response_errors`
342
+ - Renamed from `alchemist` to `olbrain`
343
+
344
+ ### v0.1.0
345
+
346
+ - Initial release
347
+ - Basic session creation and messaging
348
+ - Real-time streaming support
349
+
350
+ ## License
351
+
352
+ MIT License - see [LICENSE](LICENSE) for details.
353
+
354
+ ## Support
355
+
356
+ - **Issues**: [GitHub Issues](https://github.com/olbrain/olbrain-python-sdk/issues)
357
+ - **Email**: support@olbrain.com