hibira 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.
- hibira-0.1.0/.gitignore +10 -0
- hibira-0.1.0/CHANGELOG.md +13 -0
- hibira-0.1.0/LICENSE +21 -0
- hibira-0.1.0/PKG-INFO +297 -0
- hibira-0.1.0/README.md +268 -0
- hibira-0.1.0/pyproject.toml +71 -0
- hibira-0.1.0/src/hibira/__init__.py +43 -0
- hibira-0.1.0/src/hibira/_client.py +479 -0
- hibira-0.1.0/src/hibira/_errors.py +72 -0
- hibira-0.1.0/src/hibira/_signing.py +106 -0
- hibira-0.1.0/src/hibira/_version.py +1 -0
- hibira-0.1.0/src/hibira/fastapi.py +128 -0
- hibira-0.1.0/src/hibira/py.typed +0 -0
- hibira-0.1.0/src/hibira/stream.py +419 -0
- hibira-0.1.0/tests/test_client.py +201 -0
- hibira-0.1.0/tests/test_e2e.py +166 -0
- hibira-0.1.0/tests/test_fastapi.py +71 -0
- hibira-0.1.0/tests/test_signing.py +90 -0
- hibira-0.1.0/tests/test_stream.py +218 -0
hibira-0.1.0/.gitignore
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
First release.
|
|
6
|
+
|
|
7
|
+
- `Client` and `AsyncClient`: `trigger`, `trigger_batch`, `channels`, `channel_info`, `users`, `terminate_user_connections`, settings from `HIBIRA_*` environment variables.
|
|
8
|
+
- Channel and user auth (`authenticate_channel`, `authenticate_user`) and webhook verification (`verify_webhook`).
|
|
9
|
+
- Hibira Push: `push_to_interests`, `push_to_users`, `push_token`, `delete_push_user`.
|
|
10
|
+
- Approvals: `request_approval`, `get_approval`, `wait_for_approval`.
|
|
11
|
+
- `stream_to_channel` / `astream_to_channel`: stream LLM output to `useStream()` in `@hibira-io/react` and `@hibira-io/vue`, with `text_of` for OpenAI, Anthropic, OpenAI Agents SDK, LangChain / LangGraph and Gemini chunks.
|
|
12
|
+
- Errors: `HibiraError` base; `HTTPError` with `AuthenticationError`, `NotFound`, `PayloadTooLarge`, `RateLimited`; `ConnectionError` for network failures; `InvalidWebhook`, `ConfigError`.
|
|
13
|
+
- `hibira.fastapi`: channel / user auth router and webhook dependency.
|
hibira-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Hibira
|
|
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.
|
hibira-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: hibira
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Hibira for Python: realtime events, channel auth, webhooks, push notifications, approvals and LLM streaming (Pusher-compatible)
|
|
5
|
+
Project-URL: Homepage, https://hibira.io
|
|
6
|
+
Project-URL: Documentation, https://github.com/hibira-io/python#readme
|
|
7
|
+
Project-URL: Source, https://github.com/hibira-io/python
|
|
8
|
+
Project-URL: Changelog, https://github.com/hibira-io/python/blob/main/CHANGELOG.md
|
|
9
|
+
Project-URL: Issues, https://github.com/hibira-io/python/issues
|
|
10
|
+
Author-email: Hibira <dev@hibira.io>
|
|
11
|
+
License-Expression: MIT
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: channels,fastapi,hibira,langgraph,llm,push notifications,pusher,realtime,streaming,websocket
|
|
14
|
+
Classifier: Development Status :: 4 - Beta
|
|
15
|
+
Classifier: Framework :: AsyncIO
|
|
16
|
+
Classifier: Framework :: FastAPI
|
|
17
|
+
Classifier: Intended Audience :: Developers
|
|
18
|
+
Classifier: Operating System :: OS Independent
|
|
19
|
+
Classifier: Programming Language :: Python :: 3
|
|
20
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
21
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
22
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
23
|
+
Classifier: Typing :: Typed
|
|
24
|
+
Requires-Python: >=3.9
|
|
25
|
+
Requires-Dist: httpx<1,>=0.24
|
|
26
|
+
Provides-Extra: fastapi
|
|
27
|
+
Requires-Dist: fastapi>=0.100; extra == 'fastapi'
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
# hibira
|
|
31
|
+
|
|
32
|
+
Python server library for [Hibira](https://hibira.io), hosted realtime that
|
|
33
|
+
speaks the Pusher Channels protocol. Publish events, authorize private and
|
|
34
|
+
presence channels, verify webhooks, send push notifications, ask a person for
|
|
35
|
+
an approval, and stream LLM output to the browser as it is written.
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
pip install hibira
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Python 3.9+, one dependency ([httpx](https://www.python-httpx.org/)). Both a
|
|
42
|
+
regular and an asyncio client. pusher-js, Laravel Echo and the
|
|
43
|
+
`@hibira-io/*` front-end packages connect to Hibira unchanged.
|
|
44
|
+
|
|
45
|
+
## Set up
|
|
46
|
+
|
|
47
|
+
Create an app at [hibira.io/portal](https://hibira.io/portal) (the free plan
|
|
48
|
+
needs no card) and put its keys in the environment:
|
|
49
|
+
|
|
50
|
+
```sh
|
|
51
|
+
HIBIRA_APP_ID=...
|
|
52
|
+
HIBIRA_APP_KEY=...
|
|
53
|
+
HIBIRA_APP_SECRET=...
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
import hibira
|
|
58
|
+
|
|
59
|
+
client = hibira.Client.from_env() # or hibira.Client(app_id, key, secret)
|
|
60
|
+
client.trigger("orders", "created", {"id": 1042})
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
async with hibira.AsyncClient.from_env() as client:
|
|
65
|
+
await client.trigger(["orders", "dashboard"], "created", {"id": 1042})
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
| Setting | Environment | Default |
|
|
69
|
+
| --- | --- | --- |
|
|
70
|
+
| `app_id`, `key`, `secret` | `HIBIRA_APP_ID`, `HIBIRA_APP_KEY`, `HIBIRA_APP_SECRET` | |
|
|
71
|
+
| `host` | `HIBIRA_HOST` | `ws.hibira.io` (or the host shown on your app page) |
|
|
72
|
+
| `port`, `use_tls` | `HIBIRA_PORT`, `HIBIRA_USE_TLS` | `443`, `True` |
|
|
73
|
+
| `push_instance_id`, `push_secret_key` | `HIBIRA_PUSH_INSTANCE_ID`, `HIBIRA_PUSH_SECRET_KEY` | |
|
|
74
|
+
| `push_endpoint` | `HIBIRA_PUSH_ENDPOINT` | `https://<host>` |
|
|
75
|
+
| `timeout` | | `10.0` seconds |
|
|
76
|
+
|
|
77
|
+
Keyword arguments to `from_env()` win over the environment. Both clients
|
|
78
|
+
accept `http_client=` to reuse your own `httpx.Client` / `httpx.AsyncClient`.
|
|
79
|
+
|
|
80
|
+
## Stream LLM output to the browser
|
|
81
|
+
|
|
82
|
+
`stream_to_channel` sends a stream of text to a channel as it is produced, in
|
|
83
|
+
the format `useStream()` in [@hibira-io/react](https://github.com/hibira-io/react)
|
|
84
|
+
and [@hibira-io/vue](https://github.com/hibira-io/vue) puts back together.
|
|
85
|
+
Tokens are batched (about 10 events a second rather than one per token), each
|
|
86
|
+
event stays under the plan's message size, and the last event carries the
|
|
87
|
+
whole text when it fits, so people who open the page late catch up. With
|
|
88
|
+
channel history on (paid plans), `useStream(channel, { rewind: true })`
|
|
89
|
+
replays a stream after a reload.
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
from openai import OpenAI
|
|
93
|
+
import hibira
|
|
94
|
+
|
|
95
|
+
client = hibira.Client.from_env()
|
|
96
|
+
openai = OpenAI()
|
|
97
|
+
|
|
98
|
+
stream = openai.chat.completions.create(model="gpt-5-mini", messages=messages, stream=True)
|
|
99
|
+
result = hibira.stream_to_channel(client, f"private-conversation-{conversation_id}", stream, meta={"role": "assistant"})
|
|
100
|
+
save_message(conversation_id, result.text)
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
```jsx
|
|
104
|
+
// React
|
|
105
|
+
const { text, done } = useStream(`private-conversation-${conversationId}`);
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
`text_of` reads the text out of chunks from the common SDKs, so you can pass
|
|
109
|
+
their streams as they are:
|
|
110
|
+
|
|
111
|
+
| Source | Pass |
|
|
112
|
+
| --- | --- |
|
|
113
|
+
| OpenAI chat completions | `client.chat.completions.create(..., stream=True)` |
|
|
114
|
+
| OpenAI Responses | `client.responses.create(..., stream=True)` |
|
|
115
|
+
| Anthropic | `client.messages.create(..., stream=True)` (or the async client) |
|
|
116
|
+
| OpenAI Agents SDK | `Runner.run_streamed(agent, input).stream_events()` |
|
|
117
|
+
| LangGraph / LangChain | `graph.astream(input, stream_mode="messages")`, `llm.astream(...)` |
|
|
118
|
+
| Gemini (google-genai) | `client.models.generate_content_stream(...)` |
|
|
119
|
+
| Anything else | an iterable of `str` or `bytes`, or pass `pick=lambda chunk: ...` |
|
|
120
|
+
|
|
121
|
+
With asyncio, use `astream_to_channel` (it takes async or plain iterables,
|
|
122
|
+
and an `AsyncClient` or a `Client`):
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
async def answer(conversation_id: str, question: str) -> str:
|
|
126
|
+
stream = graph.astream({"messages": [("user", question)]}, stream_mode="messages")
|
|
127
|
+
result = await hibira.astream_to_channel(client, f"private-conversation-{conversation_id}", stream)
|
|
128
|
+
return result.text
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
To stream only one LangGraph node, filter with `pick`:
|
|
132
|
+
`pick=lambda c: hibira.text_of(c) if c[1].get("langgraph_node") == "agent" else ""`.
|
|
133
|
+
|
|
134
|
+
| Option | Default | |
|
|
135
|
+
| --- | --- | --- |
|
|
136
|
+
| `id` | random UUID | stream id, also in the result |
|
|
137
|
+
| `event` | `"ai-stream"` | event name |
|
|
138
|
+
| `interval` | `0.1` | seconds to gather tokens before sending them |
|
|
139
|
+
| `max_bytes` | `3500` | largest event payload (Free plans allow 4 KB per message) |
|
|
140
|
+
| `meta` | | JSON sent with the first event (model, message id, author) |
|
|
141
|
+
| `pick` | `text_of` | text of one chunk |
|
|
142
|
+
| `socket_id` | | leave out this connection (the sender's own tab) |
|
|
143
|
+
| `stop` | | a `threading.Event`; set it to end the stream with error `"aborted"` (sync only; cancel the task with asyncio) |
|
|
144
|
+
|
|
145
|
+
If the source raises, the final event carries the error (useStream shows it)
|
|
146
|
+
and the exception is raised again. Both return a `StreamResult(id, text, events)`.
|
|
147
|
+
|
|
148
|
+
## Authorize private and presence channels
|
|
149
|
+
|
|
150
|
+
```python
|
|
151
|
+
client.authenticate_channel("private-user-42", socket_id)
|
|
152
|
+
# {"auth": "key:signature"}
|
|
153
|
+
|
|
154
|
+
client.authenticate_channel("presence-room-7", socket_id, {"user_id": "42", "user_info": {"name": "Ann"}})
|
|
155
|
+
# {"auth": "...", "channel_data": "{\"user_id\":\"42\",...}"}
|
|
156
|
+
|
|
157
|
+
client.authenticate_user(socket_id, {"id": "42", "name": "Ann"}) # user sign-in
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
Return the dict as JSON from the endpoint pusher-js calls
|
|
161
|
+
(`channelAuthorization.endpoint`). It receives `socket_id` and
|
|
162
|
+
`channel_name` as form fields. These methods need no network and are plain
|
|
163
|
+
functions on `AsyncClient` too.
|
|
164
|
+
|
|
165
|
+
### FastAPI
|
|
166
|
+
|
|
167
|
+
```sh
|
|
168
|
+
pip install "hibira[fastapi]"
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
```python
|
|
172
|
+
from fastapi import Depends, FastAPI
|
|
173
|
+
from hibira import AsyncClient
|
|
174
|
+
from hibira.fastapi import auth_router, webhook
|
|
175
|
+
|
|
176
|
+
client = AsyncClient.from_env()
|
|
177
|
+
app = FastAPI()
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
async def authorize(request, channel: str):
|
|
181
|
+
user = await current_user(request)
|
|
182
|
+
if channel == f"private-user-{user.id}":
|
|
183
|
+
return True
|
|
184
|
+
if channel.startswith("presence-room-"):
|
|
185
|
+
return {"user_id": str(user.id), "user_info": {"name": user.name}}
|
|
186
|
+
return False
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
app.include_router(auth_router(client, authorize)) # POST /hibira/auth
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
@app.post("/hibira/webhook")
|
|
193
|
+
async def on_webhook(payload: dict = Depends(webhook(client))):
|
|
194
|
+
for event in payload["events"]:
|
|
195
|
+
...
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
`auth_router(client, authorize, user=...)` also answers user sign-in at
|
|
199
|
+
`/hibira/user-auth`. Django support is in
|
|
200
|
+
[django-hibira](https://github.com/hibira-io/django).
|
|
201
|
+
|
|
202
|
+
## Webhooks
|
|
203
|
+
|
|
204
|
+
```python
|
|
205
|
+
payload = client.verify_webhook(
|
|
206
|
+
request.headers.get("X-Pusher-Key"),
|
|
207
|
+
request.headers.get("X-Pusher-Signature"),
|
|
208
|
+
request.body, # the raw body, bytes or str
|
|
209
|
+
)
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
Raises `hibira.InvalidWebhook` when the key or signature does not match.
|
|
213
|
+
|
|
214
|
+
## Channels API
|
|
215
|
+
|
|
216
|
+
```python
|
|
217
|
+
client.trigger_batch([{"channel": "a", "name": "e", "data": {"x": 1}}])
|
|
218
|
+
client.channels(prefix="presence-", info="user_count")
|
|
219
|
+
client.channel_info("presence-room-7", info=["user_count", "subscription_count"])
|
|
220
|
+
client.users("presence-room-7")
|
|
221
|
+
client.terminate_user_connections("42")
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
`trigger` takes one channel or a list of up to 100. Data that is not a `str`
|
|
225
|
+
is sent as JSON. `socket_id=` leaves out the sender's own connection.
|
|
226
|
+
|
|
227
|
+
## Push notifications
|
|
228
|
+
|
|
229
|
+
Turn on Push for the app in the portal and set `HIBIRA_PUSH_INSTANCE_ID` and
|
|
230
|
+
`HIBIRA_PUSH_SECRET_KEY`. Bodies use the Beams format.
|
|
231
|
+
|
|
232
|
+
```python
|
|
233
|
+
client.push_to_interests(
|
|
234
|
+
["news"],
|
|
235
|
+
{
|
|
236
|
+
"web": {"notification": {"title": "New post", "deep_link": "https://example.com/p/1"}},
|
|
237
|
+
"fcm": {"notification": {"title": "New post"}},
|
|
238
|
+
"apns": {"aps": {"alert": {"title": "New post"}}},
|
|
239
|
+
},
|
|
240
|
+
)
|
|
241
|
+
client.push_to_users(["42"], {...})
|
|
242
|
+
client.push_token("42") # {"token": ...} for setUserId in the web, Android and iOS SDKs
|
|
243
|
+
client.delete_push_user("42")
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
## Approvals
|
|
247
|
+
|
|
248
|
+
Ask a person for a decision from a script, worker or agent. Hibira hosts the
|
|
249
|
+
answer page.
|
|
250
|
+
|
|
251
|
+
```python
|
|
252
|
+
approval = client.request_approval(
|
|
253
|
+
"Refund order #1042 for $89?",
|
|
254
|
+
details="Customer says the parcel never arrived.",
|
|
255
|
+
options=["Refund", "Decline"], # the first one approves
|
|
256
|
+
push_interests=["ops"], # or push_users=[...], or share approval["url"]
|
|
257
|
+
channel="private-hibira-approvals.ops", # shows in the @hibira-io/approvals inbox
|
|
258
|
+
)
|
|
259
|
+
result = client.wait_for_approval(approval["approval_id"], timeout=3600)
|
|
260
|
+
if result["status"] == "approved":
|
|
261
|
+
refund(1042)
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
`status` is `pending`, `approved`, `rejected` or `expired`. `get_approval(id, wait=25)`
|
|
265
|
+
reads it once, waiting up to 25 seconds for an answer.
|
|
266
|
+
|
|
267
|
+
## Errors
|
|
268
|
+
|
|
269
|
+
Every error is a `hibira.HibiraError`. HTTP errors are `hibira.HTTPError`
|
|
270
|
+
(`status`, `message`, `body`), with subclasses `AuthenticationError` (401,
|
|
271
|
+
403), `NotFound` (404), `PayloadTooLarge` (413, the event is over the plan's
|
|
272
|
+
message size) and `RateLimited` (429). Network failures (DNS, connect,
|
|
273
|
+
TLS, proxy, timeout) raise `hibira.ConnectionError`. Missing settings raise
|
|
274
|
+
`ConfigError`.
|
|
275
|
+
|
|
276
|
+
## Development
|
|
277
|
+
|
|
278
|
+
```sh
|
|
279
|
+
python -m venv .venv && .venv/bin/pip install -e . pytest fastapi ruff mypy
|
|
280
|
+
.venv/bin/pytest
|
|
281
|
+
.venv/bin/ruff check . && .venv/bin/mypy
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
`tests/test_e2e.py` runs against a real server when `HIBIRA_E2E=1` and the
|
|
285
|
+
`HIBIRA_*` settings point at it (it needs `pip install websockets`).
|
|
286
|
+
|
|
287
|
+
## 中文摘要
|
|
288
|
+
|
|
289
|
+
`hibira` 是 Hibira 的 Python 伺服器端套件(Python 3.9 以上,同步與 asyncio 兩種
|
|
290
|
+
client):發送事件、私人 / presence 頻道授權、驗證 webhook、推播通知、人工核准,
|
|
291
|
+
以及用 `stream_to_channel` 把 LLM 的輸出即時串流到瀏覽器(React / Vue 的
|
|
292
|
+
`useStream()` 直接接收)。支援 OpenAI、Anthropic、OpenAI Agents SDK、LangGraph、
|
|
293
|
+
Gemini 的串流格式,並附 FastAPI 授權路由與 webhook 驗證。
|
|
294
|
+
|
|
295
|
+
## License
|
|
296
|
+
|
|
297
|
+
MIT
|
hibira-0.1.0/README.md
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
# hibira
|
|
2
|
+
|
|
3
|
+
Python server library for [Hibira](https://hibira.io), hosted realtime that
|
|
4
|
+
speaks the Pusher Channels protocol. Publish events, authorize private and
|
|
5
|
+
presence channels, verify webhooks, send push notifications, ask a person for
|
|
6
|
+
an approval, and stream LLM output to the browser as it is written.
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
pip install hibira
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Python 3.9+, one dependency ([httpx](https://www.python-httpx.org/)). Both a
|
|
13
|
+
regular and an asyncio client. pusher-js, Laravel Echo and the
|
|
14
|
+
`@hibira-io/*` front-end packages connect to Hibira unchanged.
|
|
15
|
+
|
|
16
|
+
## Set up
|
|
17
|
+
|
|
18
|
+
Create an app at [hibira.io/portal](https://hibira.io/portal) (the free plan
|
|
19
|
+
needs no card) and put its keys in the environment:
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
HIBIRA_APP_ID=...
|
|
23
|
+
HIBIRA_APP_KEY=...
|
|
24
|
+
HIBIRA_APP_SECRET=...
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
import hibira
|
|
29
|
+
|
|
30
|
+
client = hibira.Client.from_env() # or hibira.Client(app_id, key, secret)
|
|
31
|
+
client.trigger("orders", "created", {"id": 1042})
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
async with hibira.AsyncClient.from_env() as client:
|
|
36
|
+
await client.trigger(["orders", "dashboard"], "created", {"id": 1042})
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
| Setting | Environment | Default |
|
|
40
|
+
| --- | --- | --- |
|
|
41
|
+
| `app_id`, `key`, `secret` | `HIBIRA_APP_ID`, `HIBIRA_APP_KEY`, `HIBIRA_APP_SECRET` | |
|
|
42
|
+
| `host` | `HIBIRA_HOST` | `ws.hibira.io` (or the host shown on your app page) |
|
|
43
|
+
| `port`, `use_tls` | `HIBIRA_PORT`, `HIBIRA_USE_TLS` | `443`, `True` |
|
|
44
|
+
| `push_instance_id`, `push_secret_key` | `HIBIRA_PUSH_INSTANCE_ID`, `HIBIRA_PUSH_SECRET_KEY` | |
|
|
45
|
+
| `push_endpoint` | `HIBIRA_PUSH_ENDPOINT` | `https://<host>` |
|
|
46
|
+
| `timeout` | | `10.0` seconds |
|
|
47
|
+
|
|
48
|
+
Keyword arguments to `from_env()` win over the environment. Both clients
|
|
49
|
+
accept `http_client=` to reuse your own `httpx.Client` / `httpx.AsyncClient`.
|
|
50
|
+
|
|
51
|
+
## Stream LLM output to the browser
|
|
52
|
+
|
|
53
|
+
`stream_to_channel` sends a stream of text to a channel as it is produced, in
|
|
54
|
+
the format `useStream()` in [@hibira-io/react](https://github.com/hibira-io/react)
|
|
55
|
+
and [@hibira-io/vue](https://github.com/hibira-io/vue) puts back together.
|
|
56
|
+
Tokens are batched (about 10 events a second rather than one per token), each
|
|
57
|
+
event stays under the plan's message size, and the last event carries the
|
|
58
|
+
whole text when it fits, so people who open the page late catch up. With
|
|
59
|
+
channel history on (paid plans), `useStream(channel, { rewind: true })`
|
|
60
|
+
replays a stream after a reload.
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
from openai import OpenAI
|
|
64
|
+
import hibira
|
|
65
|
+
|
|
66
|
+
client = hibira.Client.from_env()
|
|
67
|
+
openai = OpenAI()
|
|
68
|
+
|
|
69
|
+
stream = openai.chat.completions.create(model="gpt-5-mini", messages=messages, stream=True)
|
|
70
|
+
result = hibira.stream_to_channel(client, f"private-conversation-{conversation_id}", stream, meta={"role": "assistant"})
|
|
71
|
+
save_message(conversation_id, result.text)
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
```jsx
|
|
75
|
+
// React
|
|
76
|
+
const { text, done } = useStream(`private-conversation-${conversationId}`);
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
`text_of` reads the text out of chunks from the common SDKs, so you can pass
|
|
80
|
+
their streams as they are:
|
|
81
|
+
|
|
82
|
+
| Source | Pass |
|
|
83
|
+
| --- | --- |
|
|
84
|
+
| OpenAI chat completions | `client.chat.completions.create(..., stream=True)` |
|
|
85
|
+
| OpenAI Responses | `client.responses.create(..., stream=True)` |
|
|
86
|
+
| Anthropic | `client.messages.create(..., stream=True)` (or the async client) |
|
|
87
|
+
| OpenAI Agents SDK | `Runner.run_streamed(agent, input).stream_events()` |
|
|
88
|
+
| LangGraph / LangChain | `graph.astream(input, stream_mode="messages")`, `llm.astream(...)` |
|
|
89
|
+
| Gemini (google-genai) | `client.models.generate_content_stream(...)` |
|
|
90
|
+
| Anything else | an iterable of `str` or `bytes`, or pass `pick=lambda chunk: ...` |
|
|
91
|
+
|
|
92
|
+
With asyncio, use `astream_to_channel` (it takes async or plain iterables,
|
|
93
|
+
and an `AsyncClient` or a `Client`):
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
async def answer(conversation_id: str, question: str) -> str:
|
|
97
|
+
stream = graph.astream({"messages": [("user", question)]}, stream_mode="messages")
|
|
98
|
+
result = await hibira.astream_to_channel(client, f"private-conversation-{conversation_id}", stream)
|
|
99
|
+
return result.text
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
To stream only one LangGraph node, filter with `pick`:
|
|
103
|
+
`pick=lambda c: hibira.text_of(c) if c[1].get("langgraph_node") == "agent" else ""`.
|
|
104
|
+
|
|
105
|
+
| Option | Default | |
|
|
106
|
+
| --- | --- | --- |
|
|
107
|
+
| `id` | random UUID | stream id, also in the result |
|
|
108
|
+
| `event` | `"ai-stream"` | event name |
|
|
109
|
+
| `interval` | `0.1` | seconds to gather tokens before sending them |
|
|
110
|
+
| `max_bytes` | `3500` | largest event payload (Free plans allow 4 KB per message) |
|
|
111
|
+
| `meta` | | JSON sent with the first event (model, message id, author) |
|
|
112
|
+
| `pick` | `text_of` | text of one chunk |
|
|
113
|
+
| `socket_id` | | leave out this connection (the sender's own tab) |
|
|
114
|
+
| `stop` | | a `threading.Event`; set it to end the stream with error `"aborted"` (sync only; cancel the task with asyncio) |
|
|
115
|
+
|
|
116
|
+
If the source raises, the final event carries the error (useStream shows it)
|
|
117
|
+
and the exception is raised again. Both return a `StreamResult(id, text, events)`.
|
|
118
|
+
|
|
119
|
+
## Authorize private and presence channels
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
client.authenticate_channel("private-user-42", socket_id)
|
|
123
|
+
# {"auth": "key:signature"}
|
|
124
|
+
|
|
125
|
+
client.authenticate_channel("presence-room-7", socket_id, {"user_id": "42", "user_info": {"name": "Ann"}})
|
|
126
|
+
# {"auth": "...", "channel_data": "{\"user_id\":\"42\",...}"}
|
|
127
|
+
|
|
128
|
+
client.authenticate_user(socket_id, {"id": "42", "name": "Ann"}) # user sign-in
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
Return the dict as JSON from the endpoint pusher-js calls
|
|
132
|
+
(`channelAuthorization.endpoint`). It receives `socket_id` and
|
|
133
|
+
`channel_name` as form fields. These methods need no network and are plain
|
|
134
|
+
functions on `AsyncClient` too.
|
|
135
|
+
|
|
136
|
+
### FastAPI
|
|
137
|
+
|
|
138
|
+
```sh
|
|
139
|
+
pip install "hibira[fastapi]"
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
from fastapi import Depends, FastAPI
|
|
144
|
+
from hibira import AsyncClient
|
|
145
|
+
from hibira.fastapi import auth_router, webhook
|
|
146
|
+
|
|
147
|
+
client = AsyncClient.from_env()
|
|
148
|
+
app = FastAPI()
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
async def authorize(request, channel: str):
|
|
152
|
+
user = await current_user(request)
|
|
153
|
+
if channel == f"private-user-{user.id}":
|
|
154
|
+
return True
|
|
155
|
+
if channel.startswith("presence-room-"):
|
|
156
|
+
return {"user_id": str(user.id), "user_info": {"name": user.name}}
|
|
157
|
+
return False
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
app.include_router(auth_router(client, authorize)) # POST /hibira/auth
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@app.post("/hibira/webhook")
|
|
164
|
+
async def on_webhook(payload: dict = Depends(webhook(client))):
|
|
165
|
+
for event in payload["events"]:
|
|
166
|
+
...
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
`auth_router(client, authorize, user=...)` also answers user sign-in at
|
|
170
|
+
`/hibira/user-auth`. Django support is in
|
|
171
|
+
[django-hibira](https://github.com/hibira-io/django).
|
|
172
|
+
|
|
173
|
+
## Webhooks
|
|
174
|
+
|
|
175
|
+
```python
|
|
176
|
+
payload = client.verify_webhook(
|
|
177
|
+
request.headers.get("X-Pusher-Key"),
|
|
178
|
+
request.headers.get("X-Pusher-Signature"),
|
|
179
|
+
request.body, # the raw body, bytes or str
|
|
180
|
+
)
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Raises `hibira.InvalidWebhook` when the key or signature does not match.
|
|
184
|
+
|
|
185
|
+
## Channels API
|
|
186
|
+
|
|
187
|
+
```python
|
|
188
|
+
client.trigger_batch([{"channel": "a", "name": "e", "data": {"x": 1}}])
|
|
189
|
+
client.channels(prefix="presence-", info="user_count")
|
|
190
|
+
client.channel_info("presence-room-7", info=["user_count", "subscription_count"])
|
|
191
|
+
client.users("presence-room-7")
|
|
192
|
+
client.terminate_user_connections("42")
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
`trigger` takes one channel or a list of up to 100. Data that is not a `str`
|
|
196
|
+
is sent as JSON. `socket_id=` leaves out the sender's own connection.
|
|
197
|
+
|
|
198
|
+
## Push notifications
|
|
199
|
+
|
|
200
|
+
Turn on Push for the app in the portal and set `HIBIRA_PUSH_INSTANCE_ID` and
|
|
201
|
+
`HIBIRA_PUSH_SECRET_KEY`. Bodies use the Beams format.
|
|
202
|
+
|
|
203
|
+
```python
|
|
204
|
+
client.push_to_interests(
|
|
205
|
+
["news"],
|
|
206
|
+
{
|
|
207
|
+
"web": {"notification": {"title": "New post", "deep_link": "https://example.com/p/1"}},
|
|
208
|
+
"fcm": {"notification": {"title": "New post"}},
|
|
209
|
+
"apns": {"aps": {"alert": {"title": "New post"}}},
|
|
210
|
+
},
|
|
211
|
+
)
|
|
212
|
+
client.push_to_users(["42"], {...})
|
|
213
|
+
client.push_token("42") # {"token": ...} for setUserId in the web, Android and iOS SDKs
|
|
214
|
+
client.delete_push_user("42")
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
## Approvals
|
|
218
|
+
|
|
219
|
+
Ask a person for a decision from a script, worker or agent. Hibira hosts the
|
|
220
|
+
answer page.
|
|
221
|
+
|
|
222
|
+
```python
|
|
223
|
+
approval = client.request_approval(
|
|
224
|
+
"Refund order #1042 for $89?",
|
|
225
|
+
details="Customer says the parcel never arrived.",
|
|
226
|
+
options=["Refund", "Decline"], # the first one approves
|
|
227
|
+
push_interests=["ops"], # or push_users=[...], or share approval["url"]
|
|
228
|
+
channel="private-hibira-approvals.ops", # shows in the @hibira-io/approvals inbox
|
|
229
|
+
)
|
|
230
|
+
result = client.wait_for_approval(approval["approval_id"], timeout=3600)
|
|
231
|
+
if result["status"] == "approved":
|
|
232
|
+
refund(1042)
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
`status` is `pending`, `approved`, `rejected` or `expired`. `get_approval(id, wait=25)`
|
|
236
|
+
reads it once, waiting up to 25 seconds for an answer.
|
|
237
|
+
|
|
238
|
+
## Errors
|
|
239
|
+
|
|
240
|
+
Every error is a `hibira.HibiraError`. HTTP errors are `hibira.HTTPError`
|
|
241
|
+
(`status`, `message`, `body`), with subclasses `AuthenticationError` (401,
|
|
242
|
+
403), `NotFound` (404), `PayloadTooLarge` (413, the event is over the plan's
|
|
243
|
+
message size) and `RateLimited` (429). Network failures (DNS, connect,
|
|
244
|
+
TLS, proxy, timeout) raise `hibira.ConnectionError`. Missing settings raise
|
|
245
|
+
`ConfigError`.
|
|
246
|
+
|
|
247
|
+
## Development
|
|
248
|
+
|
|
249
|
+
```sh
|
|
250
|
+
python -m venv .venv && .venv/bin/pip install -e . pytest fastapi ruff mypy
|
|
251
|
+
.venv/bin/pytest
|
|
252
|
+
.venv/bin/ruff check . && .venv/bin/mypy
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
`tests/test_e2e.py` runs against a real server when `HIBIRA_E2E=1` and the
|
|
256
|
+
`HIBIRA_*` settings point at it (it needs `pip install websockets`).
|
|
257
|
+
|
|
258
|
+
## 中文摘要
|
|
259
|
+
|
|
260
|
+
`hibira` 是 Hibira 的 Python 伺服器端套件(Python 3.9 以上,同步與 asyncio 兩種
|
|
261
|
+
client):發送事件、私人 / presence 頻道授權、驗證 webhook、推播通知、人工核准,
|
|
262
|
+
以及用 `stream_to_channel` 把 LLM 的輸出即時串流到瀏覽器(React / Vue 的
|
|
263
|
+
`useStream()` 直接接收)。支援 OpenAI、Anthropic、OpenAI Agents SDK、LangGraph、
|
|
264
|
+
Gemini 的串流格式,並附 FastAPI 授權路由與 webhook 驗證。
|
|
265
|
+
|
|
266
|
+
## License
|
|
267
|
+
|
|
268
|
+
MIT
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.24"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "hibira"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Hibira for Python: realtime events, channel auth, webhooks, push notifications, approvals and LLM streaming (Pusher-compatible)"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.9"
|
|
13
|
+
authors = [{ name = "Hibira", email = "dev@hibira.io" }]
|
|
14
|
+
keywords = ["hibira", "pusher", "websocket", "realtime", "channels", "push notifications", "llm", "streaming", "langgraph", "fastapi"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Framework :: AsyncIO",
|
|
18
|
+
"Framework :: FastAPI",
|
|
19
|
+
"Intended Audience :: Developers",
|
|
20
|
+
"Operating System :: OS Independent",
|
|
21
|
+
"Programming Language :: Python :: 3",
|
|
22
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
23
|
+
"Topic :: Internet :: WWW/HTTP",
|
|
24
|
+
"Topic :: Software Development :: Libraries",
|
|
25
|
+
"Typing :: Typed",
|
|
26
|
+
]
|
|
27
|
+
dependencies = ["httpx>=0.24,<1"]
|
|
28
|
+
|
|
29
|
+
[project.optional-dependencies]
|
|
30
|
+
fastapi = ["fastapi>=0.100"]
|
|
31
|
+
|
|
32
|
+
[project.urls]
|
|
33
|
+
Homepage = "https://hibira.io"
|
|
34
|
+
Documentation = "https://github.com/hibira-io/python#readme"
|
|
35
|
+
Source = "https://github.com/hibira-io/python"
|
|
36
|
+
Changelog = "https://github.com/hibira-io/python/blob/main/CHANGELOG.md"
|
|
37
|
+
Issues = "https://github.com/hibira-io/python/issues"
|
|
38
|
+
|
|
39
|
+
[dependency-groups]
|
|
40
|
+
dev = ["pytest>=8", "fastapi>=0.100", "ruff>=0.6", "mypy>=1.10"]
|
|
41
|
+
|
|
42
|
+
[tool.hatch.version]
|
|
43
|
+
path = "src/hibira/_version.py"
|
|
44
|
+
|
|
45
|
+
[tool.hatch.build.targets.wheel]
|
|
46
|
+
packages = ["src/hibira"]
|
|
47
|
+
|
|
48
|
+
[tool.hatch.build.targets.sdist]
|
|
49
|
+
include = ["src", "tests", "README.md", "CHANGELOG.md", "LICENSE"]
|
|
50
|
+
|
|
51
|
+
[tool.pytest.ini_options]
|
|
52
|
+
testpaths = ["tests"]
|
|
53
|
+
|
|
54
|
+
[tool.ruff]
|
|
55
|
+
line-length = 120
|
|
56
|
+
target-version = "py39"
|
|
57
|
+
|
|
58
|
+
[tool.ruff.lint]
|
|
59
|
+
select = ["E", "F", "W", "I", "B", "UP", "BLE"]
|
|
60
|
+
ignore = ["UP006", "UP007", "UP035", "UP045"]
|
|
61
|
+
|
|
62
|
+
[tool.ruff.lint.flake8-bugbear]
|
|
63
|
+
extend-immutable-calls = ["fastapi.Depends"]
|
|
64
|
+
|
|
65
|
+
[tool.ruff.lint.per-file-ignores]
|
|
66
|
+
"tests/*" = ["B008"]
|
|
67
|
+
|
|
68
|
+
[tool.mypy]
|
|
69
|
+
python_version = "3.10"
|
|
70
|
+
strict = true
|
|
71
|
+
files = ["src/hibira"]
|