Metadata-Version: 2.4
Name: hilus
Version: 0.2.0
Summary: Python SDK and command-line tool for Hilus: query an organization's data, configure and test its AI agents, stream live calls and conversations, and work on its code.
Author: Hilus
License: Apache-2.0
Project-URL: Homepage, https://hilus.ai
Project-URL: Documentation, https://api.hilus.ai/Platform/docs
Keywords: hilus,ai agents,voice agents,api,sdk,cli,hql
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Environment :: Console
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: requests>=2.28
Requires-Dist: websocket-client>=1.6
Requires-Dist: websockets>=13.0
Requires-Dist: pydantic>=2.0
Requires-Dist: PyJWT[crypto]>=2.10
Requires-Dist: click>=8.1
Requires-Dist: pyyaml>=6.0
Requires-Dist: tabulate>=0.9
Requires-Dist: fusepy>=3.0
Provides-Extra: speech
Requires-Dist: numpy>=1.24; extra == "speech"
Requires-Dist: pydantic>=2.0; extra == "speech"
Requires-Dist: requests>=2.28; extra == "speech"
Requires-Dist: websockets>=12.0; extra == "speech"
Provides-Extra: opus
Requires-Dist: opuslib>=3.0; extra == "opus"
Provides-Extra: dev
Requires-Dist: mypy>=1.8; extra == "dev"
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: responses>=0.24; extra == "dev"
Requires-Dist: types-requests; extra == "dev"
Requires-Dist: pytest-mock>=3.0; extra == "dev"
Requires-Dist: ruff>=0.1; extra == "dev"
Requires-Dist: openapi-spec-validator>=0.9; extra == "dev"
Requires-Dist: moto>=5; extra == "dev"
Requires-Dist: pillow>=10; extra == "dev"
Requires-Dist: pydub>=0.25; extra == "dev"

# hilus

