hilus 0.2.0__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.
Files changed (95) hide show
  1. hilus/LICENSE +202 -0
  2. hilus/README.md +300 -0
  3. hilus/__init__.py +72 -0
  4. hilus/_client_support.py +55 -0
  5. hilus/_registry.py +53 -0
  6. hilus/_stt_mixin.py +146 -0
  7. hilus/api_url.py +106 -0
  8. hilus/audio.py +432 -0
  9. hilus/cli/__init__.py +0 -0
  10. hilus/cli/_generated_runtime.py +1906 -0
  11. hilus/cli/api_client.py +846 -0
  12. hilus/cli/commands/__init__.py +0 -0
  13. hilus/cli/commands/checkout.py +150 -0
  14. hilus/cli/commands/clone.py +86 -0
  15. hilus/cli/commands/docs_cmd.py +79 -0
  16. hilus/cli/commands/generated/__init__.py +42 -0
  17. hilus/cli/commands/generated/browser.py +2269 -0
  18. hilus/cli/commands/generated/connectorgateway.py +119 -0
  19. hilus/cli/commands/generated/google.py +365 -0
  20. hilus/cli/commands/generated/platform.py +17963 -0
  21. hilus/cli/commands/generated/slack.py +151 -0
  22. hilus/cli/commands/generated/stripe.py +336 -0
  23. hilus/cli/commands/init.py +190 -0
  24. hilus/cli/commands/login.py +77 -0
  25. hilus/cli/commands/mount_cmd.py +449 -0
  26. hilus/cli/commands/new.py +175 -0
  27. hilus/cli/commands/sdk_cmd.py +283 -0
  28. hilus/cli/commands/switch.py +139 -0
  29. hilus/cli/git_credential.py +97 -0
  30. hilus/cli/main.py +874 -0
  31. hilus/cli/mount.py +3446 -0
  32. hilus/cli/paths.py +210 -0
  33. hilus/cli/utils.py +645 -0
  34. hilus/errors.py +231 -0
  35. hilus/examples/async_job.py +41 -0
  36. hilus/examples/known_voices.py +59 -0
  37. hilus/examples/quickstart.py +43 -0
  38. hilus/examples/repo_edit_and_test.py +43 -0
  39. hilus/examples/streaming_events.py +31 -0
  40. hilus/generated/__init__.py +28 -0
  41. hilus/generated/browser.py +2200 -0
  42. hilus/generated/google.py +519 -0
  43. hilus/generated/models.py +15463 -0
  44. hilus/generated/platform.py +22124 -0
  45. hilus/generated/slack.py +332 -0
  46. hilus/generated/stripe.py +273 -0
  47. hilus/hql/__init__.py +18 -0
  48. hilus/hql/ast.py +953 -0
  49. hilus/hql/parser.py +1960 -0
  50. hilus/log.py +514 -0
  51. hilus/oauth.py +386 -0
  52. hilus/py.typed +0 -0
  53. hilus/service_client.py +785 -0
  54. hilus/speech/__init__.py +163 -0
  55. hilus/speech/__main__.py +5 -0
  56. hilus/speech/bench/__init__.py +1 -0
  57. hilus/speech/bench/__main__.py +5 -0
  58. hilus/speech/bench/cli.py +304 -0
  59. hilus/speech/bench/client.py +116 -0
  60. hilus/speech/bench/dataset.py +129 -0
  61. hilus/speech/bench/judge.py +57 -0
  62. hilus/speech/bench/providers/__init__.py +121 -0
  63. hilus/speech/bench/providers/_common.py +52 -0
  64. hilus/speech/bench/providers/_socket.py +112 -0
  65. hilus/speech/bench/providers/assemblyai.py +194 -0
  66. hilus/speech/bench/providers/cartesia.py +88 -0
  67. hilus/speech/bench/providers/deepgram.py +191 -0
  68. hilus/speech/bench/providers/elevenlabs.py +244 -0
  69. hilus/speech/bench/providers/hilus.py +98 -0
  70. hilus/speech/bench/providers/speechmatics.py +149 -0
  71. hilus/speech/bench/report.py +54 -0
  72. hilus/speech/bench/run.py +107 -0
  73. hilus/speech/bench/scoring.py +187 -0
  74. hilus/speech/bench/submit.py +109 -0
  75. hilus/speech/compare.py +695 -0
  76. hilus/speech/diarization_evaluation.py +246 -0
  77. hilus/speech/formats.py +202 -0
  78. hilus/speech/hypothesis.py +67 -0
  79. hilus/speech/inverse_normalize.py +379 -0
  80. hilus/speech/labels.py +316 -0
  81. hilus/speech/lattice.py +251 -0
  82. hilus/speech/metrics.py +1439 -0
  83. hilus/speech/scorecard.py +325 -0
  84. hilus/speech/severity.py +93 -0
  85. hilus/speech/streaming.py +523 -0
  86. hilus/speech/submission.py +292 -0
  87. hilus/speech/tasks.py +116 -0
  88. hilus/speech/text.py +490 -0
  89. hilus/stt.py +583 -0
  90. hilus/ws.py +306 -0
  91. hilus-0.2.0.dist-info/METADATA +348 -0
  92. hilus-0.2.0.dist-info/RECORD +95 -0
  93. hilus-0.2.0.dist-info/WHEEL +5 -0
  94. hilus-0.2.0.dist-info/entry_points.txt +3 -0
  95. hilus-0.2.0.dist-info/top_level.txt +1 -0
