Metadata-Version: 2.5
Name: rydhm
Version: 0.1.2
Summary: The Rydhm API from Python: voice and chat experts, the Onboarding coach, and rep calls with live transcripts, suggestions and AI voicemail.
Project-URL: Homepage, https://rydhm.ai
Project-URL: Documentation, https://docs.rydhm.ai/developers/sdk-python
Author: Rydhm
License-Expression: MIT
License-File: LICENSE
Keywords: ai,dialer,onboarding,rydhm,sales,sdk,sse,voice,voice-agent
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
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: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: httpx<1,>=0.25
Requires-Dist: pydantic<3,>=2.5
Requires-Dist: typing-extensions>=4.7
Provides-Extra: test
Requires-Dist: pytest>=7; extra == 'test'
Description-Content-Type: text/markdown

# rydhm

The [Rydhm](https://rydhm.ai) API from Python: voice and chat experts, the **Onboarding coach** inside
your app, and **rep calls** (a human rep on the phone from the browser, Rydhm transcribing, suggesting
and leaving AI voicemails).

- Sync `Rydhm` and asyncio `AsyncRydhm` clients, built on `httpx`.
- Typed `pydantic` v2 models with snake_case attributes, typed errors, retries with backoff, timeouts.
- Live event streams (Server-Sent Events) as iterators that reconnect by themselves.
- Python 3.9+.

```
pip install rydhm
```

On PyPI: [pypi.org/project/rydhm](https://pypi.org/project/rydhm/). Docs: [docs.rydhm.ai/developers/sdk-python](https://docs.rydhm.ai/developers/sdk-python).

## Set up

Create a secret API key in the Rydhm app (**Developers → API keys**) with only the scopes you need.
Keep it on your server.

```python
from rydhm import Rydhm

client = Rydhm()  # reads RYDHM_API_KEY
# or: Rydhm(api_key="rydhm_live_...", base_url="https://api-staging.rydhm.ai", timeout=30, max_retries=2)
```

Every method takes `request_options={"timeout": 10, "max_retries": 0, "headers": {...}}`. Use the
client as a context manager (`with Rydhm() as client:`) to close its connections when you are done.

## Quickstart: Onboarding coach

The coach lives in your web app through `@rydhm/web`. From your server you sign users and keep the
coach's guides and page map in code.

```python
import os
from rydhm import Rydhm, sign_user_id

client = Rydhm()
expert_id = os.environ["RYDHM_EXPERT_ID"]

# 1. A publishable key for your website (experts:write).
key = client.engine.publishable_keys.create(
    expert_id, name="Production", allowed_origins=["https://app.example.com"], require_signed_user=True
)
print(key.key)  # rydhm_pk_live_...: goes in your page

# 2. Sign your users (the workspace's user-signing secret, from the Rydhm app).
user_hash = sign_user_id(os.environ["RYDHM_ENGINE_USER_SECRET"], "user_42")
# page: Rydhm.init({ key, user: { id: "user_42", hash: user_hash } })

# 3. The page map and a guide, as code (nested JSON is the API's camelCase).
client.engine.page_targets.sync(expert_id, [
    {"name": "Invite button", "selector": "[data-test=invite]", "textHint": "Invite", "pagePattern": "/settings/team"},
    {"name": "New project", "selector": "#new-project"},
])
client.engine.guides.create(
    expert_id,
    name="Invite your team",
    nudge="Want me to show you how to invite your team?",
    trigger={"type": "first_visit"},
    steps=[
        {"id": "open", "title": "Open Team settings", "instruction": "Take them to Settings, then Team.",
         "pagePattern": "/settings/team", "completeWhen": {"type": "page", "value": "/settings/team"}},
        {"id": "invite", "title": "Send an invite", "instruction": "Show the Invite button.",
         "target": "Invite button", "completeWhen": {"type": "event", "value": "invite_sent"}},
    ],
)

# 4. See how it goes (experts:read).
stats = client.engine.analytics(expert_id, days=30)
for funnel in stats.guides:
    print(funnel.name, f"{funnel.completed}/{funnel.started}")
for person in client.engine.end_users.list(expert_id, q="acme"):  # every page
    print(person.external_id, person.last_seen_at)
```

## Quickstart: rep calls

> Rep calls are in preview: the routes are live for early-access workspaces
> (`https://api-staging.rydhm.ai`); small changes are still possible before launch.

A key with `calls:write` and `calls:read`:

```python
client.reps.upsert("usr_4821", name="Maya Patel", mobile_number="+14155550101")

# The rep's browser goes online with this (hand the whole thing to the page):
token = client.reps.softphone_token("usr_4821").model_dump(by_alias=True)  # {url, token, presenceRoom, expiresAt}

call = client.rep_calls.create(
    rep="usr_4821",
    to="+14155550199",
    external_ref="act_77120",
    suggestions=True,
    context={"prospect": {"name": "Dana Kim", "company": "Acme"}, "goal": "Book a demo"},
    idempotency_key="act_77120",  # a retried request never dials twice
)
# hand call.join (url, token) to the browser: softphone.join(call)

for event in client.rep_calls.events(call.id):
    if event.type == "call.answered" and event.data.by == "machine":
        client.rep_calls.leave_voicemail(call.id)  # AI waits for the beep, speaks, hangs up
    elif event.type == "call.transcript" and event.data.final:
        print(f"{event.data.speaker}: {event.data.text}")
    elif event.type == "call.suggestion":
        print("Ask:", event.data.text)
    elif event.type == "call.summary":
        print(event.data.outcome, event.data.summary)  # the stream ends after the summary

client.rep_calls.hangup(call.id)  # safe to repeat
```

Callbacks ring the rep: put numbers in a pool, and listen to the rep's stream.

```python
pool = client.number_pools.create(
    name="West coast",
    strategy="local_presence",
    callback_routing={"order": ["rep_browser", "rep_mobile", "voicemail"], "ringSeconds": 20},
)
# Then put numbers in it in the app (Sales calls > Numbers, inbound mode "rep"): phone-number routes are
# session-only today, so client.phone_numbers.update(...) needs an admin session.

for event in client.events.stream(rep_id="usr_4821"):
    if event.type == "call.incoming":
        print("Callback from", event.data.from_, "about", event.data.external_ref)
```

## Async

```python
import asyncio
from rydhm import AsyncRydhm

async def main() -> None:
    async with AsyncRydhm() as client:
        call = await client.rep_calls.create(rep="usr_4821", to="+14155550199")
        async for event in client.rep_calls.events(call.id, types=["call.transcript"]):
            print(event.data.speaker, event.data.text)
        page = await client.rep_calls.list(rep="usr_4821")
        async for c in client.rep_calls.list():  # every call
            print(c.id, c.status)

asyncio.run(main())
```

## Live events

`rep_calls.events(call_id)` and `events.stream(rep_id=...)` return an `EventStream` of typed events
(`CallTranscriptEvent`, `CallAnsweredEvent`…; narrow on `event.type` or with `isinstance`).

- Reconnects after a drop with backoff and the server's `retry:` hint, resuming with `Last-Event-ID`;
  duplicates are dropped by event id.
- Heartbeats are skipped; no bytes for `heartbeat_timeout` (60 s) counts as a dead connection.
- A call's stream ends after `call.summary` (`until="ended"`, or `"never"`); a 4xx is raised at once.
- `types=[...]` keeps only some; `with ... as stream:` or `stream.close()` stops it;
  `stream.last_event_id` resumes later (`last_event_id=`).
- An event type this version does not know arrives as a plain `EngineEvent` (with `data` as a dict).

## Errors

```python
from rydhm import PermissionDeniedError, RateLimitError, RydhmError

try:
    client.rep_calls.create(rep="usr_4821", to="+14155550199")
except PermissionDeniedError as e:
    print("Add these scopes to the key:", e.missing_scopes)
except RateLimitError as e:
    print("Try again in", e.retry_after_seconds, "s")
except RydhmError as e:
    print(e.status, e.code, e.message, e.request_id)
```

| Exception | When |
| --- | --- |
| `BadRequestError` | 400 |
| `AuthenticationError` | 401 |
| `PaymentRequiredError` | 402 (`upgrade_hint`) |
| `PermissionDeniedError` | 403 (`missing_scopes`) |
| `NotFoundError` | 404 |
| `ConflictError` | 409 (`stale_edit`, duplicate names) |
| `UnprocessableEntityError` | 422 |
| `RateLimitError` | 429 after retries (`retry_after_seconds`) |
| `InternalServerError` | 5xx after retries |
| `RydhmConnectionError` | the API could not be reached (status 0) |
| `RydhmTimeoutError` | no answer in time (status 0) |

## Retries

Up to `max_retries` (2) more tries with exponential backoff or the server's `Retry-After`: a 429 with
`Retry-After` on any call (the rate limiter: nothing was done; `retry_on_rate_limit=False` turns it off),
and a 5xx, a timeout, a dropped connection or a 429 without `Retry-After` (`pool_exhausted`,
`concurrency_limit`) only on calls that are safe to repeat (reads, PUT, DELETE, `hangup`, `decline`,
`revoke`, `reorder`, `meetings.leave`, and anything with an `idempotency_key`).

## Webhooks

```python
from rydhm import WebhookVerificationError, verify_webhook

@app.post("/webhooks/rydhm")  # Flask
def rydhm_webhook():
    try:
        event = verify_webhook(os.environ["RYDHM_WEBHOOK_SECRET"], request.headers, request.get_data())
    except WebhookVerificationError:
        return "bad signature", 400
    if event.type == "call.summary.ready":
        crm.log(event.data["call"]["external_ref"], event.data["summary"]["snippet"])
    return "", 204
```

## Everything else

```python
experts = client.experts.list()
result = client.chat.ask(experts[0].id, "What can you help with?")
client.chat.ask(experts[0].id, "And pricing?", conversation_id=result.conversation_id)
# Or stream a reply as it is written: send the turn, then read the stream (ask() already read its own).
client.chat.send(result.conversation_id, "Do you offer a free trial?")
for frame in client.chat.stream(result.conversation_id):
    ...
client.knowledge.add(expert_id, filename="faq.md", content="# FAQ\n...")
hits = client.knowledge.search(expert_id, "refund policy")
token = client.voice.session(expert_id)
client.meetings.join(join_url="https://meet.google.com/abc-defg-hij", agent_id=expert_id, idempotency_key="evt-123")
client.request("GET", "/v1/analytics/usage", query={"from": "2026-11-01", "to": "2026-11-08"})  # any route
```

## Development

```
cd packages/sdk-python
python -m venv .venv && .venv/Scripts/python -m pip install -e ".[test]" build   # (bin/ on macOS and Linux)
python scripts/unasync.py        # regenerate the async resources after editing resources/_sync.py
python -m pytest
python -m build                  # dist/rydhm-0.1.0.tar.gz and the wheel
```

`resources/_sync.py` is the one place the routes are written; `resources/_async.py` is generated from it
(a test fails when it is stale). The rep-call routes and models follow `backend/api/src/rep-calls` and
`@tony/shared` engine/repCalls.ts (the "rep calls" parts of `_sync.py` and `_models.py`).