**The Python SDK and command-line tool for [Hilus](https://hilus.ai).**

Hilus runs AI agents that answer an organization's calls, web chat, email and
text messages, and act in the systems the organization already uses. This
package is how developers work with an organization on Hilus from code and
from the terminal:

- **Read and query its data:** conversations, calls, messages and every other
  record, with typed models and HQL, a SQL-like query language.
- **Configure its agents:** agents, workflows, documents and forms are
  versioned on branches and promoted to live through reviewed changesets.
- **Follow what happens live:** stream a call's events or a conversation as
  it unfolds.
- **Test agents before they go live:** simulate whole conversations, replay a
  reply, run saved tests.
- **Work on the organization's own code:** every organization has a git
  repository; clone it, change it on a branch, run its tests, ship it with a
  changeset.

One install gives you both:

- **`hilus` (Python):** typed clients generated from the API itself, one
  method per operation with documented parameters, pydantic responses,
  streaming, retries and typed errors.
- **`hilus` (CLI):** every API operation as a command, plus sign-in, `hilus
  clone` and a live view of the organization's configuration as files.

```bash
pip install hilus
```

Python 3.10 or newer. Full documentation, every operation and guide:
<https://api.hilus.ai/Platform/docs>.

## Sign in

```bash
hilus login           # opens the browser; sign in, or create an account there
hilus context whoami
```

`hilus login` signs you in through the browser, the way other CLIs do: no
key to copy. It stores a refresh token owner-only in
`~/.hilus/credentials.yaml`, and the CLI and the SDK renew the short-lived
access key themselves from then on. `hilus logout` revokes it. `hilus init`
does the same sign-in and also asks for your default organization and
branch. On a machine without a browser, `hilus login --no-browser` prints
the URL to open on another device; after you sign in there, the page shows a
code to paste back into the terminal.

The SDK uses that sign-in with no configuration: `PlatformClient()`.

**CI, servers and other automation** use an API key instead: create one on
the dashboard's Developer page, <https://app.hilus.ai/settings/developer>,
and set `HILUS_API_TOKEN` and `HILUS_ORG` (and `HILUS_API_URL` for a
non-production deployment), or store it with `echo "$KEY" | hilus init
--token -`. Never put a key on a command line. No account yet? Create one at
<https://app.hilus.ai/signup>.

If a call fails because you are not signed in, or because the credential was
refused (expired, revoked), the error says which and what to do.

An organization is a tenant: every call acts in one, sent as the
`X-Hilus-Schema` header. A key may be allowed several; pass
`organization=` (SDK) or `hilus context switch "<Org>"` (CLI) to choose.

## First call (SDK)

```python
from hilus import PlatformClient

client = PlatformClient()                       # from the environment, else from `hilus init`
# or, explicitly: PlatformClient(base="https://api.hilus.ai", auth_token="<api key>", organization="<org id>")

me = client.admin.whoami()                      # WhoamiUser
rows = client.query.run_hql(hql="Call | status = 'active' | limit 5").rows
agents = client.entities.list("Agent", limit=5)  # EntityListResponse
```

Precedence is explicit argument, then environment, then the stored sign-in.
An explicit token is never paired with the stored organization, and a token
stored for one API URL is refused for another: a staging key cannot reach
production by accident.

## Errors, retries and timeouts

Every failed call raises a typed exception with the HTTP context:

```python
from hilus import AccessDeniedError, AuthError, HilusApiError, RateLimitError, TransportError

try:
    client.entities.get("Agent", "missing")
except AuthError:               # 401, or no token at all
    ...
except AccessDeniedError as e:  # 403; e.denial_reason when a gateway refused
    ...
except RateLimitError as e:     # 429 after the retries; e.retry_after in seconds
    ...
except TransportError as e:     # no HTTP answer: DNS, connection, TLS, timeout (e.__cause__ is the requests error)
    ...
except HilusApiError as e:      # anything else: e.status_code, e.body, e.request_id
    print(e.status_code, e.body, e.request_id)
```

Idempotent requests (GET, or any call with `idempotent=True` on
`_request`) are retried up to `max_retries=3` times on 429/502/503/504 and
on transport failures, honouring `Retry-After`, with exponential backoff
capped at 30 s. Writes are never retried.

The client's `timeout=` (60 s) is the read timeout of a request; every
method also takes `request_timeout=`. Routes the server allows longer (a
test run, a workspace command) wait at least the server's own limit, so
`client.repos.repo_test(...)` does not time out on the client side.

## Streaming

Server-Sent Events routes are iterators; WebSocket routes return a
`FrameStream` to iterate and `send` on:

```python
from hilus import BrowserClient, PlatformClient, StreamTimeout
from hilus.generated.models import WSCallEventsConfigEvent

for entry in BrowserClient().stream_actions(session_id, since=0):   # SSE: ActionLogEntry frames
    print(entry.id, entry.type)

client = PlatformClient(ws_timeout=120)                             # idle limit; None waits for the server
with client.calls.call_events_stream(call_id) as frames:
    frames.send(WSCallEventsConfigEvent(type="config"))
    for frame in frames:                                            # typed by the frame's `type`
        print(frame.type)
print(frames.close_code, frames.close_reason)                       # set when the server closed
```

A dropped GET stream is reopened once from the last event id; a frame type
newer than this client is yielded as a dict instead of ending the stream;
idle past `ws_timeout` raises `StreamTimeout`.

## Live transcription

`client.stt.listen` streams audio to the live transcription socket and
yields what was said, and by whom, as it is said. It sends the audio as
binary frames at the pace it was spoken, sends `finalize` at the end, and
stops after `closed`:

```python
from hilus import PlatformClient
from hilus.audio import Audio
from hilus.stt import Identity, KnownPerson, Transcript

client = PlatformClient()
ann = KnownPerson(id="u-17", name="Ann", voiceprints=[held_print])   # a voiceprint you kept from an earlier stream

with client.stt.listen(Audio.wav("call.wav"), known=[ann], voiceprints="data") as live:
    for event in live:
        match event:
            case Transcript(is_final=True):
                print(f"speaker {event.speaker}: {event.text}")
            case Identity(status="identified"):
                print(f"speaker {event.speaker} is {event.known_id}")
        # live.add_known(...), live.remove_known(...), live.update(keyterms=[...]) change it while it runs
new_prints = live.voiceprints                                         # speaker -> voiceprint, to keep
```

- Audio: `Audio.wav(path_or_file)` (rate, width and channels from the
  header), `Audio.pcm(bytes, sample_rate)` (what `tts.speak_stream(format="pcm")`
  returns), `Audio.mulaw` / `Audio.alaw` for phone audio, `Audio.numpy(array,
  sample_rate)`, `Audio.join(parts, gap=)`; or an iterable of byte chunks
  (a microphone, a phone line), sent as they arrive. `realtime=False` sends
  a recording as fast as the socket takes it.
- Opus, to save bandwidth (`pip install "hilus[opus]"`):
  `client.stt.listen(Audio.wav("call.wav"), encoding="opus", bitrate=24000)`
  sends 20 ms Opus packets, about 134 kB a minute of speech against 1.92 MB
  of 16 kHz PCM; `Audio.opus_packets(packets)` sends packets you already
  have as they are. PCM stays the default: Opus is lossy.
- `async with client.stt.alisten(...) as live: async for event in live: ...`
  is the same for asyncio, and takes async iterables.
- A refused config raises `hilus.StreamError` on entering, before any audio
  is sent; an `error` frame mid-stream is yielded; a stream that fails raises
  `StreamError`. The low-level socket is still `client.stt.stream()`
  (`FrameStream.send_bytes` sends binary frames).

`examples/known_voices.py` is the whole round trip: two of the platform's
voices make a first call, which collects a voiceprint, and a second, which
recognizes that person by your own id.

## Background work

Routes that run in the background by default (`clinical.clinical_consult`,
`lab.simulate`, ...) answer `202` while the server works. With the default
`wait=True` the method polls until the result is ready (`wait_timeout`
seconds at most, `poll_interval` seconds at first, backing off to five);
with `wait=False` it returns a `PendingExecution` to poll yourself:

```python
pending = client.clinical.clinical_consult(case_synopsis="...", species="dog", wait=False)
outcome = client.jobs.poll_async(pending.async_id)    # {"status": "pending" | "completed" | "failed", "result": ...}
```

## Logging from your code

`hilus.log.get_logger` gives you a standard Python logger whose lines go to
Hilus, where your organization's members read them as `Log` (the
dashboard's Logs page, or `hilus query run-hql --hql "Log | ..."`):

```python
from hilus.log import get_logger

log = get_logger("acme.sync")                   # any dotted name not under `hilus`
log.info("synced %s visits", 12, extra={"clinic": "north", "rows": 12})
try:
    sync()
except Exception:
    log.exception("sync failed")                # the traceback is part of the message
```

Everything in `extra=` becomes the line's `data` (strings, numbers and
bools; anything else is sent as its `str`), so any key works, `message`
included. The loggers sit in a tree of their own: your own `logging`
configuration neither repeats nor stops their lines.

