Metadata-Version: 2.5
Name: thalovant
Version: 0.13.1
Summary: Python SDK and CLI for direct Thalovant hub data-plane clients and agents
Project-URL: Homepage, https://thalovant.com
Project-URL: Documentation, https://docs.thalovant.com/developers/sdks/python/
Project-URL: Repository, https://github.com/thalovant/thalovant-python-sdk
Project-URL: Issues, https://github.com/thalovant/thalovant-python-sdk/issues
Author: Thalovant
Maintainer: Thalovant
License-Expression: MIT
License-File: LICENSE
License-File: LICENSE-langcodes
Keywords: agent,assistant,iot,sdk,thalovant,voice
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Natural Language :: English
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Communications
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Requires-Dist: aiohttp>=3.11
Requires-Dist: cryptography<49.0.0,>=48.0.1; sys_platform == 'darwin' and platform_machine == 'x86_64'
Requires-Dist: cryptography>=48.0.1; sys_platform != 'darwin' or platform_machine != 'x86_64'
Provides-Extra: dev
Requires-Dist: bitstring<5,>=4.1.1; extra == 'dev'
Requires-Dist: build>=1.2; extra == 'dev'
Requires-Dist: certifi; extra == 'dev'
Requires-Dist: hivemind-bus-client>=1.1.9a1; extra == 'dev'
Requires-Dist: mypy>=1.13; extra == 'dev'
Requires-Dist: noiseprotocol>=0.3.1; extra == 'dev'
Requires-Dist: ovos-spec-tools[langcodes]<1.17,>=1.10.5a1; extra == 'dev'
Requires-Dist: paho-mqtt>=2.1.0; extra == 'dev'
Requires-Dist: poorman-handshake>=2.0.0a3; extra == 'dev'
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: pyyaml>=6.0.2; extra == 'dev'
Requires-Dist: requests>=2.33.0; extra == 'dev'
Requires-Dist: ruff>=0.8; extra == 'dev'
Requires-Dist: thalovant-languages>=0.3.0; extra == 'dev'
Requires-Dist: types-pyyaml; extra == 'dev'
Provides-Extra: docs
Requires-Dist: mkdocs-material>=9.7.7; extra == 'docs'
Requires-Dist: mkdocs>=1.6; extra == 'docs'
Requires-Dist: mkdocstrings[python]>=0.25; extra == 'docs'
Requires-Dist: pymdown-extensions>=11.0.1; extra == 'docs'
Provides-Extra: listing
Requires-Dist: thalovant-languages>=0.3.0; extra == 'listing'
Provides-Extra: mqtt
Requires-Dist: paho-mqtt>=2.1.0; extra == 'mqtt'
Provides-Extra: publish
Requires-Dist: build>=1.2; extra == 'publish'
Requires-Dist: twine>=7.0; extra == 'publish'
Provides-Extra: yaml
Requires-Dist: pyyaml>=6.0.2; extra == 'yaml'
Description-Content-Type: text/markdown

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/thalovant/.github/main/profile/assets/thalovant-logo-dark.png">
    <source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/thalovant/.github/main/profile/assets/thalovant-logo-light.png">
    <img src="https://raw.githubusercontent.com/thalovant/.github/main/profile/assets/thalovant-logo-light.png" alt="Thalovant" width="320">
  </picture>
</p>

# Thalovant Python SDK

