Skip to main content

bloonio_voice_relay_client

Client SDK for bloonio_voice_relay — the Bloonio voice-assistant PaaS. Backend integration for tenants: mint per-call tokens for your app's WebRTC/WS client, manage voice assistants (openai / gemini / sandbox), and fetch sessions and transcripts. Framework-agnostic (httpx + pydantic), bearer-key auth only.

Install

pip install bloonio-voice-relay-client

Two-minute integration

# .env
BLOONIO_VOICE_BASE_URL=$BASE_URL
BLOONIO_VOICE_API_KEY=bvr_...

Unlike the sibling wa / mail / auth / chat relay clients (each keyed on a tenant_id + tenant_secret pair), the voice tenant plane accepts exactly one credential: Authorization: Bearer bvr_.... No HMAC signing, no secondary auth mode — BLOONIO_VOICE_API_KEY is the only secret this SDK needs.

This SDK is the backend side — read this before writing any integration code. VoiceRelayClient / AsyncVoiceRelayClient hold your tenant's bvr_ key and must never run in a browser or ship inside a mobile app. The pattern your app's WebRTC/WS client actually needs: your server calls mint_call_token(assistant_id=...) and hands the resulting call_token to your app; the app then talks to the relay's public plane directly (/api/v1/public/connect/session, the call-token-gated stream socket, /api/v1/public/fetch/transcript) using only that token. The bvr_ key itself never leaves your backend.

The token is session-scoped — it authorises exactly one session (connect it, stream it, read its transcript) and nothing else — and reusable within its TTL (CALL_TOKEN_TTL_SECONDS, 300s by default server-side): it is not single-use. The TTL bounds how long the token can be used to start something (connect the call, open the stream socket); reading the transcript of a call that's already connected is honoured past that TTL for as long as the session is still live.

Quickstart

# main.py — construct the client once at startup and register it as the singleton
from fastapi import FastAPI
from bloonio_voice_relay_client import VoiceRelayClient, VoiceRelaySettings, set_voice_client

app = FastAPI()
set_voice_client(VoiceRelayClient(VoiceRelaySettings()))   # reads the BLOONIO_VOICE_* env vars above
# anywhere else — a route, a worker task, a management command
from bloonio_voice_relay_client import get_voice_client

voice = get_voice_client()
voice.whoami()   # confirms the key resolves: {"tenant_id": ..., "tenant_name": ...}

# provider="sandbox" is the one provider that costs nothing and calls nothing to try —
# no OpenAI/Gemini credentials needed, zero outbound network calls server-side. `openai`
# and `gemini` are the real providers; swap `provider=` once you're wiring an actual call.
assistant = voice.create_assistant(
    name="Front desk",
    provider="sandbox",
    instructions="You are a friendly assistant for Acme Freight.",
)
print(assistant["assistant_id"], assistant["status"])

# Mint a call token for THIS assistant and hand `call_token` to your app — see
# "This SDK is the backend side" above. Never hand the app `voice` itself.
token = voice.mint_call_token(assistant_id=assistant["assistant_id"])
print(token["call_token"], token["expires_at"])

session = voice.fetch_session(session_id=token["session_id"])
print(session["status"])   # "created" -> "active" -> "ended" | "orphaned"

for turn in voice.fetch_transcript(session_id=token["session_id"]):
    print(turn["role"], turn["text"])

