pipecat-satham 0.1.0__tar.gz

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.
@@ -0,0 +1,3 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ dist/
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,191 @@
1
+ Metadata-Version: 2.4
2
+ Name: pipecat-satham
3
+ Version: 0.1.0
4
+ Summary: Satham realtime speech-to-speech service for Pipecat
5
+ Project-URL: Homepage, https://satham.ai
6
+ Author: Satham
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Keywords: pipecat,pipecat-ai,realtime,satham,speech-to-speech,voice-agent
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Framework :: AsyncIO
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.11
23
+ Requires-Dist: pipecat-ai~=1.16.0
24
+ Requires-Dist: satham~=0.1.0
25
+ Description-Content-Type: text/markdown
26
+
27
+ # pipecat-satham
28
+
29
+ Satham's realtime speech-to-speech model (satham-1) as a Pipecat service. `SathamRealtimeLLMService`
30
+ stands in for STT, LLM and TTS: your context brings the agent's instructions and tools, and Satham
31
+ hears the caller, ends turns, replies in speech and handles barge-in.
32
+
33
+ Pipecat 1.16; Python 3.11+. (Pipecat runs only in Python, so there is no Node version.)
34
+
35
+ ```sh
36
+ pip install pipecat-satham
37
+ ```
38
+
39
+ ## Use
40
+
41
+ You pass your Satham endpoint and API key (or set `SATHAM_URL` and `SATHAM_API_KEY`); there is no
42
+ default server.
43
+
44
+ ```python
45
+ import os
46
+
47
+ from pipecat.frames.frames import LLMRunFrame
48
+ from pipecat.pipeline.pipeline import Pipeline
49
+ from pipecat.pipeline.worker import PipelineParams, PipelineWorker
50
+ from pipecat.processors.aggregators.llm_context import LLMContext
51
+ from pipecat.processors.aggregators.llm_response_universal import LLMContextAggregatorPair
52
+
53
+ from pipecat_satham import SathamRealtimeLLMService
54
+
55
+ llm = SathamRealtimeLLMService(
56
+ url=os.environ["SATHAM_URL"],
57
+ api_key=os.environ["SATHAM_API_KEY"],
58
+ greeting="Hello, this is Asha from Example Homes. Is this a good time?",
59
+ language="en",
60
+ language_switch="auto",
61
+ )
62
+ # The context's system message is the call's instructions.
63
+ context = LLMContext(
64
+ [{"role": "system", "content": "You are Asha, who books site visits for Example Homes."}]
65
+ )
66
+ user, assistant = LLMContextAggregatorPair(context)
67
+ pipeline = Pipeline([transport.input(), user, llm, transport.output(), assistant])
68
+ worker = PipelineWorker(pipeline, params=PipelineParams(audio_in_sample_rate=16_000))
69
+
70
+
71
+ @transport.event_handler("on_client_connected")
72
+ async def on_connected(transport, client):
73
+ await worker.queue_frames([LLMRunFrame()]) # starts the call; the agent greets
74
+ ```
75
+
76
+ - **The call starts with the first `LLMContextFrame` (or `LLMRunFrame`)**, as with any Pipecat
77
+ realtime service, and the agent speaks first: the `greeting` if there is one, else a reply from its
78
+ instructions. The context's system message is the call's instructions (or pass `instructions=`),
79
+ and the context's tools join the service's. Caller audio before the call starts is dropped.
80
+ - **Audio** goes in as 16 kHz mono; the agent's speech comes out as `TTSAudioRawFrame`s between
81
+ `TTSStartedFrame` and `TTSStoppedFrame`, with its words as `TTSTextFrame`s.
82
+ - **Turns and interruptions.** Satham's speech start and stop become proposed user turns, which the
83
+ context aggregator's external turn strategies turn into user turns and interruptions. An
84
+ interruption from anywhere else in the pipeline cancels the agent's reply.
85
+ - **Transcripts** go upstream as `InterimTranscriptionFrame` / `TranscriptionFrame`; both sides of the
86
+ conversation land in the `LLMContext`.
87
+ - **`modalities=["text"]`** sends the agent's words as `LLMTextFrame`s for a TTS service of your own;
88
+ **`turn_detection=None`** leaves turns to the pipeline's VAD and turn strategies (each
89
+ `UserStoppedSpeakingFrame` ends the caller's turn).
90
+
91
+ ## Controls
92
+
93
+ Every keyword of the constructor besides `url`, `api_key`, `instructions`, `tools`, `tool_choice`,
94
+ `connect_timeout` and `start_audio_paused` is a control; other keywords go to Pipecat's `LLMService`.
95
+ Mid-call, `await llm.update_options(...)` changes any control, as does an `LLMUpdateSettingsFrame`
96
+ with `SathamRealtimeLLMService.Settings(controls={...})` (its `temperature`, `top_p` and `max_tokens`
97
+ map to Satham's). Controls you leave out are not sent; values are checked against these ranges, or the
98
+ server's from `GET /v1/info`.
99
+
100
+ The controls marked "needs session controls" need a Satham server with session controls (its
101
+ `GET /v1/info` lists `controls`, as the server does since 2026-11-16); an older server refuses them
102
+ when the call starts. `greeting` and `agent` belong to the start of a call. Setting
103
+ `input_audio_noise_reduction`'s `mode` alone resets `strength_db` to that mode's preset, so send both
104
+ to keep a custom strength; `None` leaves noise reduction at the server's default (on), and `"none"`
105
+ turns it off. `agent` is an optional
106
+ preset on the server and is not needed.
107
+
108
+ <!-- controls -->
109
+ | Option | Range | Default | OpenAI equivalent | Notes |
110
+ | --- | --- | --- | --- | --- |
111
+ | `instructions` | text, up to 16000 characters | none | - | the agent's role; from the LiveKit agent or Pipecat context in the adapters |
112
+ | `greeting` | text, up to 1000 characters | none | - | said first; without one the caller speaks first |
113
+ | `tools` | up to 128 functions | none | - | preview: needs a server with tool support |
114
+ | `tool_choice` | see notes | "auto" | `tool_choice` | "auto", "none", "required" or one function |
115
+ | `agent` | text, up to 64 characters | none | - | optional: a preset agent on the server, such as a demo's |
116
+ | `model` | text, up to 64 characters | "satham-1" | `model` | "satham-1" only today; needs session controls |
117
+ | `modalities` | list | ["audio", "text"] | `modalities` | ["audio", "text"], ["audio"], or ["text"]: words only, for your own TTS; needs session controls |
118
+ | `language` | `auto`, `hi`, `ta`, `te`, `kn`, `bn`, `pa`, `en` | "auto" | - | |
119
+ | `language_switch` | `auto`, `off`, or `None` | "auto" | - | |
120
+ | `voice_on_language_switch` | `keep`, `native`, or `None` | "keep" | - | |
121
+ | `turn_detection.enabled` | `True` / `False` | true | `turn_detection=None` | false (or turn_detection=None): the client ends each turn; needs session controls |
122
+ | `turn_detection.type` | `server_vad`, `semantic_vad` | "server_vad" | `turn_detection.type` | needs session controls |
123
+ | `turn_detection.threshold` | 0.1 to 0.95 | 0.5 | `turn_detection.threshold` | the speech detector's threshold; needs session controls |
124
+ | `turn_detection.eagerness` | `auto`, `low`, `medium`, `high` | "auto" | `turn_detection.eagerness` | semantic_vad's end-of-turn wait; needs session controls |
125
+ | `turn_detection.prefix_padding_ms` | 0 to 1000 | 300 | `turn_detection.prefix_padding_ms` | needs session controls |
126
+ | `turn_detection.min_speech_ms` | 50 to 1000 | 100 | - | needs session controls |
127
+ | `turn_detection.silence_duration_ms` | 150 to 2000 | 350 | `turn_detection.silence_duration_ms` | server_vad's end-of-turn wait; needs session controls |
128
+ | `turn_detection.create_response` | `True` / `False` | true | `turn_detection.create_response` | answer each turn at once; needs session controls |
129
+ | `turn_detection.interrupt_response` | `True` / `False` | true | `turn_detection.interrupt_response` | barge-in on or off; needs session controls |
130
+ | `turn_detection.barge_in.min_speech_ms` | 0 to 2000 | 400 | - | needs session controls |
131
+ | `turn_detection.barge_in.min_probability` | 0 to 1 | 0.8 | - | needs session controls |
132
+ | `turn_detection.barge_in.min_dbfs` | -90 to 0, or `None` | -40 | - | needs session controls |
133
+ | `turn_detection.continue_within_ms` | 0 to 5000, or `None` | 2000 | - | the caller carrying on in the same turn; null: off; needs session controls |
134
+ | `turn_detection.continue_max_heard_ms` | 0 to 5000 | 1000 | - | needs session controls |
135
+ | `input_audio_noise_reduction.enabled` | `True` / `False` | true | `input_audio_noise_reduction={"type": "none"}` | false, "none" or {"type": "none"}: off; needs session controls |
136
+ | `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 |
137
+ | `input_audio_noise_reduction.strength_db` | 0 to 100 | 12 | - | needs session controls |
138
+ | `input_audio_noise_reduction.apply_to_transcription` | `True` / `False` | false | - | needs session controls |
139
+ | `input_audio_transcription.enabled` | `True` / `False` | true | `input_audio_transcription=None` | transcript events to the client; needs session controls |
140
+ | `input_audio_transcription.code_mixed` | `True` / `False` | true | - | English words in Latin script, and digits; needs session controls |
141
+ | `voice` | text, up to 64 characters | the language's | `voice` | |
142
+ | `breaths` | `True` / `False`, or `None` | off | - | |
143
+ | `natural_pauses` | `True` / `False`, or `None` | off | - | |
144
+ | `continuation` | `True` / `False`, or `None` | true | - | each phrase carries on from the one before; needs session controls |
145
+ | `speed` | 1 to 1 | 1.0 | `speed` | 1.0 only today; needs session controls |
146
+ | `phrasing.first_phrase_max_chars` | 1 to 120 | 120 | - | at least min_phrase_chars; needs session controls |
147
+ | `phrasing.min_phrase_chars` | 1 to 120 | 20 | - | needs session controls |
148
+ | `normalise_numbers` | `True` / `False` | true | - | numbers and amounts said as words; needs session controls |
149
+ | `pronunciations` | word to respelling | none | - | {word: respelling}, up to 200; needs session controls |
150
+ | `temperature` | 0.6 to 1.2 | 0.7 | `temperature` | needs session controls |
151
+ | `top_p` | 0.05 to 1 | 0.8 | - | needs session controls |
152
+ | `max_response_output_tokens` | 1 to 4096 | 320 | `max_response_output_tokens` | or "inf"; never above the server's; needs session controls |
153
+ | `tone` | `auto`, `conversational`, `happy`, `sad`, `excited`, `professional` | "auto" | - | "auto": the model picks; needs session controls |
154
+ | `repeat_guard` | `True` / `False` | true | - | re-asks a reply that repeats a recent one; needs session controls |
155
+ | `drift_guard` | `True` / `False` | true | - | keeps replies in the call's language; needs session controls |
156
+ <!-- /controls -->
157
+
158
+ ## Tools (preview)
159
+
160
+ Preview: tools need a Satham server with tool support.
161
+
162
+ ```python
163
+ from pipecat.adapters.llm.schemas.function_schema import FunctionSchema
164
+ from pipecat.adapters.llm.schemas.tools_schema import ToolsSchema
165
+ from pipecat.frames.frames import EndTaskFrame, FunctionCallResultProperties
166
+ from pipecat.processors.frame_processor import FrameDirection
167
+
168
+ END_CALL = FunctionSchema(
169
+ name="end_call",
170
+ description="End the call when the conversation is over. Say a short goodbye in the same turn.",
171
+ properties={"reason": {"type": "string"}},
172
+ required=[],
173
+ )
174
+
175
+
176
+ async def end_call(params):
177
+ await params.result_callback("ended", properties=FunctionCallResultProperties(run_llm=False))
178
+ await params.llm.push_frame(EndTaskFrame(), FrameDirection.UPSTREAM)
179
+
180
+
181
+ llm = SathamRealtimeLLMService(..., tools=ToolsSchema(standard_tools=[END_CALL]))
182
+ llm.register_function("end_call", end_call)
183
+ ```
184
+
185
+ Each call the agent makes runs the handler registered with `register_function`; the agent replies to
186
+ its result unless the result carries `FunctionCallResultProperties(run_llm=False)`. A cancelled call
187
+ is answered with `CANCELLED` and no reply. `LLMSetToolsFrame` replaces the tools mid-call.
188
+
189
+ Event handlers: `on_session_updated(service, event)` when the call's language changes, and
190
+ `on_server_event(service, event)` for every Satham event. Not supported: `LLMMessagesAppendFrame`
191
+ (Satham keeps the conversation itself).
@@ -0,0 +1,165 @@
1
+ # pipecat-satham
2
+
3
+ Satham's realtime speech-to-speech model (satham-1) as a Pipecat service. `SathamRealtimeLLMService`
4
+ stands in for STT, LLM and TTS: your context brings the agent's instructions and tools, and Satham
5
+ hears the caller, ends turns, replies in speech and handles barge-in.
6
+
7
+ Pipecat 1.16; Python 3.11+. (Pipecat runs only in Python, so there is no Node version.)
8
+
9
+ ```sh
10
+ pip install pipecat-satham
11
+ ```
12
+
13
+ ## Use
14
+
15
+ You pass your Satham endpoint and API key (or set `SATHAM_URL` and `SATHAM_API_KEY`); there is no
16
+ default server.
17
+
18
+ ```python
19
+ import os
20
+
21
+ from pipecat.frames.frames import LLMRunFrame
22
+ from pipecat.pipeline.pipeline import Pipeline
23
+ from pipecat.pipeline.worker import PipelineParams, PipelineWorker
24
+ from pipecat.processors.aggregators.llm_context import LLMContext
25
+ from pipecat.processors.aggregators.llm_response_universal import LLMContextAggregatorPair
26
+
27
+ from pipecat_satham import SathamRealtimeLLMService
28
+
29
+ llm = SathamRealtimeLLMService(
30
+ url=os.environ["SATHAM_URL"],
31
+ api_key=os.environ["SATHAM_API_KEY"],
32
+ greeting="Hello, this is Asha from Example Homes. Is this a good time?",
33
+ language="en",
34
+ language_switch="auto",
35
+ )
36
+ # The context's system message is the call's instructions.
37
+ context = LLMContext(
38
+ [{"role": "system", "content": "You are Asha, who books site visits for Example Homes."}]
39
+ )
40
+ user, assistant = LLMContextAggregatorPair(context)
41
+ pipeline = Pipeline([transport.input(), user, llm, transport.output(), assistant])
42
+ worker = PipelineWorker(pipeline, params=PipelineParams(audio_in_sample_rate=16_000))
43
+
44
+
45
+ @transport.event_handler("on_client_connected")
46
+ async def on_connected(transport, client):
47
+ await worker.queue_frames([LLMRunFrame()]) # starts the call; the agent greets
48
+ ```
49
+
50
+ - **The call starts with the first `LLMContextFrame` (or `LLMRunFrame`)**, as with any Pipecat
51
+ realtime service, and the agent speaks first: the `greeting` if there is one, else a reply from its
52
+ instructions. The context's system message is the call's instructions (or pass `instructions=`),
53
+ and the context's tools join the service's. Caller audio before the call starts is dropped.
54
+ - **Audio** goes in as 16 kHz mono; the agent's speech comes out as `TTSAudioRawFrame`s between
55
+ `TTSStartedFrame` and `TTSStoppedFrame`, with its words as `TTSTextFrame`s.
56
+ - **Turns and interruptions.** Satham's speech start and stop become proposed user turns, which the
57
+ context aggregator's external turn strategies turn into user turns and interruptions. An
58
+ interruption from anywhere else in the pipeline cancels the agent's reply.
59
+ - **Transcripts** go upstream as `InterimTranscriptionFrame` / `TranscriptionFrame`; both sides of the
60
+ conversation land in the `LLMContext`.
61
+ - **`modalities=["text"]`** sends the agent's words as `LLMTextFrame`s for a TTS service of your own;
62
+ **`turn_detection=None`** leaves turns to the pipeline's VAD and turn strategies (each
63
+ `UserStoppedSpeakingFrame` ends the caller's turn).
64
+
65
+ ## Controls
66
+
67
+ Every keyword of the constructor besides `url`, `api_key`, `instructions`, `tools`, `tool_choice`,
68
+ `connect_timeout` and `start_audio_paused` is a control; other keywords go to Pipecat's `LLMService`.
69
+ Mid-call, `await llm.update_options(...)` changes any control, as does an `LLMUpdateSettingsFrame`
70
+ with `SathamRealtimeLLMService.Settings(controls={...})` (its `temperature`, `top_p` and `max_tokens`
71
+ map to Satham's). Controls you leave out are not sent; values are checked against these ranges, or the
72
+ server's from `GET /v1/info`.
73
+
74
+ The controls marked "needs session controls" need a Satham server with session controls (its
75
+ `GET /v1/info` lists `controls`, as the server does since 2026-11-16); an older server refuses them
76
+ when the call starts. `greeting` and `agent` belong to the start of a call. Setting
77
+ `input_audio_noise_reduction`'s `mode` alone resets `strength_db` to that mode's preset, so send both
78
+ to keep a custom strength; `None` leaves noise reduction at the server's default (on), and `"none"`
79
+ turns it off. `agent` is an optional
80
+ preset on the server and is not needed.
81
+
82
+ <!-- controls -->
83
+ | Option | Range | Default | OpenAI equivalent | Notes |
84
+ | --- | --- | --- | --- | --- |
85
+ | `instructions` | text, up to 16000 characters | none | - | the agent's role; from the LiveKit agent or Pipecat context in the adapters |
86
+ | `greeting` | text, up to 1000 characters | none | - | said first; without one the caller speaks first |
87
+ | `tools` | up to 128 functions | none | - | preview: needs a server with tool support |
88
+ | `tool_choice` | see notes | "auto" | `tool_choice` | "auto", "none", "required" or one function |
89
+ | `agent` | text, up to 64 characters | none | - | optional: a preset agent on the server, such as a demo's |
90
+ | `model` | text, up to 64 characters | "satham-1" | `model` | "satham-1" only today; needs session controls |
91
+ | `modalities` | list | ["audio", "text"] | `modalities` | ["audio", "text"], ["audio"], or ["text"]: words only, for your own TTS; needs session controls |
92
+ | `language` | `auto`, `hi`, `ta`, `te`, `kn`, `bn`, `pa`, `en` | "auto" | - | |
93
+ | `language_switch` | `auto`, `off`, or `None` | "auto" | - | |
94
+ | `voice_on_language_switch` | `keep`, `native`, or `None` | "keep" | - | |
95
+ | `turn_detection.enabled` | `True` / `False` | true | `turn_detection=None` | false (or turn_detection=None): the client ends each turn; needs session controls |
96
+ | `turn_detection.type` | `server_vad`, `semantic_vad` | "server_vad" | `turn_detection.type` | needs session controls |
97
+ | `turn_detection.threshold` | 0.1 to 0.95 | 0.5 | `turn_detection.threshold` | the speech detector's threshold; needs session controls |
98
+ | `turn_detection.eagerness` | `auto`, `low`, `medium`, `high` | "auto" | `turn_detection.eagerness` | semantic_vad's end-of-turn wait; needs session controls |
99
+ | `turn_detection.prefix_padding_ms` | 0 to 1000 | 300 | `turn_detection.prefix_padding_ms` | needs session controls |
100
+ | `turn_detection.min_speech_ms` | 50 to 1000 | 100 | - | needs session controls |
101
+ | `turn_detection.silence_duration_ms` | 150 to 2000 | 350 | `turn_detection.silence_duration_ms` | server_vad's end-of-turn wait; needs session controls |
102
+ | `turn_detection.create_response` | `True` / `False` | true | `turn_detection.create_response` | answer each turn at once; needs session controls |
103
+ | `turn_detection.interrupt_response` | `True` / `False` | true | `turn_detection.interrupt_response` | barge-in on or off; needs session controls |
104
+ | `turn_detection.barge_in.min_speech_ms` | 0 to 2000 | 400 | - | needs session controls |
105
+ | `turn_detection.barge_in.min_probability` | 0 to 1 | 0.8 | - | needs session controls |
106
+ | `turn_detection.barge_in.min_dbfs` | -90 to 0, or `None` | -40 | - | needs session controls |
107
+ | `turn_detection.continue_within_ms` | 0 to 5000, or `None` | 2000 | - | the caller carrying on in the same turn; null: off; needs session controls |
108
+ | `turn_detection.continue_max_heard_ms` | 0 to 5000 | 1000 | - | needs session controls |
109
+ | `input_audio_noise_reduction.enabled` | `True` / `False` | true | `input_audio_noise_reduction={"type": "none"}` | false, "none" or {"type": "none"}: off; needs session controls |
110
+ | `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 |
111
+ | `input_audio_noise_reduction.strength_db` | 0 to 100 | 12 | - | needs session controls |
112
+ | `input_audio_noise_reduction.apply_to_transcription` | `True` / `False` | false | - | needs session controls |
113
+ | `input_audio_transcription.enabled` | `True` / `False` | true | `input_audio_transcription=None` | transcript events to the client; needs session controls |
114
+ | `input_audio_transcription.code_mixed` | `True` / `False` | true | - | English words in Latin script, and digits; needs session controls |
115
+ | `voice` | text, up to 64 characters | the language's | `voice` | |
116
+ | `breaths` | `True` / `False`, or `None` | off | - | |
117
+ | `natural_pauses` | `True` / `False`, or `None` | off | - | |
118
+ | `continuation` | `True` / `False`, or `None` | true | - | each phrase carries on from the one before; needs session controls |
119
+ | `speed` | 1 to 1 | 1.0 | `speed` | 1.0 only today; needs session controls |
120
+ | `phrasing.first_phrase_max_chars` | 1 to 120 | 120 | - | at least min_phrase_chars; needs session controls |
121
+ | `phrasing.min_phrase_chars` | 1 to 120 | 20 | - | needs session controls |
122
+ | `normalise_numbers` | `True` / `False` | true | - | numbers and amounts said as words; needs session controls |
123
+ | `pronunciations` | word to respelling | none | - | {word: respelling}, up to 200; needs session controls |
124
+ | `temperature` | 0.6 to 1.2 | 0.7 | `temperature` | needs session controls |
125
+ | `top_p` | 0.05 to 1 | 0.8 | - | needs session controls |
126
+ | `max_response_output_tokens` | 1 to 4096 | 320 | `max_response_output_tokens` | or "inf"; never above the server's; needs session controls |
127
+ | `tone` | `auto`, `conversational`, `happy`, `sad`, `excited`, `professional` | "auto" | - | "auto": the model picks; needs session controls |
128
+ | `repeat_guard` | `True` / `False` | true | - | re-asks a reply that repeats a recent one; needs session controls |
129
+ | `drift_guard` | `True` / `False` | true | - | keeps replies in the call's language; needs session controls |
130
+ <!-- /controls -->
131
+
132
+ ## Tools (preview)
133
+
134
+ Preview: tools need a Satham server with tool support.
135
+
136
+ ```python
137
+ from pipecat.adapters.llm.schemas.function_schema import FunctionSchema
138
+ from pipecat.adapters.llm.schemas.tools_schema import ToolsSchema
139
+ from pipecat.frames.frames import EndTaskFrame, FunctionCallResultProperties
140
+ from pipecat.processors.frame_processor import FrameDirection
141
+
142
+ END_CALL = FunctionSchema(
143
+ name="end_call",
144
+ description="End the call when the conversation is over. Say a short goodbye in the same turn.",
145
+ properties={"reason": {"type": "string"}},
146
+ required=[],
147
+ )
148
+
149
+
150
+ async def end_call(params):
151
+ await params.result_callback("ended", properties=FunctionCallResultProperties(run_llm=False))
152
+ await params.llm.push_frame(EndTaskFrame(), FrameDirection.UPSTREAM)
153
+
154
+
155
+ llm = SathamRealtimeLLMService(..., tools=ToolsSchema(standard_tools=[END_CALL]))
156
+ llm.register_function("end_call", end_call)
157
+ ```
158
+
159
+ Each call the agent makes runs the handler registered with `register_function`; the agent replies to
160
+ its result unless the result carries `FunctionCallResultProperties(run_llm=False)`. A cancelled call
161
+ is answered with `CANCELLED` and no reply. `LLMSetToolsFrame` replaces the tools mid-call.
162
+
163
+ Event handlers: `on_session_updated(service, event)` when the call's language changes, and
164
+ `on_server_event(service, event)` for every Satham event. Not supported: `LLMMessagesAppendFrame`
165
+ (Satham keeps the conversation itself).
@@ -0,0 +1,38 @@
1
+ [project]
2
+ name = "pipecat-satham"
3
+ version = "0.1.0"
4
+ description = "Satham realtime speech-to-speech service for Pipecat"
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "Satham" }]
10
+ keywords = ["satham", "pipecat", "pipecat-ai", "voice-agent", "speech-to-speech", "realtime"]
11
+ classifiers = [
12
+ "Development Status :: 3 - Alpha",
13
+ "Intended Audience :: Developers",
14
+ "Operating System :: OS Independent",
15
+ "Framework :: AsyncIO",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3 :: Only",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Topic :: Multimedia :: Sound/Audio :: Speech",
21
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
22
+ "Topic :: Software Development :: Libraries :: Python Modules",
23
+ "Typing :: Typed",
24
+ ]
25
+ dependencies = ["satham~=0.1.0", "pipecat-ai~=1.16.0"]
26
+
27
+ [project.urls]
28
+ Homepage = "https://satham.ai"
29
+
30
+ [build-system]
31
+ requires = ["hatchling==1.27.0"]
32
+ build-backend = "hatchling.build"
33
+
34
+ [tool.hatch.build.targets.wheel]
35
+ packages = ["src/pipecat_satham"]
36
+
37
+ [tool.hatch.build.targets.sdist]
38
+ include = ["src/pipecat_satham", "README.md", "LICENSE"]
@@ -0,0 +1,16 @@
1
+ """Satham speech-to-speech (satham-1) for Pipecat.
2
+
3
+ from pipecat_satham import SathamRealtimeLLMService
4
+
5
+ llm = SathamRealtimeLLMService(greeting="Hello!") # the role: the context's system message
6
+ """
7
+
8
+ from .service import INPUT_SAMPLE_RATE, SathamRealtimeLLMService, SathamRealtimeLLMSettings
9
+
10
+ __version__ = "0.1.0"
11
+ __all__ = [
12
+ "INPUT_SAMPLE_RATE",
13
+ "SathamRealtimeLLMService",
14
+ "SathamRealtimeLLMSettings",
15
+ "__version__",
16
+ ]
File without changes
@@ -0,0 +1,556 @@
1
+ """Satham's speech-to-speech model as a Pipecat service.
2
+
3
+ ``SathamRealtimeLLMService`` takes the place of STT, LLM and TTS in a pipeline, in the shape of
4
+ Pipecat's ``OpenAIRealtimeLLMService``: caller audio in (``InputAudioRawFrame``), the agent's
5
+ audio out (``TTSAudioRawFrame``, between ``TTSStartedFrame`` and ``TTSStoppedFrame``), its words
6
+ as ``LLMTextFrame`` and ``TTSTextFrame``, and the caller's words as ``TranscriptionFrame``
7
+ (upstream, for the context aggregator).
8
+
9
+ Satham detects turns and barge-in on the server. Its ``input.speech_started`` and
10
+ ``input.speech_stopped`` become ``ProposedUserStarted/StoppedSpeakingFrame``, which the context
11
+ aggregator's external turn strategies turn into user turns and interruptions, so the transport
12
+ stops playing the agent as soon as the caller speaks.
13
+
14
+ A call starts with the first ``LLMContextFrame`` (queue an ``LLMRunFrame`` when the caller
15
+ joins, as with any Pipecat realtime service). The context's system message is the call's
16
+ instructions (unless ``instructions`` is given), and its tools join the service's; the agent then
17
+ speaks first: the ``greeting`` if there is one, else a reply from its instructions
18
+ (``response.create``). Tool calls run the handlers registered with
19
+ ``register_function``; their results go back as ``tool.result``, and the server replies unless
20
+ the result asks for no reply (``FunctionCallResultProperties(run_llm=False)``).
21
+
22
+ Every other setting is a control (``satham.Controls``), with OpenAI's names where they exist.
23
+ ``modalities=["text"]`` sends the agent's words downstream as ``LLMTextFrame``s for a TTS service
24
+ of your own; ``turn_detection=None`` leaves turns to the pipeline (its VAD and turn strategies),
25
+ and each ``UserStoppedSpeakingFrame`` ends the caller's turn.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import contextlib
31
+ import json
32
+ from dataclasses import dataclass, field
33
+ from typing import Any, Unpack
34
+
35
+ from loguru import logger
36
+ from pipecat.adapters.llm.schemas.tools_schema import ToolsSchema
37
+ from pipecat.audio.utils import create_stream_resampler
38
+ from pipecat.frames.frames import (
39
+ CancelFrame,
40
+ EndFrame,
41
+ Frame,
42
+ FunctionCallCancelFrame,
43
+ FunctionCallFromLLM,
44
+ FunctionCallResultFrame,
45
+ InputAudioRawFrame,
46
+ InterimTranscriptionFrame,
47
+ InterruptionFrame,
48
+ LLMContextFrame,
49
+ LLMFullResponseEndFrame,
50
+ LLMFullResponseStartFrame,
51
+ LLMMessagesAppendFrame,
52
+ LLMRunFrame,
53
+ LLMServiceMetadataFrame,
54
+ LLMSetToolsFrame,
55
+ LLMTextFrame,
56
+ ProposedUserStartedSpeakingFrame,
57
+ ProposedUserStoppedSpeakingFrame,
58
+ StartFrame,
59
+ TextType,
60
+ TranscriptionFrame,
61
+ TTSAudioRawFrame,
62
+ TTSStartedFrame,
63
+ TTSStoppedFrame,
64
+ TTSTextFrame,
65
+ UserStoppedSpeakingFrame,
66
+ )
67
+ from pipecat.processors.aggregators.llm_context import LLMContext
68
+ from pipecat.processors.frame_processor import FrameDirection
69
+ from pipecat.services.llm_service import LLMService
70
+ from pipecat.services.settings import LLMSettings
71
+ from pipecat.transcriptions.language import Language
72
+ from pipecat.turns.user_turn_strategies import ExternalUserTurnStrategies
73
+ from pipecat.utils.time import time_now_iso8601
74
+ from pipecat.utils.types import NOT_GIVEN, NotGiven, is_given
75
+ from satham.controls import to_wire
76
+
77
+ import satham
78
+ from satham import _protocol as wire
79
+
80
+ INPUT_SAMPLE_RATE = 16_000
81
+ """Caller audio goes to Satham as 16 kHz mono 16-bit PCM."""
82
+
83
+ _FROM_LLM_SETTINGS = {
84
+ "temperature": "temperature",
85
+ "top_p": "top_p",
86
+ "max_tokens": "max_response_output_tokens",
87
+ }
88
+
89
+
90
+ @dataclass
91
+ class SathamRealtimeLLMSettings(LLMSettings):
92
+ """The settings a running call can change (``LLMUpdateSettingsFrame``, ``session.update``).
93
+
94
+ Parameters:
95
+ controls: any of Satham's controls (``satham.Controls``), e.g. ``{"speed": 1.1,
96
+ "turn_detection": {"silence_duration_ms": 500}}``; only the given ones change.
97
+
98
+ The common ``temperature``, ``top_p`` and ``max_tokens`` map to Satham's ``temperature``,
99
+ ``top_p`` and ``max_response_output_tokens``.
100
+ """
101
+
102
+ controls: dict[str, Any] | NotGiven = field(default_factory=lambda: NOT_GIVEN)
103
+
104
+
105
+ def _tool_dicts(tools: ToolsSchema | list[Any] | NotGiven | None) -> list[dict[str, Any]]:
106
+ """Pipecat tools as OpenAI function definitions."""
107
+ if not is_given(tools) or tools is None:
108
+ return []
109
+ if isinstance(tools, ToolsSchema):
110
+ return [{"type": "function", "function": t.to_default_dict()} for t in tools.standard_tools]
111
+ out: list[dict[str, Any]] = []
112
+ for tool in tools:
113
+ if hasattr(tool, "to_default_dict"):
114
+ out.append({"type": "function", "function": tool.to_default_dict()})
115
+ elif isinstance(tool, dict):
116
+ out.append(tool)
117
+ return out
118
+
119
+
120
+ def _language(code: str | None) -> Language | None:
121
+ try:
122
+ return Language(code) if code else None
123
+ except ValueError:
124
+ return None
125
+
126
+
127
+ class SathamRealtimeLLMService(LLMService):
128
+ """Satham (satham-1) speech-to-speech for Pipecat pipelines.
129
+
130
+ Args:
131
+ url: your Satham endpoint (``wss://...`` or ``https://...``); ``$SATHAM_URL``.
132
+ api_key: your API key; ``$SATHAM_API_KEY``.
133
+ instructions: the agent's role; by default, the context's system message.
134
+ greeting: the opening line; without one the agent opens with a reply of its own.
135
+ language: ``"auto"`` or one of ``hi ta te kn bn pa en``.
136
+ voice: a named voice, ``"default"``, or a cloned voice's id.
137
+ breaths: keep the voice's breaths.
138
+ natural_pauses: keep the voice's longer pauses inside a phrase.
139
+ language_switch: ``"auto"`` or ``"off"``.
140
+ voice_on_language_switch: ``"keep"`` or ``"native"``.
141
+ tools: functions the agent may call, beside the context's (``ToolsSchema`` or a list).
142
+ tool_choice: ``"auto"``, ``"none"``, ``"required"``, or one function as
143
+ ``{"type": "function", "name": ...}``.
144
+ connect_timeout: seconds to wait for the call to start.
145
+ start_audio_paused: drop caller audio until ``set_audio_input_paused(False)``.
146
+ agent: optional, a preset agent on the server (such as a demo's).
147
+
148
+ Event handlers: ``on_session_updated(service, event)`` when the call's language changes
149
+ (``event`` is a ``satham.SessionUpdated``), ``on_server_event(service, event)`` for every
150
+ Satham event.
151
+ """
152
+
153
+ Settings = SathamRealtimeLLMSettings
154
+ _settings: SathamRealtimeLLMSettings
155
+
156
+ def __init__(
157
+ self,
158
+ *,
159
+ url: str | None = None,
160
+ api_key: str | None = None,
161
+ instructions: str | None = None,
162
+ tools: ToolsSchema | list[Any] | None = None,
163
+ tool_choice: str | dict[str, Any] | None = None,
164
+ connect_timeout: float = 10.0,
165
+ start_audio_paused: bool = False,
166
+ settings: SathamRealtimeLLMSettings | None = None,
167
+ **controls: Unpack[satham.Controls],
168
+ ) -> None:
169
+ defaults = SathamRealtimeLLMSettings(
170
+ model=str(controls.get("model") or "satham-1"),
171
+ system_instruction=instructions,
172
+ temperature=None,
173
+ max_tokens=None,
174
+ top_p=None,
175
+ top_k=None,
176
+ frequency_penalty=None,
177
+ presence_penalty=None,
178
+ seed=None,
179
+ filter_incomplete_user_turns=False,
180
+ user_turn_completion_config=None,
181
+ controls={},
182
+ )
183
+ if settings is not None:
184
+ defaults.apply_update(settings)
185
+ # Keywords that are not Satham controls go to Pipecat's LLMService (run_in_parallel, ...).
186
+ known = satham.Controls.__optional_keys__ | satham.Controls.__required_keys__
187
+ service_kwargs = {k: v for k, v in controls.items() if k not in known}
188
+ super().__init__(settings=defaults, **service_kwargs)
189
+ self._client = satham.Client(url, api_key, open_timeout=connect_timeout)
190
+ self._controls: dict[str, Any] = {k: v for k, v in controls.items() if k in known}
191
+ # Check the controls now, not when the first call starts.
192
+ to_wire(self._controls, where="session.start", limits=self._client.limits)
193
+ self._tools = tools
194
+ self._tool_choice = tool_choice
195
+ self._text_only = list(self._controls.get("modalities") or ["text", "audio"]) == ["text"]
196
+ turns = self._controls.get("turn_detection", {})
197
+ turns = turns.model_dump(exclude_none=True) if hasattr(turns, "model_dump") else turns
198
+ self._manual_turns = "turn_detection" in self._controls and (
199
+ turns is None or (isinstance(turns, dict) and turns.get("enabled") is False)
200
+ )
201
+ self._audio_paused = start_audio_paused
202
+ self._resampler = create_stream_resampler()
203
+ self._context: LLMContext | None = None
204
+ self._call: satham.Session | None = None
205
+ self._starting = False
206
+ self._receive_task: Any = None
207
+ self._response_id: str | None = None
208
+ self._audio_started = False
209
+ self._interrupted_by_server = False
210
+ self._barged_in = False
211
+ self._proposed = 0
212
+ self._spoken_over: str | None = None
213
+ self._open_calls: set[str] = set()
214
+ language = self._controls.get("language")
215
+ self.language: str | None = None if language in (None, "auto") else str(language)
216
+ self._register_event_handler("on_session_updated")
217
+ self._register_event_handler("on_server_event")
218
+
219
+ # -- Pipecat hooks -----------------------------------------------------------------------
220
+
221
+ def can_generate_metrics(self) -> bool:
222
+ return True
223
+
224
+ def service_metadata_frame(self) -> LLMServiceMetadataFrame:
225
+ return LLMServiceMetadataFrame(
226
+ service_name=self.name,
227
+ is_realtime_service=True,
228
+ # With manual turns the pipeline's own VAD and turn strategies decide.
229
+ user_turn_strategies=None if self._manual_turns else ExternalUserTurnStrategies(),
230
+ )
231
+
232
+ def _service_tools(self) -> ToolsSchema | list[Any] | None:
233
+ return self._tools
234
+
235
+ def set_audio_input_paused(self, paused: bool) -> None:
236
+ self._audio_paused = paused
237
+
238
+ @property
239
+ def call(self) -> satham.Session | None:
240
+ """The underlying ``satham.Session``, once the call has started."""
241
+ return self._call
242
+
243
+ async def start(self, frame: StartFrame) -> None:
244
+ await super().start(frame)
245
+
246
+ async def stop(self, frame: EndFrame) -> None:
247
+ await super().stop(frame)
248
+ await self._end_call()
249
+
250
+ async def cancel(self, frame: CancelFrame) -> None:
251
+ await super().cancel(frame)
252
+ await self._end_call()
253
+
254
+ async def cleanup(self) -> None:
255
+ await super().cleanup()
256
+ await self._end_call()
257
+
258
+ async def process_frame(self, frame: Frame, direction: FrameDirection) -> None:
259
+ await super().process_frame(frame, direction)
260
+ if isinstance(frame, LLMContextFrame):
261
+ self._context = frame.context
262
+ await self._start_call()
263
+ elif isinstance(frame, LLMRunFrame):
264
+ await self._start_call()
265
+ elif isinstance(frame, InputAudioRawFrame):
266
+ if not self._audio_paused:
267
+ await self._send_user_audio(frame)
268
+ elif isinstance(frame, InterruptionFrame):
269
+ await self._handle_interruption()
270
+ elif isinstance(frame, UserStoppedSpeakingFrame) and self._manual_turns:
271
+ await self._send({"type": wire.INPUT_COMMIT}) # the pipeline ended the caller's turn
272
+ elif isinstance(frame, LLMSetToolsFrame):
273
+ self._sync_registered_tool_handlers(frame.tools)
274
+ self._tools = frame.tools
275
+ await self._send({"type": wire.SESSION_UPDATE, "tools": self._all_tools()})
276
+ elif isinstance(frame, LLMMessagesAppendFrame):
277
+ logger.warning(
278
+ f"{self}: Satham keeps the conversation itself; appended messages are ignored"
279
+ )
280
+ await self.push_frame(frame, direction)
281
+
282
+ async def push_frame(
283
+ self, frame: Frame, direction: FrameDirection = FrameDirection.DOWNSTREAM
284
+ ) -> None:
285
+ if direction == FrameDirection.DOWNSTREAM:
286
+ if isinstance(frame, FunctionCallResultFrame):
287
+ await self._send_tool_result(frame)
288
+ elif (
289
+ isinstance(frame, FunctionCallCancelFrame)
290
+ and frame.tool_call_id in self._open_calls
291
+ ):
292
+ self._open_calls.discard(frame.tool_call_id)
293
+ await self._send(wire.tool_result(frame.tool_call_id, "CANCELLED", respond=False))
294
+ await super().push_frame(frame, direction)
295
+
296
+ async def _update_settings(self, delta: LLMSettings) -> dict[str, Any]:
297
+ changed = await super()._update_settings(delta)
298
+ changes: dict[str, Any] = {}
299
+ if "controls" in changed and is_given(getattr(delta, "controls", NOT_GIVEN)):
300
+ changes.update(delta.controls)
301
+ for name, control in _FROM_LLM_SETTINGS.items():
302
+ if name in changed:
303
+ changes[control] = getattr(self._settings, name)
304
+ if changes:
305
+ await self.update_options(**changes)
306
+ return changed
307
+
308
+ async def update_options(self, **changes: Unpack[satham.Controls]) -> None:
309
+ """Change the call's controls (``session.update``); before it starts, its start."""
310
+ fields = to_wire(dict(changes), where="session.update", limits=self._client.limits)
311
+ if self._call is None:
312
+ self._controls.update(changes)
313
+ return
314
+ message = wire.session_update(fields)
315
+ if message is not None:
316
+ await self._send(message)
317
+ if changes.get("language") not in (None, "auto"):
318
+ self.language = str(changes["language"])
319
+
320
+ # -- the call ----------------------------------------------------------------------------
321
+
322
+ def _all_tools(self) -> list[dict[str, Any]]:
323
+ tools = {
324
+ t["function"]["name"] if "function" in t else t["name"]: t
325
+ for t in _tool_dicts(self._tools)
326
+ }
327
+ if self._context is not None:
328
+ for tool in _tool_dicts(self._context.tools):
329
+ name = tool["function"]["name"] if "function" in tool else tool["name"]
330
+ tools.setdefault(name, tool)
331
+ return list(tools.values())
332
+
333
+ def _context_instructions(self) -> str | None:
334
+ if self._context is None:
335
+ return None
336
+ for message in self._context.get_messages():
337
+ if isinstance(message, dict) and message.get("role") in ("system", "developer"):
338
+ content = message.get("content")
339
+ if isinstance(content, str) and content.strip():
340
+ return content
341
+ if isinstance(content, list):
342
+ text = " ".join(p.get("text", "") for p in content if isinstance(p, dict))
343
+ if text.strip():
344
+ return text
345
+ return None
346
+
347
+ async def _start_call(self) -> None:
348
+ if self._call is not None or self._starting:
349
+ return
350
+ self._starting = True
351
+ system = self._settings.system_instruction
352
+ instructions = (system if is_given(system) else None) or self._context_instructions()
353
+ tools = self._all_tools()
354
+ try:
355
+ with contextlib.suppress(satham.SathamError):
356
+ await self._client.load_controls() # the server's ranges, when it lists them
357
+ self._call = await self._client.connect(
358
+ **self._controls,
359
+ instructions=instructions,
360
+ sample_rate=INPUT_SAMPLE_RATE,
361
+ tools=tools or None,
362
+ tool_choice=self._tool_choice if tools else None,
363
+ )
364
+ except (satham.SathamError, ValueError) as e:
365
+ await self.push_error(error_msg=f"Satham: {e}", exception=e, fatal=True)
366
+ return
367
+ finally:
368
+ self._starting = False
369
+ if self._call.language:
370
+ self.language = self._call.language
371
+ self._receive_task = self.create_task(self._receive(self._call), name="satham-receive")
372
+ if "greeting" not in self._controls and "agent" not in self._controls:
373
+ # As with Pipecat's OpenAI realtime service, the run frame has the agent speak first.
374
+ await self._send(wire.response_create())
375
+
376
+ async def _end_call(self) -> None:
377
+ call, self._call = self._call, None
378
+ if call is not None:
379
+ await call.close()
380
+ if self._receive_task is not None:
381
+ await self.cancel_task(self._receive_task, timeout=1.0)
382
+ self._receive_task = None
383
+
384
+ async def _send(self, message: dict[str, Any]) -> None:
385
+ if self._call is None:
386
+ return
387
+ with contextlib.suppress(satham.SessionClosedError):
388
+ await self._call.send(message)
389
+
390
+ async def _send_user_audio(self, frame: InputAudioRawFrame) -> None:
391
+ if self._call is None:
392
+ return # no call yet: the caller has not been put through
393
+ audio = frame.audio
394
+ if frame.num_channels == 2:
395
+ samples = memoryview(audio).cast("h")
396
+ audio = b"".join(
397
+ ((samples[i] + samples[i + 1]) // 2).to_bytes(2, "little", signed=True)
398
+ for i in range(0, len(samples) - 1, 2)
399
+ )
400
+ if frame.sample_rate != INPUT_SAMPLE_RATE:
401
+ audio = await self._resampler.resample(audio, frame.sample_rate, INPUT_SAMPLE_RATE)
402
+ if audio:
403
+ with contextlib.suppress(satham.SessionClosedError):
404
+ await self._call.send_audio(audio)
405
+
406
+ async def _send_tool_result(self, frame: FunctionCallResultFrame) -> None:
407
+ if frame.tool_call_id not in self._open_calls:
408
+ return
409
+ if frame.properties is not None and not frame.properties.is_final:
410
+ return # Satham takes one result per call: the final one
411
+ self._open_calls.discard(frame.tool_call_id)
412
+ run_llm = frame.run_llm
413
+ if run_llm is None and frame.properties is not None:
414
+ run_llm = frame.properties.run_llm
415
+ result = frame.result
416
+ if frame.error:
417
+ output = f"error: {frame.error}"
418
+ elif result is None or isinstance(result, str):
419
+ output = result or ""
420
+ else:
421
+ output = json.dumps(result, ensure_ascii=False, default=str)
422
+ await self._send(wire.tool_result(frame.tool_call_id, output, respond=run_llm is not False))
423
+
424
+ async def _handle_interruption(self) -> None:
425
+ if self._proposed:
426
+ # The interruption that the caller's speech (proposed by this service) brought
427
+ # about: the server has stopped the reply already. A reply started since then is
428
+ # the answer to that speech, and plays on.
429
+ self._proposed -= 1
430
+ if self._response_id is not None and self._response_id == self._spoken_over:
431
+ await self._end_response()
432
+ return
433
+ if self._response_id is None:
434
+ return
435
+ if not self._interrupted_by_server:
436
+ await self._send({"type": wire.RESPONSE_CANCEL})
437
+ await self._end_response()
438
+
439
+ async def _propose_user_turn(self) -> None:
440
+ self._proposed += 1
441
+ self._spoken_over = self._response_id
442
+ await self.broadcast_frame(ProposedUserStartedSpeakingFrame)
443
+
444
+ async def _end_response(self) -> None:
445
+ if self._response_id is None:
446
+ return
447
+ self._response_id = None
448
+ await self.stop_all_metrics()
449
+ if self._audio_started:
450
+ self._audio_started = False
451
+ await self.push_frame(TTSStoppedFrame())
452
+ await self.push_frame(LLMFullResponseEndFrame())
453
+
454
+ # -- server events -----------------------------------------------------------------------
455
+
456
+ async def _receive(self, call: satham.Session) -> None:
457
+ async for event in call:
458
+ await self._call_event_handler("on_server_event", event)
459
+ await self._on_event(event)
460
+ if self._call is call:
461
+ reason = call.end_reason or f"connection closed ({call.close_code})"
462
+ logger.info(f"{self}: the Satham call ended: {reason}")
463
+
464
+ async def _on_event(self, event: satham.Event) -> None:
465
+ if isinstance(event, satham.ResponseAudio):
466
+ if self._text_only or event.response_id != self._response_id or not event.data:
467
+ return
468
+ if not self._audio_started:
469
+ self._audio_started = True
470
+ await self.stop_ttfb_metrics()
471
+ await self.push_frame(TTSStartedFrame())
472
+ fmt = event.format
473
+ await self.push_frame(
474
+ TTSAudioRawFrame(
475
+ audio=event.data, sample_rate=fmt.sample_rate, num_channels=fmt.channels
476
+ )
477
+ )
478
+ elif isinstance(event, satham.ResponseTextDelta):
479
+ if event.response_id == self._response_id and event.text and self._text_only:
480
+ await self.push_frame(LLMTextFrame(event.text)) # for the pipeline's own TTS
481
+ elif event.response_id == self._response_id and event.text:
482
+ text = LLMTextFrame(event.text)
483
+ text.append_to_context = False
484
+ await self.push_frame(text)
485
+ spoken = TTSTextFrame(event.text, text_type=TextType.SENTENCE)
486
+ spoken.includes_inter_frame_spaces = True
487
+ await self.push_frame(spoken)
488
+ elif isinstance(event, satham.SpeechStarted):
489
+ if self._barged_in:
490
+ self._barged_in = False # already proposed when the reply was cut off
491
+ else:
492
+ await self._propose_user_turn()
493
+ elif isinstance(event, satham.SpeechStopped):
494
+ await self.start_processing_metrics()
495
+ await self.start_ttfb_metrics()
496
+ await self.broadcast_frame(ProposedUserStoppedSpeakingFrame)
497
+ elif isinstance(event, satham.TranscriptPartial):
498
+ await self.push_frame(
499
+ InterimTranscriptionFrame(
500
+ event.text, "", time_now_iso8601(), _language(event.language), result=event.raw
501
+ ),
502
+ FrameDirection.UPSTREAM,
503
+ )
504
+ elif isinstance(event, satham.TranscriptFinal):
505
+ if event.text:
506
+ await self.push_frame(
507
+ TranscriptionFrame(
508
+ event.text,
509
+ "",
510
+ time_now_iso8601(),
511
+ _language(event.language),
512
+ result=event.raw,
513
+ ),
514
+ FrameDirection.UPSTREAM,
515
+ )
516
+ elif isinstance(event, satham.ResponseStarted):
517
+ await self._end_response()
518
+ self._response_id = event.response_id
519
+ self._interrupted_by_server = False
520
+ await self.push_frame(LLMFullResponseStartFrame())
521
+ elif isinstance(event, satham.ResponseDone):
522
+ if event.response_id == self._response_id:
523
+ await self._end_response()
524
+ elif isinstance(event, satham.ResponseInterrupted):
525
+ if event.response_id == self._response_id:
526
+ self._interrupted_by_server = True
527
+ if event.reason == "barge_in":
528
+ # The caller is speaking; propose the turn now, while the reply is still
529
+ # open, so the interruption reaches the transport before more audio does.
530
+ self._barged_in = True
531
+ await self._propose_user_turn()
532
+ await self._end_response()
533
+ elif isinstance(event, satham.ToolCall):
534
+ self._open_calls.add(event.call_id)
535
+ try:
536
+ arguments = event.args
537
+ except ValueError:
538
+ arguments = {}
539
+ await self.run_function_calls(
540
+ [
541
+ FunctionCallFromLLM(
542
+ function_name=event.name,
543
+ tool_call_id=event.call_id,
544
+ arguments=arguments,
545
+ context=self._context or LLMContext(),
546
+ )
547
+ ]
548
+ )
549
+ elif isinstance(event, satham.SessionUpdated):
550
+ if event.language:
551
+ self.language = event.language
552
+ await self._call_event_handler("on_session_updated", event)
553
+ elif isinstance(event, satham.Error):
554
+ await self.push_error(
555
+ error_msg=f"Satham {event.code}: {event.message}", fatal=event.fatal
556
+ )