[![PyPI](https://img.shields.io/pypi/v/thalovant)](https://pypi.org/project/thalovant/) [![CI](https://github.com/thalovant/thalovant-python-sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/thalovant/thalovant-python-sdk/actions/workflows/ci.yml) [![Licence](https://img.shields.io/github/license/thalovant/thalovant-python-sdk)](LICENSE) [![Docs](https://img.shields.io/badge/docs-docs.thalovant.com-5c6bc0)](https://docs.thalovant.com/developers/sdks/python/)

Python SDK for connecting apps, services, kiosks, and agents to Thalovant hubs.

The control API is used to discover hubs and provision a client identity. After
that, the SDK talks directly to the hub data plane over HTTPS, WSS, or MQTTS.

```text
Thalovant API      -> discover hubs, create client identity
Python SDK         -> connect to the hub data plane
Hub runtime        -> skills, events, replies
```

The SDK is asyncio at its core. `AsyncThalovantClient` and
`AsyncThalovantControlPlane` are the implementation; `ThalovantClient` and
`ThalovantControlPlane` run the same code on a private event-loop thread, so a
script, a CLI or a voice satellite can call them without an event loop of its
own.

## Requirements

- Python 3.10 or newer.
- A Thalovant account with API access for authenticated control-plane actions.
- A hub id or slug, and a client identity for that hub. You can create one
  through the API or use one downloaded from the dashboard.

## Install

```bash
pip install thalovant
```

Optional extras: `thalovant[mqtt]`, `thalovant[yaml]` and `thalovant[listing]`.
The documentation says what each one adds.

## Quick start

```python
from thalovant import ThalovantClient, ThalovantControlPlane

api = ThalovantControlPlane()

# Public hub discovery does not require auth.
public_hubs = api.list_public_hubs(limit=12)
for hub in public_hubs["data"]:
    print(hub["id"], hub["slug"], hub["title"])

# Auth is required when creating a client identity. This opens the browser on
# this machine, or prints a code to approve from any browser where there is none.
api.interactive_login()

result = api.create_client_identity(
    "hub-id",
    name="python-demo-client",
    preferred_protocols=("wss", "https", "mqtt"),
)

with ThalovantClient(result.identity, protocol="wss") as client:
    info = client.connection_info()
    print("connected in", info.connect_ms, "ms")
    reply = client.ask("Tell me a short clean joke.")
    print(reply.text)
```

Keep `result` secret: `result.identity` and the raw `result.client` API resource
carry the client credentials. `result.as_dict()` redacts every secret and is
safe to log; `result.as_dict(include_secrets=True)` returns the real
credentials, so use it only to save the identity and never log it.

## Sign in

```python
from thalovant import ThalovantControlPlane

api = ThalovantControlPlane()
api.interactive_login()  # the browser here, or a device code where there is none
# method="browser" or method="device" forces one.
```

`interactive_login()` opens your browser at the Thalovant consent page and
listens on `127.0.0.1` for the answer (OAuth with PKCE on a loopback redirect,
RFC 8252). It always prints the address too, in case the browser does not
open. The browser that approves hands the answer to its own computer, so a
sign-in link sent to somebody on another computer delivers nothing to you or to
them. (A forwarded port, such as `ssh -L`, or another user of the same computer
can still complete it.)

On a machine that cannot show a browser, it prints a code to enter at
`thalovant.com/activate` from any browser instead: over SSH, in CI, or on Linux
with neither `DISPLAY` nor `WAYLAND_DISPLAY`. It does the same against an API
that does not offer browser sign-in yet. `browser_login()` and
`login_with_browser()` (the device login) are the two methods on their own.
`AsyncThalovantControlPlane` has the same methods, awaited.

`scopes=` asks for what the token may do. The default is `hubs:read` and
`clients:write`. `device_name=` is what the consent page and the token show.
The default is `thalovant-python-sdk on <hostname>`.

The result is a scoped API token that lasts 365 days and is listed in the
dashboard. It counts against your plan. `api.revoke_api_token()` revokes it.

A denied sign-in raises `ThalovantDeviceLoginDenied`. A browser sign-in that
nobody answers within 300 seconds (`timeout=`) raises
`ThalovantDeviceLoginExpired`. Accounts with a password can still use
`api.login(email, password)`.

## Chat apps

A hub can answer in Telegram, Discord, Matrix, Mattermost or Twitch. Read the
owner's allowance first (Free plans allow none), connect the bot, then choose
where it answers. Credentials go in a `SecretValue`, which never prints.

```python
import os
from thalovant import SecretValue, ThalovantControlPlane

api = ThalovantControlPlane(access_token=os.environ["THALOVANT_API_TOKEN"])
hub_id = os.environ["THALOVANT_HUB_ID"]
if not api.get_bridge_networks(hub_id).allowance.can_create:
    raise SystemExit("The plan has no room for another chat app.")

# Telegram: a bot token.
telegram = api.create_bridge(hub_id, "telegram", token=SecretValue(os.environ["TELEGRAM_BOT_TOKEN"]))
chats = [chat for chat in api.list_bridge_chats(telegram.id) if chat.selectable]
if not chats:
    raise SystemExit("Add the bot to a group and mention it there, then list the chats again.")
telegram = api.update_bridge(telegram.id, allowed=chats[:1], etag=telegram.etag)
api.send_bridge_test_message(telegram.id, telegram.allowed[0].id)

# Matrix: a homeserver and user, and an access token. Room ids are typed.
matrix = api.create_bridge(
    hub_id, "matrix",
    secrets={"access_token": SecretValue(os.environ["MATRIX_ACCESS_TOKEN"])},
    settings={"homeserver": "https://matrix.example.org", "user_id": "@kitchen-hub:example.org"},
)
api.update_bridge(matrix.id, allowed=["!abcdefgh:example.org"])

# Twitch: bot login and client id, refresh token and client secret.
twitch = api.create_bridge(
    hub_id, "twitch",
    secrets={
        "refresh_token": SecretValue(os.environ["TWITCH_REFRESH_TOKEN"]),
        "client_secret": SecretValue(os.environ["TWITCH_CLIENT_SECRET"]),
    },
    settings={"bot_login": "kitchenhubbot", "client_id": os.environ["TWITCH_CLIENT_ID"]},
)
api.update_bridge(twitch.id, allowed=["#MyChannel"])

api.update_bridge(twitch.id, paused=True)        # pause; paused=False resumes
print(api.get_bridge(telegram.id).status.reason)  # Setup, Starting, Connected, Paused, ...
```

A refusal is a `ThalovantAPIError` with `code` and `fields` (the settings or
secrets it names); see the [chat apps guide](docs/guides/chat-apps.md) for the
status words, holds and every code.

## Intercom

Say a short text aloud on a hub's speakers (the [intercom guide](docs/guides/intercom.md)).
Off by default at every level, announce-only, and **not a certified safety system**: it does
not replace smoke or CO alarms, medical alert devices or emergency services. The API does
not store the text (it keeps a keyed hash and the length), and intercom does not record or
store speech. (The names are `announce` and `*_intercom_*`: the HiveMind mesh already has an
`intercom` frame, which is a different thing.)

```python
from uuid import uuid4

from thalovant import IntercomRepeat, IntercomTargets

api.set_intercom_settings(hub_id, True)                        # hubs:write
speakers = api.list_intercom_speakers(hub_id).items              # intercom:read; use a client_id
speaker = next((s for s in speakers if s.can_play), None)       # can_play=False is listed but never receives
if speaker is None:
    raise SystemExit("This hub has no connection that can play speech.")
api.update_intercom_speaker(hub_id, speaker.client_id, receive=True, room="kitchen")
# A fresh unique key for each announcement you mean to send. The same key replays the stored
# result (Idempotency-Replayed: true) and never sends again; to send again, use a new key.
api.announce(hub_id, "Dinner is ready", IntercomTargets.for_rooms("kitchen"),
             idempotency_key=str(uuid4()))                                # intercom:send
urgent = api.announce(hub_id, "Please answer", IntercomTargets.everyone(), priority="urgent",
                      repeat=IntercomRepeat(times=3, interval_seconds=20),
                      idempotency_key=str(uuid4()), wait=True)            # urgent needs intercom:urgent as well; the polls use intercom:read, which intercom:send implies
print(urgent.status, urgent.acked_by)
if urgent.sending:                                                        # still repeating after the wait
    api.cancel_announcement(hub_id, urgent.id)                            # stop it; a finished one is a 409
```

Scopes: `intercom:read`, `intercom:send`, `intercom:urgent` (in addition to `intercom:send`, for
`priority="urgent"` and every `repeat`) and `hubs:write` for settings and speakers. Speakers
carry `kind`, `can_play` (a connection that cannot play speech is listed but never receives) and
`policy_synced`; an announcement carries `replayed` when the answer is the stored one for your
key. The text is checked first with the API's own rule (1-280 characters, no `<` or `>`, no
control, bidirectional or invisible format characters). `delivered` means the hub handed the
speech to the speaker's connection, not that anyone heard it. The platform switch is off until
the operator turns it on: `ThalovantIntercomPlatformDisabledError`.

After a 502 `hub_unreachable`, read the announcement (`error.announcement_id`) before sending
again: a replayed `failed` announcement stays `failed`, so a deliberate second send needs a
new key. `announce` never uses a request timeout below 25 s (the API waits up to 10 s for the
hub). The hub, client and announcement ids are refused locally when they are `.`, `..`, empty,
or hold `/`, `?`, `#`, a backslash or a control character.

## Documentation

| Topic | Link |
| :--- | :--- |
| Python SDK: install, sign-in, identities, protocols, conversations, events, asyncio, Home Assistant, provisioning, errors, upgrading to 0.9 | <https://docs.thalovant.com/developers/sdks/python/> |
| The Thalovant product | <https://docs.thalovant.com> |

## Not yet in the online documentation

These parts of the old README have no counterpart on the documentation page.
They are described in the `docs/` folder of this repository and in
[CHANGELOG.md](CHANGELOG.md).

- Listing your hubs, workspace analytics and durable memory.
- Rich responses (`reply.display_items`) and skill sounds (`reply.media_events`).
- Actions and exact inputs (`send_action`, `send_code`).
- Reading an API error and the API shape overview.
- CLI diagnostics: `thalovant --identity _identity.json doctor` checks identity
  shape, endpoint selection, authentication, handshake and transport health.

## Development

```bash
pip install -e ".[dev]"
pytest
```

## Security

See [SECURITY.md](SECURITY.md).

## Licence

MIT. See [LICENSE](LICENSE).