Errors. Every method raises VoiceRelayError on any non-2xx response: .status_code, .message (the relay's message, or the raw response text when there's no structured message to show), and .body (the parsed JSON envelope, or None when the response body wasn't JSON at all). .code also exists — extracted from the envelope's data.code when present, the same mechanism bloonio_wa_relay_client uses — but is always None against the real relay today: no voice tenant-plane route currently populates it, so an identifier like QUOTA_EXCEEDED rides inside .message instead ("QUOTA_EXCEEDED: monthly minutes exhausted"), not as a separate field.

from bloonio_voice_relay_client import VoiceRelayError

try:
    voice.mint_call_token(assistant_id=assistant["assistant_id"])
except VoiceRelayError as e:
    print(e.status_code, e.message)

Reuse one VoiceRelayClient per process — it wraps a single httpx.Client — and either call voice.close() when done or use it as a context manager: with VoiceRelayClient(...) as voice:. The async twin, AsyncVoiceRelayClient, has full method parity (await voice.whoami(), async with AsyncVoiceRelayClient(...) as voice: / await voice.aclose()).

Assistants

for a in voice.list_assistants():   # newest first, no pagination, capped at 200
    print(a["assistant_id"], a["name"], a["status"])

assistant = voice.fetch_assistant(assistant_id="asst_1")

update_assistant only edits name / instructions / voice / first_message / language / temperature / tools — provider, pipeline, mode and model are fixed at creation and cannot be changed afterward; the update endpoint has no fields for them at all (create a new assistant instead of trying to migrate one in place). Fields you don't pass are left untouched, not cleared — there's no way to null a field through this route either:

updated = voice.update_assistant(assistant_id="asst_1", name="New name", temperature=0.5)

delete_assistant always returns None — the relay's delete response carries no data, only a confirmation message, so there's nothing to hand back:

voice.delete_assistant(assistant_id="asst_1")   # -> None

Sessions & calls

create_session and mint_call_token accept the identical assistant_id request — the difference is the response. create_session is for when your OWN backend will finish the call itself (see connect_session below); mint_call_token (Quickstart, above) is the one to reach for when you're instead handing the call off to your app's own WebRTC/WS client over the public plane.

session = voice.create_session(assistant_id="asst_1")

for s in voice.list_sessions():   # newest first, no pagination/filter, capped at 200
    print(s["session_id"], s["status"])

connect_session applies to provider="openai" sessions only (400 otherwise) and, unlike every other method here, performs a real, billable server-proxied SDP exchange with OpenAI the moment it succeeds — there is no sandbox/dry-run form of this one call. A gemini session instead streams over a websocket (/relay/stream/session), out of this SDK's scope. Only call it once you're intentionally starting a live OpenAI call, with an SDP offer your own WebRTC stack produced:

result = voice.connect_session(session_id=session["session_id"], sdp_offer="v=0\r\n...")
print(result["attached"], result["sdp_answer"])

Tools: webhook and http kinds

An assistant's tools hold two kinds, selected by kind (a tool without kind is a webhook). Pass plain dicts or the WebhookTool / HttpTool models; the full contract is section 11 of the relay's docs/02_API_CONTRACT.md.

from bloonio_voice_relay_client import HttpTool

booking = HttpTool(
    name="get_booking",
    description="Look up a booking by its six-letter reference.",
    url="https://api.example.com/v1/bookings/{reference}",
    headers={"X-Assistant-Key": "k_live_example"},        # secret: stored encrypted, read back as "•••"
    parameters={"type": "object", "properties": {"reference": {"type": "string"}}, "required": ["reference"]},
    send_visitor=True,                                    # adds X-Assistant-Visitor / X-Assistant-Conversation
)
voice.update_assistant(assistant_id="asst_1", tools=[booking])
  • http mirrors chat's BotTool field for field, so the identical chat tool JSON works unchanged and kind is optional: the relay treats an entry with url and no server_url as http (an entry with server_url stays a webhook). Chat's model forbids unknown fields, so for JSON chat also reads use HttpTool(...).chat_json(), which dumps the tool without kind: GET puts the arguments in the query, POST in a JSON body, never retried, redirects not followed, result capped at 6000 chars. On this (relay, bvr_) plane headers replace the stored ones wholesale; sending a read-back ••• is refused. Header names must be HTTP tokens and values visible ASCII (no accents, tabs or line breaks: put such data in a parameter), and X-Assistant-Visitor / X-Assistant-Conversation are the relay's own (it sets them for send_visitor tools). HttpTool refuses all of these locally, as the relay does (422 invalid_header_name, invalid_header_value, reserved_header_name; relay 0.3.0).
  • webhook is a signed POST; retried only on network errors / 5xx (max 3). The body is JSON-escaped (\uXXXX for non-ASCII); verify the raw bytes as received. A non-object JSON answer is passed to the model as raw text.

Caller identity

call = voice.mint_call_token(assistant_id="asst_1", caller_ref=str(customer.id))   # server-side only

caller_ref (1-140 printable characters, accents fine) is your id for the person on the call. It is never settable from a publishable-key client. send_visitor http tools receive it as X-Assistant-Visitor (UTF-8: a latin-1-decoding server recovers it with value.encode("latin-1").decode("utf-8")); a send_visitor tool on a session without one is not called (the model hears this needs a signed-in caller). A webhook tool's signed body carries caller_ref whenever the session has one, for every webhook tool.

Verifying a webhook call

from bloonio_voice_relay_client import verify_tool_webhook

# raw bytes, e.g. FastAPI: body = await request.body()
if not verify_tool_webhook(
    secret=HMAC_SECRET,
    body=body,
    timestamp=request.headers["X-Voice-Timestamp"],
    signature=request.headers["X-Voice-Signature"],
):
    raise PermissionError("bad signature")
call_id = request.headers.get("X-Voice-Call-Id")   # NOT signed: a de-duplication hint across retries only

Scheme: hex(hmac_sha256(secret, f"{timestamp_ms}.{sha256_hex(body)}")); timestamps older (or newer) than tolerance_seconds (default 300) are rejected. It returns False, never raises.

Public surface

Every client method returns the relay's response data verbatim — a plain dict or list, never an instance of the schemas below. The schemas exist so you can validate/type a response yourself, e.g. Assistant.model_validate(res).

Symbol Kind Notes
VoiceRelayClient client (sync) wraps httpx.Client; reuse one per process
AsyncVoiceRelayClient client (async) wraps httpx.AsyncClient; async with / await .aclose()
VoiceRelaySettings settings reads BLOONIO_VOICE_* env vars (pydantic-settings); base_url / api_key required, request_timeout_seconds defaults to 10.0
VoiceRelayError error raised on any non-2xx; .status_code / .message / .body / .code (see "Errors" above)
AssistantProvider enum openai | gemini | sandbox
SessionStatus enum created → active → ended | orphaned
TurnRole enum user | assistant
AssistantTool schema one entry of Assistant.tools — the create-side hmac_secret is write-only and never echoed back, so this schema doesn't model it either
Assistant schema create_assistant() / fetch_assistant() / list_assistants() (one row) / update_assistant(); status is a plain str, always "active" in practice (deleted rows are never returned again)
WebhookTool / HttpTool schema tool definitions for create_assistant / update_assistant; Assistant.tools reads back both kinds
verify_tool_webhook function receiver-side check of a signed webhook tool call
CallToken schema mint_call_token()'s response shape
Session schema fetch_session() / list_sessions() (one row) — deliberately narrower than the raw dict; internal bookkeeping fields present after a call connects are ignored, not rejected, if you validate into this schema
ConnectSessionResult schema connect_session()'s response shape
TranscriptTurn schema one row of fetch_transcript()
set_voice_client / get_voice_client singleton app-startup wiring — see "Quickstart"

Voice ships no contract doc — the three enums above are read directly off bloonio_voice_relay's own source, not a published spec, and none of them are formal enum.Enum classes server-side. A future value the relay starts returning that isn't listed here raises pydantic.ValidationError out of .model_validate() rather than parsing leniently — client methods return the raw dict/list regardless of this, so it only bites if you opt into the schemas above.

License

Proprietary — Bloonio internal.

Metadata

Release files for bloonio-voice-relay-client 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for bloonio-voice-relay-client 0.2.0
File Size Uploaded Provenance Actions
bloonio_voice_relay_client-0.2.0.tar.gz 38.8 kB Without provenance Details for bloonio_voice_relay_client-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for bloonio-voice-relay-client 0.2.0
File Interpreter ABI Platform Actions
bloonio_voice_relay_client-0.2.0-py3-none-any.whl Python 3 none any Details for bloonio_voice_relay_client-0.2.0-py3-none-any.whl

Total release size: 62.4 kB

Release files / bloonio_voice_relay_client-0.2.0.tar.gz

Download URL bloonio_voice_relay_client-0.2.0.tar.gz
Size 38.8 kB
Tags Source
SHA-256 checksum
How to use checksums
bdc29d106bdaf136c19e83e96fa3bc637ecf42d787c765c1c7e3fb8729a88b27
BLAKE2b-256 checksum
How to use checksums
f7d4bd4ff79d41916faee4b2bcbd3fef41d2db40b99ede423a1e99c5b6589216
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.13

Release files / bloonio_voice_relay_client-0.2.0-py3-none-any.whl

Download URL bloonio_voice_relay_client-0.2.0-py3-none-any.whl
Size 23.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
13cc717292e269c4fea6b4afbfe0b2eb69ae49842ed93b9f50df23dd991a256b
BLAKE2b-256 checksum
How to use checksums
508966af3bac30d35e50c9fd2e9b78ee16ede1e09067353432cbcfc17931fb29
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.13

Security for bloonio-voice-relay-client 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page