Lines are queued and sent in the background with the client's usual
credentials, at most 500 per request or after a second; `log.info` never
waits on the network and never raises. A busy or unreachable server is
retried; up to 10,000 waiting lines are kept, and if older ones had to be
dropped the next batch says how many. Lines still queued are sent at exit
(waiting five seconds at most); call `hilus.log.flush()` yourself before
`os._exit` or at the end of a short job. Set `HILUS_LOG_ECHO=1` to also
print every line to stderr. To send a standard-library logger's lines too,
attach a `hilus.log.HilusHandler()` to it.

## Examples

The package ships runnable examples in `hilus/examples/` (find them with
`python -c "import hilus, os; print(os.path.join(os.path.dirname(hilus.__file__), 'examples'))"`):
`quickstart.py`, `streaming_events.py`, `known_voices.py` (live
transcription that recognizes your own people), `async_job.py` and
`repo_edit_and_test.py` (change code on a branch, run its tests, open a
changeset). Every organization's own repository (`hilus clone`) starts with
more under `examples/`.

## CLI

```bash
hilus init                                              # sign in (once)
hilus context whoami                                    # organization, branch, API, masked token
hilus query run-hql --hql "Agent | select id, name | limit 5"
hilus entities list --entity-type Agent --limit 5
hilus docs --query "changesets"                         # the docs, no sign-in needed
hilus repos tree --depth 1
hilus clone                                             # the organization's repository, plain git afterwards
hilus workspaces run --command "pytest -q" --branch feature/try
hilus workspaces steps                                  # what ran, what it printed
hilus mount up                                          # the organization's entities as a YAML filesystem
```

`hilus --help` lists every group; each command's `--help` is the reference
(generated from the same route docstrings the API docs use). Errors print
one line and exit 1; with `--format json` they are `{"success": false,
"error": ...}` on stdout. Set `HILUS_DEBUG=1` to see every request.

`hilus clone` configures the clone with `credential.<api host>.helper =
git-credential-hilus`, which mints a one-hour password from the stored
sign-in whenever git asks, so `git pull`/`git push` work in any editor and
no token is written to disk. The helper answers only for the API host.

## Typed clients

`hilus.generated` holds one typed client per service, rendered from the
served OpenAPI and AsyncAPI documents (`python -m Hilus.scripts.render_sdk_py`
in the monorepo; CI fails when the committed files are stale). Nested
mounts are attributes, routes are methods with the documented parameters,
responses are pydantic models (`extra="allow"`: a field the server adds
tomorrow does not break today's client), SSE routes yield typed frames,
WebSocket routes return a `FrameStream`, and routes answering raw bytes
(audio, HTML) return `bytes`.

`hilus sdk gen` writes a `hilus_types/` package with one pydantic model per
entity type of the organization (fields, nested models, `EntityRef`, tool
names), meant to be committed next to your code; `hilus sdk gen --check`
reports drift.

## What's in the package

| Import | What |
|---|---|
| `hilus.PlatformClient`, `hilus.BrowserClient`, ... | Generated typed clients, one per service. |
| `hilus.ServiceClient` | The typed HTTP base the clients share; subclass it for a service of your own. |
| `hilus.errors` | `HilusApiError` and its subclasses. |
| `hilus.stt`, `hilus.audio` | Live transcription: `client.stt.listen` / `alisten`, its frames under short names, and `Audio` sources. |
| `hilus.hql` | Parser for HQL, the query language of `query.run_hql`. |
| `hilus.log` | `get_logger`: log from your own code to your organization's `Log`. |
| `hilus.cli.main` | The `hilus` click entry point (programmatic launching). |

## License

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.
