Metadata-Version: 2.4
Name: satham
Version: 0.1.5
Summary: Async Python client for satham's realtime speech-to-speech API and kural-1 text to speech
Project-URL: Homepage, https://satham.ai
Author: satham
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: hindi,indian-languages,realtime,satham,speech,speech-to-speech,tamil,telugu,text-to-speech,tts,voice-agent,websocket
Classifier: Development Status :: 3 - Alpha
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.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: websockets<18,>=13.1
Description-Content-Type: text/markdown

# satham

An async Python client for satham's realtime speech-to-speech API. Your agent brings its own
instructions, greeting and tools; you connect to your satham endpoint with your API key, stream the
caller's audio in and the agent's audio out, follow transcripts, interruptions and language changes,
answer tool calls, and change any of the call's controls while it runs. It also speaks text with
kural-1, satham's text-to-speech model ([Text to speech](#text-to-speech)).

Python 3.11+. One dependency: `websockets`.

```sh
pip install satham
```

Framework adapters: [`livekit-plugins-satham`](https://pypi.org/project/livekit-plugins-satham/) for
LiveKit Agents and [`pipecat-satham`](https://pypi.org/project/pipecat-satham/) for Pipecat.

## A call

You pass your satham endpoint and API key (or set `SATHAM_URL` and `SATHAM_API_KEY`); there is no
default server.

```python
import asyncio
import os

import satham

ROLE = "You are Asha, who books site visits for Example Homes. Keep every reply short."


async def main() -> None:
    async with satham.connect(
        os.environ["SATHAM_URL"],  # your satham endpoint, wss://... or https://...
        os.environ["SATHAM_API_KEY"],
        instructions=ROLE,  # the agent's role: your prompt
        greeting="Hello, this is Asha from Example Homes. Is this a good time?",
        language="en",  # or "auto"; the call can follow the caller into another language
        language_switch="auto",
        sample_rate=16_000,  # the caller audio you send: 16-bit mono PCM
    ) as call:
        asyncio.create_task(stream_microphone(call))  # await call.send_audio(pcm) per packet
        async for event in call:
            match event:
                case satham.ResponseAudio():
                    speaker.write(event.data)  # PCM in call.output_audio's format
                case satham.SpeechStarted() | satham.ResponseInterrupted():
                    speaker.clear()  # the caller is talking: stop at once
                case satham.TranscriptFinal():
                    print("caller:", event.text, event.language)
                case satham.ResponseDone():
                    print("agent:", event.text)
                case satham.SessionUpdated():
                    print("now in", event.language, "because of the", event.reason)


asyncio.run(main())
```

Without a `greeting` the caller speaks first. `connect()` raises `AuthenticationError`,
`ServerBusyError`, `InvalidRequestError` (a refused setting) or `SathamError` (connection failures
and timeouts; `.code` says which). A bad value fails in the client with `ValueError` before anything
is sent.

During the call, `await call.update(...)` changes any control (the same names as `connect`; only what
you pass is sent, and `instructions` can change too), `call.commit()` ends the caller's turn now
(push-to-talk), `call.cancel()` stops the reply, and `call.close()` ends the call. `call.language`
follows every language change.

Replies on demand: `await call.create_response(instructions=None)` asks for a reply now (to open the
call, or after a quiet spell; `instructions` guide that reply alone), and `await call.say(text)` has
the agent say fixed words in its voice. While a reply is under way, or the caller is speaking, the
server answers with a non-fatal `response_in_progress` error.

## Controls

Every keyword of `connect()` and `update()` besides the URL, key and audio format is a control
(`satham.SessionControls`, a `TypedDict`). OpenAI's names are used where LiveKit's OpenAI realtime
plugin has one; groups (`turn_detection`, `input_audio_noise_reduction`, `input_audio_transcription`,
`phrasing`) are dicts of the keys shown. A control you leave out is not sent, so the server's default
holds. Values are checked against the ranges below, or against your server's once
`await client.load_controls()` has read them from `GET /v1/info`.

The controls marked "needs session controls" need a satham server with session controls (its
`GET /v1/info` lists `controls`, as the server does since 2026-11-16); an older server refuses them
when the call starts. `greeting` and `agent` belong to the start of a call. Setting
`input_audio_noise_reduction`'s `mode` alone resets `strength_db` to that mode's preset, so send both
to keep a custom strength; `None` leaves noise reduction at the server's default (on), and `"none"`
turns it off. `agent` is
an optional preset on the server (such as a demo's) and is not needed.

<!-- controls -->
| Option | Range | Default | OpenAI equivalent | Notes |
| --- | --- | --- | --- | --- |
| `instructions` | text, up to 16000 characters | none | - | the agent's role; from the LiveKit agent or Pipecat context in the adapters |
| `greeting` | text, up to 1000 characters | none | - | said first; without one the caller speaks first |
| `tools` | up to 128 functions | none | - | preview: needs a server with tool support |
| `tool_choice` | see notes | "auto" | `tool_choice` | "auto", "none", "required" or one function |
| `agent` | text, up to 64 characters | none | - | optional: a preset agent on the server, such as a demo's |
| `model` | text, up to 64 characters | "satham-1" | `model` | "satham-1" only today; needs session controls |
| `modalities` | list | ["audio", "text"] | `modalities` | ["audio", "text"], ["audio"], or ["text"]: words only, for your own TTS; needs session controls |
| `language` | `auto`, `hi`, `ta`, `te`, `kn`, `bn`, `pa`, `en` | "auto" | - |  |
| `language_switch` | `auto`, `off`, or `None` | "auto" | - |  |
| `voice_on_language_switch` | `keep`, `native`, or `None` | "keep" | - |  |
| `turn_detection.enabled` | `True` / `False` | true | `turn_detection=None` | false (or turn_detection=None): the client ends each turn; needs session controls |
| `turn_detection.type` | `server_vad`, `semantic_vad` | "server_vad" | `turn_detection.type` | needs session controls |
| `turn_detection.threshold` | 0.1 to 0.95 | 0.5 | `turn_detection.threshold` | the speech detector's threshold; needs session controls |
| `turn_detection.eagerness` | `auto`, `low`, `medium`, `high` | "auto" | `turn_detection.eagerness` | semantic_vad's end-of-turn wait; needs session controls |
| `turn_detection.prefix_padding_ms` | 0 to 1000 | 300 | `turn_detection.prefix_padding_ms` | needs session controls |
| `turn_detection.min_speech_ms` | 50 to 1000 | 100 | - | needs session controls |
| `turn_detection.silence_duration_ms` | 150 to 2000 | 350 | `turn_detection.silence_duration_ms` | server_vad's end-of-turn wait; needs session controls |
| `turn_detection.create_response` | `True` / `False` | true | `turn_detection.create_response` | answer each turn at once; needs session controls |
| `turn_detection.interrupt_response` | `True` / `False` | true | `turn_detection.interrupt_response` | barge-in on or off; needs session controls |
| `turn_detection.barge_in.min_speech_ms` | 0 to 2000 | 400 | - | needs session controls |
| `turn_detection.barge_in.min_probability` | 0 to 1 | 0.8 | - | needs session controls |
| `turn_detection.barge_in.min_dbfs` | -90 to 0, or `None` | -40 | - | needs session controls |
| `turn_detection.continue_within_ms` | 0 to 5000, or `None` | 2000 | - | the caller carrying on in the same turn; null: off; needs session controls |
| `turn_detection.continue_max_heard_ms` | 0 to 5000 | 1000 | - | needs session controls |
| `input_audio_noise_reduction.enabled` | `True` / `False` | true | `input_audio_noise_reduction={"type": "none"}` | false, "none" or {"type": "none"}: off; needs session controls |
| `input_audio_noise_reduction.mode` | `near_field`, `far_field` | "near_field" | `input_audio_noise_reduction.type` | resets strength_db to the mode's preset (12 or 30 dB) unless both are sent; needs session controls |
| `input_audio_noise_reduction.strength_db` | 0 to 100 | 12 | - | needs session controls |
| `input_audio_noise_reduction.apply_to_transcription` | `True` / `False` | false | - | needs session controls |
| `input_audio_transcription.enabled` | `True` / `False` | true | `input_audio_transcription=None` | transcript events to the client; needs session controls |
| `input_audio_transcription.code_mixed` | `True` / `False` | true | - | English words in Latin script, and digits; needs session controls |
| `voice` | text, up to 64 characters | the language's | `voice` |  |
| `breaths` | `True` / `False`, or `None` | off | - |  |
| `natural_pauses` | `True` / `False`, or `None` | off | - |  |
| `variant` | `"natural"` / `"warm"`, or `None` | the agent's, else natural | - | the voice's sound, from the next reply |
| `continuation` | `True` / `False`, or `None` | true | - | each phrase carries on from the one before; needs session controls |
| `speed` | 1 to 1 | 1.0 | `speed` | 1.0 only today; needs session controls |
| `phrasing.first_phrase_max_chars` | 1 to 120 | 120 | - | at least min_phrase_chars; needs session controls |
| `phrasing.min_phrase_chars` | 1 to 120 | 20 | - | needs session controls |
| `normalise_numbers` | `True` / `False` | true | - | numbers and amounts said as words; needs session controls |
| `pronunciations` | word to respelling | none | - | {word: respelling}, up to 200; needs session controls |
| `temperature` | 0.6 to 1.2 | 0.7 | `temperature` | needs session controls |
| `top_p` | 0.05 to 1 | 0.8 | - | needs session controls |
| `max_response_output_tokens` | 1 to 4096 | 320 | `max_response_output_tokens` | or "inf"; never above the server's; needs session controls |
| `tone` | `auto`, `conversational`, `happy`, `sad`, `excited`, `professional` | "auto" | - | "auto": the model picks; needs session controls |
| `repeat_guard` | `True` / `False` | true | - | re-asks a reply that repeats a recent one; needs session controls |
| `drift_guard` | `True` / `False` | true | - | keeps replies in the call's language; needs session controls |
| `ambience.sound` | `none`, `office`, `call-centre`, `cafe`, `restaurant`, `city`, `static` | "none" | - | background sound under the agent's voice; `ambience=None`: off; needs a server with background sound |
| `ambience.strength` | 0 to 2 | 1.0 | - | 1.0 is -35 dBFS RMS, a linear gain (0 is silent) |
| `ambience.typing` | `True` / `False` | false | - | keyboard typing while a tool call runs longer than 0.4 s |
| `ambience.typing_strength` | 0 to 2 | 1.0 | - | the same scale, capped at strength |
| `ambience.record` | `True` / `False` | false | - | audio satham saves keeps the sound |
| `ambience.disclose_ai` | `True` / `False` | false | - | the opening line says the agent is an AI assistant |
<!-- /controls -->

## Events

Iterate the session, or `await call.recv()`. Every event keeps its message in `.raw`.

| Event | Fields |
| --- | --- |
| `SpeechStarted` / `SpeechStopped` | `turn_id`, `audio_ms`, `continues` |
| `TranscriptPartial` / `TranscriptFinal` | `turn_id`, `text`, `language`, `code_mixed` |
| `ResponseStarted` | `response_id`, `turn_id` (`"greeting"` for the opening line) |
| `ResponseTextDelta` | `response_id`, `text` |
| `ResponseAudio` | `response_id` (`None` between replies), `data` (PCM), `format`, `duration_ms` |
| `ResponseDone` | `response_id`, `text`, `audio_ms`, `metrics` |
| `ResponseInterrupted` | `response_id`, `reason` (`barge_in`, `client_cancel`, `session_closed`) |
| `ToolCall` | `call_id`, `name`, `arguments` (JSON text), `args` (parsed) |
| `SessionUpdated` | `language`, `reason` (`caller`, `reply`, `client`), `ambience` |
| `Error` | `code`, `message`, `fatal` |
| `SessionEnded` | `reason` |

On `SpeechStarted` or `ResponseInterrupted`, drop any agent audio not yet played.

## Background sound

Off unless you set it. With the native protocol the server mixes it into the agent's audio:

```python
async with satham.connect(
    url, api_key, instructions=ROLE, ambience={"sound": "office", "strength": 1.0, "typing": True}
) as call:
    await call.update(ambience={"strength": 0.7})  # or ambience=None: room sound off
```

- **Sounds:** `office`, `call-centre`, `cafe`, `restaurant`, `city`, `static` (`satham.AMBIENCE_SOUNDS`).
- **One scale:** `strength` 1.0 is -35 dBFS RMS, about 16 dB under the voice; a linear gain, so 0.5 is
  6 dB quieter and 2.0 6 dB louder. Typing uses the same scale, capped at `strength`, and starts only once a
  tool has run 0.4 s.
- **Audio between replies.** With a room sound on, audio keeps coming between replies; it has
  `response_id=None`. Play every chunk; a reply still runs from `ResponseStarted` to `ResponseDone`.
  `SessionStarted.ambience` and `SessionUpdated.ambience` say what is in effect.
- **In LiveKit and Pipecat** the framework's own player plays it (`AmbiencePlayer`, `AmbienceMixer`),
  since their playout carries the agent's audio only during replies; the adapters refuse it as a control.
- **On the OpenAI-compatible endpoint** (no server ambience), `satham.TypingCue` times typing from the
  endpoint's events (`feed_openai`), and `satham.typing_sounds()` gives three short CC0 typing takes,
  levelled so their volume is the strength.
- The agent always answers truthfully if asked whether it is an AI (always on); `disclose_ai=True` also
  has it say so in its opening line. Disclosure under your local rules is your responsibility.

## Tools (preview)

Preview: tools need a satham server with tool support (`(await client.info()).get("tools")` is true).

```python
@satham.function_tool
def end_call(reason: str = "the conversation is over") -> None:
    """End the call when the conversation is over. Say a short goodbye in the same turn."""


async with satham.connect(url, api_key, instructions=ROLE, tools=[end_call]) as call:
    async for event in call:
        if isinstance(event, satham.ToolCall) and event.name == "end_call":
            await call.send_tool_result(event, "ended", respond=False)  # no reply wanted
```

`function_tool` builds the JSON schema from the signature and the docstring; `FunctionTool(name,
description, parameters)` or a plain OpenAI-style function definition work too.
`send_tool_result(call, output)` takes a string or any JSON value; with `respond=True` (the default)
the agent replies once every call of that reply has its result.

## Text to speech

kural-1, satham's text-to-speech model, speaks text in satham's voices: `client.audio.speech`, in the
shape of OpenAI's speech API (`POST /v1/audio/speech` on your satham endpoint, with the same key as
calls).

```python
client = satham.Client()  # $SATHAM_URL and $SATHAM_API_KEY, or Client(url, api_key)

speech = await client.audio.speech.create(input="வணக்கம்! நான் மலர்.", voice="malar")
speech.write_to_file("hello.wav")  # speech.content: a WAV file, 24 kHz mono 16-bit

async with client.audio.speech.stream(input=text, voice="naina", response_format="pcm") as audio:
    async for chunk in audio:  # raw PCM, as it is made
        speaker.write(chunk)
```

`create()` returns a `Speech`: `content` (bytes), `content_type` (`audio/wav` or `audio/pcm`),
`sample_rate`, `request_id`, and `write_to_file(path)`. `stream()` asks for the audio as it is made
(`stream: true`): `async with` sends the request (a refusal raises there), each piece arrives as soon
as the server sends it, and leaving the block early cuts the connection, so the server stops. It can
also be iterated without `async with`. A streamed WAV starts with a header whose sizes are
`0xFFFFFFFF` (the length is not known yet), so ask for `pcm` to play as it comes. Both take the same
keywords, and the ones you leave out are not sent:

| Keyword | Values | Default |
| --- | --- | --- |
| `input` | the text, up to 2,000 characters; may hold pause markers and tone tags (below) | required |
| `voice` | `naina`, `dhruv` (Hindi), `malar`, `kathir` (Tamil), `sravya`, `charan` (Telugu), `navya`, `samarth` (Kannada), `brishti`, `ritwik` (Bengali), `mehar`, `harjot` (Punjabi), `tara`, `vikram` (English), or an alias such as `ta-female` | the language's own voice |
| `language` | `hi` `ta` `te` `kn` `bn` `pa` `en` (`ta-IN` is fine): the accent, and how numbers and amounts are read | from the text's script |
| `tone` | `conversational` `happy` `sad` `excited` `professional` `disgusted` `fearful` `neutral` | `conversational` |
| `pace` | `slow` `steady` `fast`: a light nudge, not a rate | none |
| `instructions` | free-text direction for the delivery, up to 500 characters, followed on a best-effort basis; not with `tone` or `pace` | none |
| `breaths` | `True` keeps the breaths the voice takes, `False` trims them | the server's (trimmed) |
| `natural_pauses` | `True` keeps the longer pauses inside a sentence, `False` shortens them | the server's (kept) |
| `variant` | `"natural"`, the voice as it is, or `"warm"`, a warmer, softer sound | natural |
| `response_format` | `wav`, or `pcm` (the samples alone) | `wav` |
| `model` | `kural-1` | `kural-1` |
| `speed` | `1.0` only (use `pace`) | `1.0` |
| `pronunciations` | words respelled for the voice, by language: `{"hi": {"Skyline": "स्काईलाइन"}, "*": {"NAIC": "N A I C"}}` (`*`: every language), up to 100; they win over the dictionary's | none |
| `pronunciation_dictionary_id` | one of your stored dictionaries (below) | none |
| `timeout` | seconds to wait for the answer to begin, and between the pieces of a streamed one | 120 |

A pause marker in `input`, `<break time="0.5s"/>` or `<break time="500ms"/>`, puts exactly that much
silence there (0.1 to 3 seconds each, at most 10 in a request); the voice carries on across it, and
markers don't count towards the 2,000 characters. Any other markup is refused.

```python
await client.audio.speech.create(
    input='आपका ऑर्डर तैयार है। <break time="0.7s"/> धन्यवाद!', tone="happy"
)
```

A tone tag in `input` changes the tone from there until the next tag: one of `SPEECH_TONES`, or
`[calm]` (neutral), `[cheerful]` (happy), `[formal]` (professional), `[friendly]` (conversational),
in any case, at most 20 in a request (`SPEECH_TONE_ALIASES`, `SPEECH_MAX_TAGS`). The text before the
first tag takes `tone`. Tags don't count as characters, can't be combined with `instructions`, and
any other bracketed word (`[laughs]`) is refused: there are no sound effects.

```python
await client.audio.speech.create(input="Your card is blocked. [happy] We've sent a new one!")
```

`client.pronunciation_dictionaries` keeps respellings on the server for your key: `create(name=,
pronunciations=)`, `list()`, `get(id)` (with the entries), `update(id, name=, pronunciations=)`
(merged in; `""` removes a word) and `delete(id)`; up to 10 dictionaries of 500 words each. A request
names one with `pronunciation_dictionary_id=`. Words are matched whole, Latin letters in any case and
Indic scripts exactly as written, the longest first, each place once; the entries of the request's
`language` (else the voice's) apply, with the `*` ones. An unknown id is `InvalidRequestError`
(`unknown_dictionary`) in a speech request, and a `SathamError` with `status=404`
(`dictionary_not_found`) from the dictionaries' own calls.

```python
words = await client.pronunciation_dictionaries.create(
    name="brands", pronunciations={"hi": {"Skyline": "स्काईलाइन"}}
)
await client.audio.speech.create(
    input="Skyline में आपका स्वागत है।", voice="naina", pronunciation_dictionary_id=words.id
)
```

The typed names are in the package: `satham.SpeechTone`, `SpeechPace`, `SpeechLanguage`,
`SpeechVoice`, `SpeechFormat`, and the tuples `SPEECH_TONES`, `SPEECH_PACES`, `SPEECH_LANGUAGES`,
`SPEECH_VOICES`, `SPEECH_FORMATS`. The server checks the values. A refusal raises
`InvalidRequestError` (400 or 413: `.code` says what is wrong, such as `unknown_voice` or
`input_too_long`, and `.param` names the field), `AuthenticationError` (401), `RateLimitError`
(429: the key's limit a minute is used up) or `ServerBusyError` (429: the server is busy), both with
`.retry_after` in seconds; anything else is a `SathamError`: a server error, a network failure, or a
stream the server cut short (`code="incomplete_response"`). Each carries `.status` and
`.request_id`.

`(await client.info())["tts"]` lists a server's models, formats, sample rate, input limit, tones,
paces and languages; `await client.voices()` lists the voices and their aliases. The adapters bring
the same model to LiveKit (`livekit.plugins.satham.TTS`) and Pipecat
(`pipecat_satham.KuralTTSService`).

## Testing your app

`satham.testing.MockServer` is a local stand-in server with a scripted conversation: loud audio is
speech, quiet ends the turn, and `MockTurn(transcript=..., reply=..., language=..., tool_call=...)`
entries answer each turn. `MockServer(controls=False)` behaves as a server without session controls.

```python
from satham.testing import MockServer, MockTurn

async with MockServer(turns=[MockTurn(transcript="hi", reply="Hello!")]) as server:
    call = await satham.connect(server.url, instructions="You are a test agent.")
    await call.send_audio(MockServer.tone(300) + MockServer.silence(300))
```

It answers text to speech too, as the server does: the key check, every refusal, WAV and PCM (a tone
whose length grows with the text), and streamed answers in pieces. `MockSpeech` sets its limits and
timing, and `server.speech_requests` records each request:

```python
from satham.testing import MockServer, MockSpeech

async with MockServer(speech=MockSpeech(queue=0, delay=0.5)) as server:
    ...  # a second request while one is spoken: ServerBusyError
```

`MockSpeech(rate_limit=..., char_limit=...)` gives a key a limit a minute (`RateLimitError`),
`fail_after=` cuts a stream short, and `MockServer(speech=False)` is a server with speech off.