hilus/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
hilus/README.md ADDED
@@ -0,0 +1,300 @@
1
+ # hilus
2
+
3
+ **The Python SDK and command-line tool for [Hilus](https://hilus.ai).**
4
+
5
+ Hilus runs AI agents that answer an organization's calls, web chat, email and
6
+ text messages, and act in the systems the organization already uses. This
7
+ package is how developers work with an organization on Hilus from code and
8
+ from the terminal:
9
+
10
+ - **Read and query its data:** conversations, calls, messages and every other
11
+ record, with typed models and HQL, a SQL-like query language.
12
+ - **Configure its agents:** agents, workflows, documents and forms are
13
+ versioned on branches and promoted to live through reviewed changesets.
14
+ - **Follow what happens live:** stream a call's events or a conversation as
15
+ it unfolds.
16
+ - **Test agents before they go live:** simulate whole conversations, replay a
17
+ reply, run saved tests.
18
+ - **Work on the organization's own code:** every organization has a git
19
+ repository; clone it, change it on a branch, run its tests, ship it with a
20
+ changeset.
21
+
22
+ One install gives you both:
23
+
24
+ - **`hilus` (Python):** typed clients generated from the API itself, one
25
+ method per operation with documented parameters, pydantic responses,
26
+ streaming, retries and typed errors.
27
+ - **`hilus` (CLI):** every API operation as a command, plus sign-in, `hilus
28
+ clone` and a live view of the organization's configuration as files.
29
+
30
+ ```bash
31
+ pip install hilus
32
+ ```
33
+
34
+ Python 3.10 or newer. Full documentation, every operation and guide:
35
+ <https://api.hilus.ai/Platform/docs>.
36
+
37
+ ## Sign in
38
+
39
+ ```bash
40
+ hilus login # opens the browser; sign in, or create an account there
41
+ hilus context whoami
42
+ ```
43
+
44
+ `hilus login` signs you in through the browser, the way other CLIs do: no
45
+ key to copy. It stores a refresh token owner-only in
46
+ `~/.hilus/credentials.yaml`, and the CLI and the SDK renew the short-lived
47
+ access key themselves from then on. `hilus logout` revokes it. `hilus init`
48
+ does the same sign-in and also asks for your default organization and
49
+ branch. On a machine without a browser, `hilus login --no-browser` prints
50
+ the URL to open on another device; after you sign in there, the page shows a
51
+ code to paste back into the terminal.
52
+
53
+ The SDK uses that sign-in with no configuration: `PlatformClient()`.
54
+
55
+ **CI, servers and other automation** use an API key instead: create one on
56
+ the dashboard's Developer page, <https://app.hilus.ai/settings/developer>,
57
+ and set `HILUS_API_TOKEN` and `HILUS_ORG` (and `HILUS_API_URL` for a
58
+ non-production deployment), or store it with `echo "$KEY" | hilus init
59
+ --token -`. Never put a key on a command line. No account yet? Create one at
60
+ <https://app.hilus.ai/signup>.
61
+
62
+ If a call fails because you are not signed in, or because the credential was
63
+ refused (expired, revoked), the error says which and what to do.
64
+
65
+ An organization is a tenant: every call acts in one, sent as the
66
+ `X-Hilus-Schema` header. A key may be allowed several; pass
67
+ `organization=` (SDK) or `hilus context switch "<Org>"` (CLI) to choose.
68
+
69
+ ## First call (SDK)
70
+
71
+ ```python
72
+ from hilus import PlatformClient
73
+
74
+ client = PlatformClient() # from the environment, else from `hilus init`
75
+ # or, explicitly: PlatformClient(base="https://api.hilus.ai", auth_token="<api key>", organization="<org id>")
76
+
77
+ me = client.admin.whoami() # WhoamiUser
78
+ rows = client.query.run_hql(hql="Call | status = 'active' | limit 5").rows
79
+ agents = client.entities.list("Agent", limit=5) # EntityListResponse
80
+ ```
81
+
82
+ Precedence is explicit argument, then environment, then the stored sign-in.
83
+ An explicit token is never paired with the stored organization, and a token
84
+ stored for one API URL is refused for another: a staging key cannot reach
85
+ production by accident.
86
+
87
+ ## Errors, retries and timeouts
88
+
89
+ Every failed call raises a typed exception with the HTTP context:
90
+
91
+ ```python
92
+ from hilus import AccessDeniedError, AuthError, HilusApiError, RateLimitError, TransportError
93
+
94
+ try:
95
+ client.entities.get("Agent", "missing")
96
+ except AuthError: # 401, or no token at all
97
+ ...
98
+ except AccessDeniedError as e: # 403; e.denial_reason when a gateway refused
99
+ ...
100
+ except RateLimitError as e: # 429 after the retries; e.retry_after in seconds
101
+ ...
102
+ except TransportError as e: # no HTTP answer: DNS, connection, TLS, timeout (e.__cause__ is the requests error)
103
+ ...
104
+ except HilusApiError as e: # anything else: e.status_code, e.body, e.request_id
105
+ print(e.status_code, e.body, e.request_id)
106
+ ```
107
+
108
+ Idempotent requests (GET, or any call with `idempotent=True` on
109
+ `_request`) are retried up to `max_retries=3` times on 429/502/503/504 and
110
+ on transport failures, honouring `Retry-After`, with exponential backoff
111
+ capped at 30 s. Writes are never retried.
112
+
113
+ The client's `timeout=` (60 s) is the read timeout of a request; every
114
+ method also takes `request_timeout=`. Routes the server allows longer (a
115
+ test run, a workspace command) wait at least the server's own limit, so
116
+ `client.repos.repo_test(...)` does not time out on the client side.
117
+
118
+ ## Streaming
119
+
120
+ Server-Sent Events routes are iterators; WebSocket routes return a
121
+ `FrameStream` to iterate and `send` on:
122
+
123
+ ```python
124
+ from hilus import BrowserClient, PlatformClient, StreamTimeout
125
+ from hilus.generated.models import WSCallEventsConfigEvent
126
+
127
+ for entry in BrowserClient().stream_actions(session_id, since=0): # SSE: ActionLogEntry frames
128
+ print(entry.id, entry.type)
129
+
130
+ client = PlatformClient(ws_timeout=120) # idle limit; None waits for the server
131
+ with client.calls.call_events_stream(call_id) as frames:
132
+ frames.send(WSCallEventsConfigEvent(type="config"))
133
+ for frame in frames: # typed by the frame's `type`
134
+ print(frame.type)
135
+ print(frames.close_code, frames.close_reason) # set when the server closed
136
+ ```
137
+
138
+ A dropped GET stream is reopened once from the last event id; a frame type
139
+ newer than this client is yielded as a dict instead of ending the stream;
140
+ idle past `ws_timeout` raises `StreamTimeout`.
141
+
142
+ ## Live transcription
143
+
144
+ `client.stt.listen` streams audio to the live transcription socket and
145
+ yields what was said, and by whom, as it is said. It sends the audio as
146
+ binary frames at the pace it was spoken, sends `finalize` at the end, and
147
+ stops after `closed`:
148
+
149
+ ```python
150
+ from hilus import PlatformClient
151
+ from hilus.audio import Audio
152
+ from hilus.stt import Identity, KnownPerson, Transcript
153
+
154
+ client = PlatformClient()
155
+ ann = KnownPerson(id="u-17", name="Ann", voiceprints=[held_print]) # a voiceprint you kept from an earlier stream
156
+
157
+ with client.stt.listen(Audio.wav("call.wav"), known=[ann], voiceprints="data") as live:
158
+ for event in live:
159
+ match event:
160
+ case Transcript(is_final=True):
161
+ print(f"speaker {event.speaker}: {event.text}")
162
+ case Identity(status="identified"):
163
+ print(f"speaker {event.speaker} is {event.known_id}")
164
+ # live.add_known(...), live.remove_known(...), live.update(keyterms=[...]) change it while it runs
165
+ new_prints = live.voiceprints # speaker -> voiceprint, to keep
166
+ ```
167
+
168
+ - Audio: `Audio.wav(path_or_file)` (rate, width and channels from the
169
+ header), `Audio.pcm(bytes, sample_rate)` (what `tts.speak_stream(format="pcm")`
170
+ returns), `Audio.mulaw` / `Audio.alaw` for phone audio, `Audio.numpy(array,
171
+ sample_rate)`, `Audio.join(parts, gap=)`; or an iterable of byte chunks
172
+ (a microphone, a phone line), sent as they arrive. `realtime=False` sends
173
+ a recording as fast as the socket takes it.
174
+ - Opus, to save bandwidth (`pip install "hilus[opus]"`):
175
+ `client.stt.listen(Audio.wav("call.wav"), encoding="opus", bitrate=24000)`
176
+ sends 20 ms Opus packets, about 134 kB a minute of speech against 1.92 MB
177
+ of 16 kHz PCM; `Audio.opus_packets(packets)` sends packets you already
178
+ have as they are. PCM stays the default: Opus is lossy.
179
+ - `async with client.stt.alisten(...) as live: async for event in live: ...`
180
+ is the same for asyncio, and takes async iterables.
181
+ - A refused config raises `hilus.StreamError` on entering, before any audio
182
+ is sent; an `error` frame mid-stream is yielded; a stream that fails raises
183
+ `StreamError`. The low-level socket is still `client.stt.stream()`
184
+ (`FrameStream.send_bytes` sends binary frames).
185
+
186
+ `examples/known_voices.py` is the whole round trip: two of the platform's
187
+ voices make a first call, which collects a voiceprint, and a second, which
188
+ recognizes that person by your own id.
189
+
190
+ ## Background work
191
+
192
+ Routes that run in the background by default (`clinical.clinical_consult`,
193
+ `lab.simulate`, ...) answer `202` while the server works. With the default
194
+ `wait=True` the method polls until the result is ready (`wait_timeout`
195
+ seconds at most, `poll_interval` seconds at first, backing off to five);
196
+ with `wait=False` it returns a `PendingExecution` to poll yourself:
197
+
198
+ ```python
199
+ pending = client.clinical.clinical_consult(case_synopsis="...", species="dog", wait=False)
200
+ outcome = client.jobs.poll_async(pending.async_id) # {"status": "pending" | "completed" | "failed", "result": ...}
201
+ ```
202
+
203
+ ## Logging from your code
204
+
205
+ `hilus.log.get_logger` gives you a standard Python logger whose lines go to
206
+ Hilus, where your organization's members read them as `Log` (the
207
+ dashboard's Logs page, or `hilus query run-hql --hql "Log | ..."`):
208
+
209
+ ```python
210
+ from hilus.log import get_logger
211
+
212
+ log = get_logger("acme.sync") # any dotted name not under `hilus`
213
+ log.info("synced %s visits", 12, extra={"clinic": "north", "rows": 12})
214
+ try:
215
+ sync()
216
+ except Exception:
217
+ log.exception("sync failed") # the traceback is part of the message
218
+ ```
219
+
220
+ Everything in `extra=` becomes the line's `data` (strings, numbers and
221
+ bools; anything else is sent as its `str`), so any key works, `message`
222
+ included. The loggers sit in a tree of their own: your own `logging`
223
+ configuration neither repeats nor stops their lines.
224
+
225
+ Lines are queued and sent in the background with the client's usual
226
+ credentials, at most 500 per request or after a second; `log.info` never
227
+ waits on the network and never raises. A busy or unreachable server is
228
+ retried; up to 10,000 waiting lines are kept, and if older ones had to be
229
+ dropped the next batch says how many. Lines still queued are sent at exit
230
+ (waiting five seconds at most); call `hilus.log.flush()` yourself before
231
+ `os._exit` or at the end of a short job. Set `HILUS_LOG_ECHO=1` to also
232
+ print every line to stderr. To send a standard-library logger's lines too,
233
+ attach a `hilus.log.HilusHandler()` to it.
234
+
235
+ ## Examples
236
+
237
+ The package ships runnable examples in `hilus/examples/` (find them with
238
+ `python -c "import hilus, os; print(os.path.join(os.path.dirname(hilus.__file__), 'examples'))"`):
239
+ `quickstart.py`, `streaming_events.py`, `known_voices.py` (live
240
+ transcription that recognizes your own people), `async_job.py` and
241
+ `repo_edit_and_test.py` (change code on a branch, run its tests, open a
242
+ changeset). Every organization's own repository (`hilus clone`) starts with
243
+ more under `examples/`.
244
+
245
+ ## CLI
246
+
247
+ ```bash
248
+ hilus init # sign in (once)
249
+ hilus context whoami # organization, branch, API, masked token
250
+ hilus query run-hql --hql "Agent | select id, name | limit 5"
251
+ hilus entities list --entity-type Agent --limit 5
252
+ hilus docs --query "changesets" # the docs, no sign-in needed
253
+ hilus repos tree --depth 1
254
+ hilus clone # the organization's repository, plain git afterwards
255
+ hilus workspaces run --command "pytest -q" --branch feature/try
256
+ hilus workspaces steps # what ran, what it printed
257
+ hilus mount up # the organization's entities as a YAML filesystem
258
+ ```
259
+
260
+ `hilus --help` lists every group; each command's `--help` is the reference
261
+ (generated from the same route docstrings the API docs use). Errors print
262
+ one line and exit 1; with `--format json` they are `{"success": false,
263
+ "error": ...}` on stdout. Set `HILUS_DEBUG=1` to see every request.
264
+
265
+ `hilus clone` configures the clone with `credential.<api host>.helper =
266
+ git-credential-hilus`, which mints a one-hour password from the stored
267
+ sign-in whenever git asks, so `git pull`/`git push` work in any editor and
268
+ no token is written to disk. The helper answers only for the API host.
269
+
270
+ ## Typed clients
271
+
272
+ `hilus.generated` holds one typed client per service, rendered from the
273
+ served OpenAPI and AsyncAPI documents (`python -m Hilus.scripts.render_sdk_py`
274
+ in the monorepo; CI fails when the committed files are stale). Nested
275
+ mounts are attributes, routes are methods with the documented parameters,
276
+ responses are pydantic models (`extra="allow"`: a field the server adds
277
+ tomorrow does not break today's client), SSE routes yield typed frames,
278
+ WebSocket routes return a `FrameStream`, and routes answering raw bytes
279
+ (audio, HTML) return `bytes`.
280
+
281
+ `hilus sdk gen` writes a `hilus_types/` package with one pydantic model per
282
+ entity type of the organization (fields, nested models, `EntityRef`, tool
283
+ names), meant to be committed next to your code; `hilus sdk gen --check`
284
+ reports drift.
285
+
286
+ ## What's in the package
287
+
288
+ | Import | What |
289
+ |---|---|
290
+ | `hilus.PlatformClient`, `hilus.BrowserClient`, ... | Generated typed clients, one per service. |
291
+ | `hilus.ServiceClient` | The typed HTTP base the clients share; subclass it for a service of your own. |
292
+ | `hilus.errors` | `HilusApiError` and its subclasses. |
293
+ | `hilus.stt`, `hilus.audio` | Live transcription: `client.stt.listen` / `alisten`, its frames under short names, and `Audio` sources. |
294
+ | `hilus.hql` | Parser for HQL, the query language of `query.run_hql`. |
295
+ | `hilus.log` | `get_logger`: log from your own code to your organization's `Log`. |
296
+ | `hilus.cli.main` | The `hilus` click entry point (programmatic launching). |
297
+
298
+ ## License
299
+
300
+ Apache License 2.0 (the `LICENSE` file in the package). The license covers this package (the SDK and CLI); the Hilus platform it talks to is a hosted service under its own terms.
hilus/__init__.py ADDED
@@ -0,0 +1,72 @@
1
+ """Public Python SDK for Hilus services.
2
+
3
+ Quickstart:
4
+
5
+ .. code-block:: python
6
+
7
+ from hilus import PlatformClient
8
+
9
+ client = PlatformClient(auth_token="<api key>", organization="<organization id>")
10
+ print(client.admin.whoami().email)
11
+
12
+ With no arguments the client uses ``HILUS_API_URL`` / ``HILUS_API_TOKEN`` /
13
+ ``HILUS_ORG``, then the sign-in ``hilus init`` stored. One typed client per
14
+ service (``PlatformClient``, ``BrowserClient``, ...) is generated from the
15
+ served API documents; see :class:`ServiceClient` to write one of your own.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ from typing import Any
20
+
21
+ import logging as _logging
22
+
23
+ from hilus.api_url import ApiBase
24
+ from hilus.errors import AccessDeniedError, AuthError, HilusApiError, RateLimitError, StreamError, StreamTimeout, TransportError
25
+ from hilus.service_client import ServiceClient
26
+ from hilus.ws import FrameStream
27
+
28
+ def _installed_version() -> str:
29
+ # The version is stamped into the package metadata at release time (the
30
+ # "Release hilus" workflow); a source checkout reports the placeholder.
31
+ from importlib.metadata import PackageNotFoundError, version
32
+
33
+ try:
34
+ return version("hilus")
35
+ except PackageNotFoundError:
36
+ return "0.0.0.dev0"
37
+
38
+
39
+ __version__ = _installed_version()
40
+
41
+ # A library logs, the application decides whether to show it: without this,
42
+ # Python prints every warning record (one per failed request) to stderr.
43
+ _logging.getLogger("hilus").addHandler(_logging.NullHandler())
44
+
45
+ #: The generated clients are loaded on first use (``__getattr__``); they are
46
+ #: listed here so ``from hilus import *`` and completion know them.
47
+ _GENERATED_CLIENTS = ["PlatformClient", "BrowserClient", "GoogleClient", "SlackClient", "StripeClient"]
48
+
49
+ __all__ = [
50
+ "ApiBase",
51
+ "HilusApiError",
52
+ "AuthError",
53
+ "AccessDeniedError",
54
+ "RateLimitError",
55
+ "TransportError",
56
+ "StreamTimeout",
57
+ "StreamError",
58
+ "ServiceClient",
59
+ "FrameStream",
60
+ *_GENERATED_CLIENTS,
61
+ ]
62
+
63
+
64
+ def __getattr__(name: str) -> Any:
65
+ # The generated clients (`PlatformClient`, ...) define every model of
66
+ # every service; load them on first use so `import hilus` stays cheap.
67
+ if name.endswith("Client"):
68
+ import hilus.generated as generated
69
+
70
+ if hasattr(generated, name):
71
+ return getattr(generated, name)
72
+ raise AttributeError(f"module 'hilus' has no attribute {name!r}")
@@ -0,0 +1,55 @@
1
+ """Helpers the generated clients call; kept out of the generated tree.
2
+
3
+ ``ServiceClient._request`` always returns a dict and wraps non-object
4
+ bodies as ``{"value": ...}`` / ``{"text": ...}``; :func:`_scalar` undoes
5
+ that for routes documented to return a scalar or a list. :func:`_dump`
6
+ turns model arguments into JSON-ready values so a caller may pass either
7
+ a generated model or a plain dict.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ from functools import lru_cache
12
+ from typing import Any, TypeVar
13
+
14
+ from pydantic import BaseModel, TypeAdapter
15
+
16
+ T = TypeVar("T")
17
+
18
+
19
+ def _dump(value: Any) -> Any:
20
+ """JSON-ready form of a request argument (models dumped by alias)."""
21
+ if isinstance(value, BaseModel):
22
+ return value.model_dump(mode="json", by_alias=True, exclude_none=True)
23
+ if isinstance(value, list):
24
+ return [_dump(v) for v in value]
25
+ if isinstance(value, dict):
26
+ return {k: _dump(v) for k, v in value.items()}
27
+ return value
28
+
29
+
30
+ def _scalar(data: dict[str, Any]) -> Any:
31
+ """Unwrap a scalar or list response the transport wrapped in a dict."""
32
+ if "value" in data and len(data) == 1:
33
+ return data["value"]
34
+ if "text" in data and len(data) == 1:
35
+ return data["text"]
36
+ return data
37
+
38
+
39
+ @lru_cache(maxsize=None)
40
+ def _adapter(kind: Any) -> TypeAdapter[Any]:
41
+ """One cached :class:`TypeAdapter` per annotation (list responses)."""
42
+ return TypeAdapter(kind)
43
+
44
+
45
+ #: Hand-written methods a generated mount class takes as its base:
46
+ #: ``"<Service>.<mount path>"`` -> ``(module, class)``. The generator
47
+ #: (``Hilus.scripts.render_sdk_py``) reads this, so ``client.stt.listen``
48
+ #: sits beside the generated ``client.stt.stream`` without editing
49
+ #: generated code. A mixin's module must not import generated code at load.
50
+ MOUNT_MIXINS: dict[str, tuple[str, str]] = {
51
+ "Platform.stt": ("hilus._stt_mixin", "LiveTranscription"),
52
+ }
53
+
54
+
55
+ __all__ = ["MOUNT_MIXINS", "_adapter", "_dump", "_scalar"]