satham 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
satham/__init__.py ADDED
@@ -0,0 +1,114 @@
1
+ """Satham: an async Python client for the realtime speech-to-speech API (``satham.v1``).
2
+
3
+ import satham
4
+
5
+ async with satham.connect(url, api_key, instructions=role, greeting=hello) as call:
6
+ await call.send_audio(pcm16)
7
+ async for event in call:
8
+ ...
9
+ """
10
+
11
+ from ._protocol import (
12
+ GREETING_MAX_CHARS,
13
+ INSTRUCTIONS_MAX_CHARS,
14
+ LANGUAGES,
15
+ NOT_GIVEN,
16
+ PROTOCOL_VERSION,
17
+ Language,
18
+ LanguageSwitch,
19
+ StartLanguage,
20
+ VoiceOnLanguageSwitch,
21
+ )
22
+ from .client import Client, Session, __version__, connect
23
+ from .controls import (
24
+ CONTROLS,
25
+ BargeIn,
26
+ Control,
27
+ Controls,
28
+ Limits,
29
+ NoiseReduction,
30
+ Phrasing,
31
+ SessionControls,
32
+ Transcription,
33
+ TurnDetection,
34
+ )
35
+ from .errors import (
36
+ AuthenticationError,
37
+ InvalidRequestError,
38
+ SathamError,
39
+ ServerBusyError,
40
+ SessionClosedError,
41
+ )
42
+ from .events import (
43
+ AudioFormat,
44
+ Error,
45
+ Event,
46
+ ResponseAudio,
47
+ ResponseDone,
48
+ ResponseInterrupted,
49
+ ResponseStarted,
50
+ ResponseTextDelta,
51
+ SessionEnded,
52
+ SessionStarted,
53
+ SessionUpdated,
54
+ SpeechStarted,
55
+ SpeechStopped,
56
+ ToolCall,
57
+ TranscriptFinal,
58
+ TranscriptPartial,
59
+ UnknownEvent,
60
+ parse_event,
61
+ )
62
+ from .tools import FunctionTool, function_tool, tool_definitions
63
+
64
+ __all__ = [
65
+ "CONTROLS",
66
+ "GREETING_MAX_CHARS",
67
+ "INSTRUCTIONS_MAX_CHARS",
68
+ "LANGUAGES",
69
+ "NOT_GIVEN",
70
+ "PROTOCOL_VERSION",
71
+ "AudioFormat",
72
+ "AuthenticationError",
73
+ "BargeIn",
74
+ "Client",
75
+ "Control",
76
+ "Controls",
77
+ "Error",
78
+ "Event",
79
+ "FunctionTool",
80
+ "InvalidRequestError",
81
+ "Language",
82
+ "LanguageSwitch",
83
+ "Limits",
84
+ "NoiseReduction",
85
+ "Phrasing",
86
+ "ResponseAudio",
87
+ "ResponseDone",
88
+ "ResponseInterrupted",
89
+ "ResponseStarted",
90
+ "ResponseTextDelta",
91
+ "SathamError",
92
+ "ServerBusyError",
93
+ "Session",
94
+ "SessionClosedError",
95
+ "SessionControls",
96
+ "SessionEnded",
97
+ "SessionStarted",
98
+ "SessionUpdated",
99
+ "SpeechStarted",
100
+ "SpeechStopped",
101
+ "StartLanguage",
102
+ "ToolCall",
103
+ "TranscriptFinal",
104
+ "TranscriptPartial",
105
+ "Transcription",
106
+ "TurnDetection",
107
+ "UnknownEvent",
108
+ "VoiceOnLanguageSwitch",
109
+ "__version__",
110
+ "connect",
111
+ "function_tool",
112
+ "parse_event",
113
+ "tool_definitions",
114
+ ]
satham/_protocol.py ADDED
@@ -0,0 +1,184 @@
1
+ """The ``satham.v1`` wire format: message names, bounds, and the JSON each call sends.
2
+
3
+ Everything that depends on the exact shape of a message lives here, so a protocol change is a
4
+ change to this module only. The bounds below mirror the server's own validation, so that a bad
5
+ setting fails in the client, with the same wording, before it reaches the server.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Mapping, Sequence
11
+ from typing import Any, Final, Literal
12
+
13
+ PROTOCOL_VERSION: Final = "satham.v1"
14
+ REALTIME_PATH: Final = "/v1/realtime"
15
+
16
+ Language = Literal["hi", "ta", "te", "kn", "bn", "pa", "en"]
17
+ StartLanguage = Literal["auto", "hi", "ta", "te", "kn", "bn", "pa", "en"]
18
+ LanguageSwitch = Literal["auto", "off"]
19
+ VoiceOnLanguageSwitch = Literal["keep", "native"]
20
+ Encoding = Literal["pcm_s16le", "pcm_f32le"]
21
+
22
+ LANGUAGES: Final[tuple[str, ...]] = ("hi", "ta", "te", "kn", "bn", "pa", "en")
23
+ LANGUAGE_SWITCHES: Final = ("auto", "off")
24
+ VOICE_SWITCHES: Final = ("keep", "native")
25
+ ENCODINGS: Final = ("pcm_s16le", "pcm_f32le")
26
+ MIN_SAMPLE_RATE: Final = 8_000
27
+ MAX_SAMPLE_RATE: Final = 96_000
28
+
29
+ # The server's length limits today, in characters. Change them here when the server raises them.
30
+ INSTRUCTIONS_MAX_CHARS: Final = 16_000
31
+ GREETING_MAX_CHARS: Final = 1000
32
+ SAY_MAX_CHARS: Final = 4000
33
+ VOICE_MAX_CHARS: Final = 64
34
+ AGENT_MAX_CHARS: Final = 64
35
+ CALL_ID_MAX_CHARS: Final = 128
36
+
37
+ # Client -> server message types.
38
+ SESSION_START: Final = "session.start"
39
+ SESSION_UPDATE: Final = "session.update"
40
+ INPUT_COMMIT: Final = "input.commit"
41
+ RESPONSE_CANCEL: Final = "response.cancel"
42
+ RESPONSE_CREATE: Final = "response.create" # a reply now, optionally guided by instructions
43
+ RESPONSE_SAY: Final = "response.say" # these words, spoken as they are
44
+ SESSION_END: Final = "session.end"
45
+ # Tool calling: the server announces a call with ``response.function_call``; the client answers
46
+ # with ``tool.result``.
47
+ TOOL_RESULT: Final = "tool.result"
48
+ FUNCTION_CALL: Final = "response.function_call"
49
+ MAX_TOOLS: Final = 128
50
+
51
+
52
+ class _NotGiven:
53
+ """A setting left as it is (distinct from ``None``, which sends ``null``)."""
54
+
55
+ _instance: _NotGiven | None = None
56
+
57
+ def __new__(cls) -> _NotGiven:
58
+ if cls._instance is None:
59
+ cls._instance = super().__new__(cls)
60
+ return cls._instance
61
+
62
+ def __repr__(self) -> str:
63
+ return "NOT_GIVEN"
64
+
65
+ def __bool__(self) -> bool:
66
+ return False
67
+
68
+
69
+ NOT_GIVEN: Final = _NotGiven()
70
+
71
+
72
+ def _check_text(value: object, field: str, low: int, high: int) -> str:
73
+ if not isinstance(value, str):
74
+ raise ValueError(f"{field}: Input should be a valid string")
75
+ if len(value) < low:
76
+ raise ValueError(f"{field}: String should have at least {low} character{'s' * (low != 1)}")
77
+ if len(value) > high:
78
+ raise ValueError(f"{field}: String should have at most {high} characters")
79
+ return value
80
+
81
+
82
+ def _check_choice(value: object, field: str, choices: Sequence[str]) -> str:
83
+ if value not in choices:
84
+ quoted = ", ".join(f"'{c}'" for c in choices[:-1]) + f" or '{choices[-1]}'"
85
+ raise ValueError(f"{field}: Input should be {quoted}")
86
+ return str(value)
87
+
88
+
89
+ def _check_switch(value: object, field: str) -> bool | None:
90
+ if value is not None and not isinstance(value, bool):
91
+ raise ValueError(f"{field}: Input should be a valid boolean")
92
+ return value
93
+
94
+
95
+ def audio_format(encoding: str, sample_rate: int, channels: int) -> dict[str, Any]:
96
+ _check_choice(encoding, "input_audio.encoding", ENCODINGS)
97
+ if not isinstance(sample_rate, int) or isinstance(sample_rate, bool):
98
+ raise ValueError("input_audio.sample_rate: Input should be a valid integer")
99
+ if sample_rate < MIN_SAMPLE_RATE:
100
+ raise ValueError(
101
+ f"input_audio.sample_rate: Input should be greater than or equal to {MIN_SAMPLE_RATE}"
102
+ )
103
+ if sample_rate > MAX_SAMPLE_RATE:
104
+ raise ValueError(
105
+ f"input_audio.sample_rate: Input should be less than or equal to {MAX_SAMPLE_RATE}"
106
+ )
107
+ if channels not in (1, 2):
108
+ raise ValueError("input_audio.channels: Input should be 1 or 2")
109
+ return {"encoding": encoding, "sample_rate": sample_rate, "channels": channels}
110
+
111
+
112
+ def session_start(
113
+ fields: Mapping[str, Any],
114
+ *,
115
+ input_audio: Mapping[str, Any],
116
+ tools: Sequence[Mapping[str, Any]] | None = None,
117
+ tool_choice: str | Mapping[str, Any] | None = None,
118
+ ) -> dict[str, Any]:
119
+ """The ``session.start`` message: the checked controls, the audio format, the tools."""
120
+ message: dict[str, Any] = {
121
+ "type": SESSION_START,
122
+ "protocol": PROTOCOL_VERSION,
123
+ "language": "auto",
124
+ }
125
+ message.update(fields)
126
+ message["input_audio"] = dict(input_audio)
127
+ if tools:
128
+ message["tools"] = _check_tools(tools, "session.start.tools")
129
+ if tool_choice is not None:
130
+ message["tool_choice"] = tool_choice
131
+ return message
132
+
133
+
134
+ def _check_tools(tools: Sequence[Mapping[str, Any]], field: str) -> list[dict[str, Any]]:
135
+ if len(tools) > MAX_TOOLS:
136
+ raise ValueError(f"{field}: List should have at most {MAX_TOOLS} items")
137
+ return [dict(t) for t in tools]
138
+
139
+
140
+ def session_update(
141
+ fields: Mapping[str, Any],
142
+ *,
143
+ tools: Sequence[Mapping[str, Any]] | _NotGiven = NOT_GIVEN,
144
+ tool_choice: object = NOT_GIVEN,
145
+ ) -> dict[str, Any] | None:
146
+ """The ``session.update`` message naming only the given fields, or ``None`` if none is."""
147
+ if fields.get("language") == "auto":
148
+ raise ValueError(
149
+ "session.update.language: Input should be 'hi', 'ta', 'te', 'kn', 'bn', 'pa' or 'en'"
150
+ )
151
+ message: dict[str, Any] = {"type": SESSION_UPDATE, **fields}
152
+ if not isinstance(tools, _NotGiven):
153
+ message["tools"] = _check_tools(tools, "session.update.tools")
154
+ if tool_choice is not NOT_GIVEN:
155
+ message["tool_choice"] = tool_choice
156
+ return message if len(message) > 1 else None
157
+
158
+
159
+ def response_create(instructions: str | None = None) -> dict[str, Any]:
160
+ """Ask for a reply now; ``instructions`` guide this reply alone."""
161
+ message: dict[str, Any] = {"type": RESPONSE_CREATE}
162
+ if instructions is not None:
163
+ message["instructions"] = _check_text(
164
+ instructions, "response.create.instructions", 1, INSTRUCTIONS_MAX_CHARS
165
+ )
166
+ return message
167
+
168
+
169
+ def response_say(text: str) -> dict[str, Any]:
170
+ """Have the agent say ``text`` as it is, in the call's voice."""
171
+ return {"type": RESPONSE_SAY, "text": _check_text(text, "response.say.text", 1, SAY_MAX_CHARS)}
172
+
173
+
174
+ def tool_result(call_id: str, output: str, *, respond: bool = True) -> dict[str, Any]:
175
+ """The client's answer to a tool call.
176
+
177
+ With ``respond`` (the default) the agent replies once every call of that response has its
178
+ result; ``respond=False`` only records it (a call that ends or transfers the call).
179
+ """
180
+ _check_text(call_id, "tool.result.call_id", 1, CALL_ID_MAX_CHARS)
181
+ message: dict[str, Any] = {"type": TOOL_RESULT, "call_id": call_id, "output": output}
182
+ if not respond:
183
+ message["respond"] = False
184
+ return message