dtelecom-agents 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.
@@ -0,0 +1,64 @@
1
+ """Streaming voice agents for dTelecom rooms."""
2
+
3
+ from .agent import VoiceAgent
4
+ from .conversation import BargeIn, ContextManager, SentenceSplitter, TurnDetector
5
+ from .pipeline import Pipeline
6
+ from .providers.speech import BaseSTTStream
7
+ from .room import AudioInput, AudioOutput, RoomConnection
8
+ from .types import (
9
+ AgentState,
10
+ AgentTool,
11
+ AudioSink,
12
+ LLMChatOptions,
13
+ LLMChunk,
14
+ LLMPlugin,
15
+ Message,
16
+ RespondMode,
17
+ SpeechEvent,
18
+ STTPartialEnd,
19
+ STTPlugin,
20
+ STTReady,
21
+ STTStream,
22
+ Tool,
23
+ ToolCallResult,
24
+ ToolContext,
25
+ ToolDefinition,
26
+ ToolHandler,
27
+ TranscriptionResult,
28
+ TTSPlugin,
29
+ TurnMetrics,
30
+ )
31
+
32
+ __all__ = [
33
+ "AgentState",
34
+ "AgentTool",
35
+ "AudioInput",
36
+ "AudioOutput",
37
+ "AudioSink",
38
+ "BargeIn",
39
+ "BaseSTTStream",
40
+ "ContextManager",
41
+ "LLMChatOptions",
42
+ "LLMChunk",
43
+ "LLMPlugin",
44
+ "Message",
45
+ "Pipeline",
46
+ "RespondMode",
47
+ "RoomConnection",
48
+ "STTPartialEnd",
49
+ "STTPlugin",
50
+ "STTReady",
51
+ "STTStream",
52
+ "SentenceSplitter",
53
+ "SpeechEvent",
54
+ "TTSPlugin",
55
+ "Tool",
56
+ "ToolCallResult",
57
+ "ToolContext",
58
+ "ToolDefinition",
59
+ "ToolHandler",
60
+ "TranscriptionResult",
61
+ "TurnDetector",
62
+ "TurnMetrics",
63
+ "VoiceAgent",
64
+ ]
@@ -0,0 +1,275 @@
1
+ """Standalone dTelecom room voice agent."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import inspect
7
+ from collections.abc import Awaitable, Callable, Sequence
8
+ from pathlib import Path
9
+ from typing import TYPE_CHECKING
10
+
11
+ from .types import LLMPlugin, RespondMode, STTPlugin, Tool, TTSPlugin
12
+
13
+ if TYPE_CHECKING:
14
+ from dtelecom_rtc import Room
15
+ from dtelecom_server import CloudClient
16
+
17
+ from .memory import MemoryConfig, RoomMemory
18
+
19
+ from .pipeline import Events, Pipeline
20
+ from .room import AudioInput, AudioOutput, RoomConnection
21
+
22
+
23
+ class VoiceAgent(Events):
24
+ def __init__(
25
+ self,
26
+ *,
27
+ stt: STTPlugin,
28
+ llm: LLMPlugin,
29
+ instructions: str,
30
+ tts: TTSPlugin | None = None,
31
+ on_data_message: Callable[[bytes, str, str | None], None | Awaitable[None]]
32
+ | None = None,
33
+ memory: RoomMemory | MemoryConfig | None = None,
34
+ respond_mode: RespondMode = "always",
35
+ agent_name: str = "assistant",
36
+ name_variants: Sequence[str] = (),
37
+ before_respond: Callable[[str, str], bool | Awaitable[bool]] | None = None,
38
+ tools: Sequence[Tool] = (),
39
+ max_context_tokens: int = 5000,
40
+ ):
41
+ super().__init__()
42
+ self.stt, self.tts, self.llm = stt, tts, llm
43
+ self.instructions = instructions
44
+ self.on_data_message = on_data_message
45
+ self._memory_config = memory
46
+ self.memory = None
47
+ if respond_mode not in ("always", "addressed") or max_context_tokens < 1:
48
+ raise ValueError("Invalid response mode or context budget")
49
+ self.options = dict(
50
+ respond_mode=respond_mode,
51
+ agent_name=agent_name,
52
+ name_variants=name_variants,
53
+ before_respond=before_respond,
54
+ tools=tools,
55
+ max_context_tokens=max_context_tokens,
56
+ )
57
+ self.running = False
58
+ self.connection = None
59
+ self.pipeline: Pipeline | None = None
60
+ self.audio_output = None
61
+ self._source = None
62
+ self._tracks: dict[str, tuple[object, asyncio.Task]] = {}
63
+ self._track_lock = asyncio.Lock()
64
+ self._dump_dir: Path | None = None
65
+ self._stopping = False
66
+
67
+ @property
68
+ def room(self) -> Room | None:
69
+ return self.connection.room if self.connection else None
70
+
71
+ def enable_audio_dump(self, directory: str | Path):
72
+ self._dump_dir = Path(directory)
73
+ if self.audio_output:
74
+ self.audio_output.dump_dir = self._dump_dir
75
+
76
+ def _link_grant(self, session_id):
77
+ for provider in (self.stt, self.tts):
78
+ if link := getattr(provider, "set_webrtc_session_id", None):
79
+ link(session_id)
80
+
81
+ async def start(
82
+ self,
83
+ room: str,
84
+ *,
85
+ cloud: CloudClient | None = None,
86
+ token: str | None = None,
87
+ ws_url: str | None = None,
88
+ fallback_urls: Sequence[str] = (),
89
+ identity: str = "agent",
90
+ name: str | None = None,
91
+ api_key: str | None = None,
92
+ api_secret: str | None = None,
93
+ ttl: str | float = "6h",
94
+ ) -> None:
95
+ from dtelecom_rtc import AudioSource
96
+
97
+ if self.connection:
98
+ raise RuntimeError("Agent is already active")
99
+ from .memory import MemoryConfig, RoomMemory
100
+
101
+ if isinstance(self._memory_config, MemoryConfig):
102
+ if self._memory_config.enabled:
103
+ self.memory = RoomMemory(
104
+ self._memory_config.scope or room, self._memory_config.db_path
105
+ )
106
+ else:
107
+ self.memory = self._memory_config
108
+ self.connection = RoomConnection()
109
+ self._source = AudioSource(sample_rate=48000, channels=1)
110
+ self.audio_output = AudioOutput(self._source)
111
+ self.audio_output.dump_dir = self._dump_dir
112
+ self.pipeline = Pipeline(
113
+ stt=self.stt,
114
+ llm=self.llm,
115
+ instructions=self.instructions,
116
+ tts=self.tts,
117
+ memory=self.memory,
118
+ audio_output=self.audio_output,
119
+ **self.options,
120
+ )
121
+ for event in (
122
+ "transcription",
123
+ "transcription_partial",
124
+ "partial_end",
125
+ "stt_ready",
126
+ "sentence",
127
+ "response",
128
+ "agent_state",
129
+ "interrupted",
130
+ "tool_call",
131
+ "metrics",
132
+ "error",
133
+ ):
134
+ self.pipeline.on(event, lambda *args, key=event: self.emit(key, *args))
135
+ self.room.on("track_subscribed", self._subscribed)
136
+ self.room.on("track_unsubscribed", self._unsubscribed)
137
+ self.room.on("participant_disconnected", self._departed)
138
+ self.room.on("reconnected", self._reconcile_recognizers)
139
+ self.room.on("data_received", self._data)
140
+ self.room.on("disconnected", self._disconnected)
141
+ self.running = True
142
+ try:
143
+ await self.connection.connect(
144
+ room,
145
+ cloud=cloud,
146
+ token=token,
147
+ ws_url=ws_url,
148
+ fallback_urls=fallback_urls,
149
+ identity=identity,
150
+ name=name,
151
+ ttl=ttl,
152
+ api_key=api_key,
153
+ api_secret=api_secret,
154
+ on_grant=self._link_grant,
155
+ on_error=lambda exc: self.emit("error", exc),
156
+ )
157
+ if self.tts:
158
+ await self.room.publish_audio("agent-voice", self._source)
159
+ self.pipeline.warmup()
160
+ await self.emit("connected")
161
+ except BaseException:
162
+ await self.stop()
163
+ raise
164
+
165
+ async def _subscribed(self, track, publication, participant):
166
+ key = participant.identity
167
+ async with self._track_lock:
168
+ if not self.running:
169
+ return
170
+ if key in self._tracks:
171
+ old_track, old_task = self._tracks[key]
172
+ if old_track is track:
173
+ return
174
+ old_task.cancel()
175
+ await asyncio.gather(old_task, return_exceptions=True)
176
+ try:
177
+ stream = await self.pipeline.add_participant(key)
178
+ except Exception as exc:
179
+ await self.emit("error", exc)
180
+ return
181
+
182
+ async def forward():
183
+ try:
184
+ await AudioInput.pipe(track, stream)
185
+ except Exception as exc:
186
+ if self.running:
187
+ await self.emit("error", exc)
188
+
189
+ self._tracks[key] = (track, asyncio.create_task(forward()))
190
+
191
+ async def _unsubscribed(self, track, publication, participant):
192
+ async with self._track_lock:
193
+ entry = self._tracks.get(participant.identity)
194
+ if entry and entry[0] is track:
195
+ self._tracks.pop(participant.identity)
196
+ entry[1].cancel()
197
+ await asyncio.gather(entry[1], return_exceptions=True)
198
+
199
+ async def _departed(self, participant):
200
+ async with self._track_lock:
201
+ room = self.room
202
+ if not self.running or room is None or not room.is_connected:
203
+ return
204
+ # A local full rejoin clears its old roster. Keep an authenticated
205
+ # recognizer across that change until the new roster is available.
206
+ if room.participant_by_identity(participant.identity) is None:
207
+ await self.pipeline.remove_participant(participant.identity)
208
+
209
+ async def _reconcile_recognizers(self):
210
+ async with self._track_lock:
211
+ room = self.room
212
+ if not self.running or room is None or not room.is_connected:
213
+ return
214
+ identities = {p.identity for p in room.remote_participants.values()}
215
+ for identity in tuple(self.pipeline.streams):
216
+ if identity not in identities:
217
+ await self.pipeline.remove_participant(identity)
218
+
219
+ async def _data(self, payload, participant, kind, topic):
220
+ if self.running and self.on_data_message:
221
+ result = self.on_data_message(
222
+ payload, participant.identity if participant else "", topic
223
+ )
224
+ if inspect.isawaitable(result):
225
+ await result
226
+
227
+ async def _disconnected(self, reason=None):
228
+ if self.running and not self._stopping:
229
+ await self.stop(reason)
230
+
231
+ async def say(self, text):
232
+ if self.pipeline:
233
+ await self.pipeline.say(text)
234
+
235
+ async def say_ssml(self, document, display_text):
236
+ if self.pipeline:
237
+ await self.pipeline.say(display_text, ssml=document)
238
+
239
+ async def set_stt_language(self, language, *, force_whisper=False):
240
+ if self.pipeline:
241
+ await self.pipeline.set_stt_language(language, force_whisper=force_whisper)
242
+
243
+ async def stop(self, reason=None):
244
+ if not self.connection or self._stopping:
245
+ return
246
+ self._stopping, self.running = True, False
247
+ try:
248
+ async with self._track_lock:
249
+ readers = [task for _, task in self._tracks.values()]
250
+ self._tracks.clear()
251
+ for reader in readers:
252
+ reader.cancel()
253
+ await asyncio.gather(*readers, return_exceptions=True)
254
+ if self.pipeline:
255
+ await self.pipeline.stop()
256
+ if close := getattr(self.tts, "close", None):
257
+ await close()
258
+ if self.memory:
259
+ try:
260
+ await self.memory.end_session(self.llm)
261
+ finally:
262
+ await self.memory.close()
263
+ finally:
264
+ try:
265
+ await self.connection.close()
266
+ finally:
267
+ if self._source:
268
+ self._source.close()
269
+ if self.audio_output:
270
+ self.audio_output.clear()
271
+ self.connection = self.pipeline = self.audio_output = self._source = (
272
+ None
273
+ )
274
+ self._stopping = False
275
+ await self.emit("disconnected", reason)
@@ -0,0 +1,192 @@
1
+ """Conversation primitives adapted from dTelecom agents-js, Apache-2.0."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import re
8
+ from collections.abc import Callable
9
+ from contextlib import aclosing
10
+
11
+ from .types import LLMChatOptions, LLMPlugin, Message, ToolCallResult
12
+
13
+
14
+ class SentenceSplitter:
15
+ _end = re.compile(r"""[.!?؟]+["'”’»)\]]*\s+|[。!?।]+["'”’」』))]*\s*""")
16
+ _short = frozenset("e.g i.e etc vs mr mrs ms dr prof st approx inc ltd u.s".split())
17
+
18
+ def __init__(self) -> None:
19
+ self.buffer = ""
20
+
21
+ def push(self, token: str) -> list[str]:
22
+ self.buffer += token
23
+ chunks = []
24
+ while self.buffer:
25
+ end = self._boundary()
26
+ if end is None:
27
+ break
28
+ chunks.append(self.buffer[:end].strip())
29
+ self.buffer = self.buffer[end:]
30
+ return chunks
31
+
32
+ def _boundary(self) -> int | None:
33
+ for match in self._end.finditer(self.buffer):
34
+ if self.buffer[match.start()] == ".":
35
+ word = re.search(r"([\w.]+)$", self.buffer[: match.start()])
36
+ if word and word[1].lower() in self._short:
37
+ continue
38
+ if len(self.buffer[: match.end()].strip()) >= 20:
39
+ return match.end()
40
+ if len(self.buffer) >= 250:
41
+ clause = re.search(r"[,;:—]\s*", self.buffer)
42
+ if clause and clause.start() >= 20:
43
+ return clause.end()
44
+ space = self.buffer.rfind(" ", 0, 251)
45
+ if space >= 20:
46
+ return space + 1
47
+ return None
48
+
49
+ def flush(self) -> str:
50
+ text, self.buffer = self.buffer.strip(), ""
51
+ return text
52
+
53
+ def reset(self) -> None:
54
+ self.buffer = ""
55
+
56
+
57
+ class ContextManager:
58
+ def __init__(
59
+ self,
60
+ instructions: str,
61
+ max_context_tokens: int = 5000,
62
+ recent_turns_to_keep: int = 4,
63
+ ):
64
+ if max_context_tokens <= 0 or recent_turns_to_keep < 1:
65
+ raise ValueError("Expected a positive context budget and recent turn count")
66
+ self.instructions = instructions
67
+ self.budget = max_context_tokens
68
+ self.recent = recent_turns_to_keep
69
+ self.turns: list[list[Message]] = []
70
+ self.summary = ""
71
+ self._generation = 0
72
+
73
+ def add_user_turn(self, speaker: str, text: str) -> None:
74
+ self.turns.append([{"role": "user", "content": f"[{speaker}]: {text}"}])
75
+
76
+ def add_agent_turn(self, text: str) -> None:
77
+ self.turns.append([{"role": "assistant", "content": text}])
78
+
79
+ def add_tool_exchange(
80
+ self, content: str, results: list[tuple[ToolCallResult, str]]
81
+ ) -> None:
82
+ group: list[Message] = [
83
+ {
84
+ "role": "assistant",
85
+ "content": content or None,
86
+ "tool_calls": [call.to_wire() for call, _ in results],
87
+ }
88
+ ]
89
+ group.extend(
90
+ {"role": "tool", "tool_call_id": call.id, "content": value}
91
+ for call, value in results
92
+ )
93
+ self.turns.append(group)
94
+
95
+ def build_messages(self, memory: str = "") -> list[Message]:
96
+ messages = [{"role": "system", "content": self.instructions}]
97
+ if memory:
98
+ messages.append(
99
+ {
100
+ "role": "system",
101
+ "content": "Relevant context from past conversations:\n" + memory,
102
+ }
103
+ )
104
+ if self.summary:
105
+ messages.append(
106
+ {
107
+ "role": "system",
108
+ "content": "Conversation summary so far:\n" + self.summary,
109
+ }
110
+ )
111
+ return messages + [m.copy() for group in self.turns for m in group]
112
+
113
+ @property
114
+ def should_summarize(self) -> bool:
115
+ size = len(self.summary) + sum(
116
+ len(json.dumps(group, ensure_ascii=False)) for group in self.turns
117
+ )
118
+ return len(self.turns) > self.recent and size > self.budget * 4
119
+
120
+ async def summarize(self, llm: LLMPlugin) -> None:
121
+ count = len(self.turns) - self.recent
122
+ if count <= 0:
123
+ return
124
+ generation = self._generation
125
+ body = json.dumps(self.turns[:count], ensure_ascii=False)
126
+ messages = [
127
+ {
128
+ "role": "system",
129
+ "content": "Summarize the conversation, preserving key facts and decisions.",
130
+ },
131
+ {"role": "user", "content": self.summary + "\n" + body},
132
+ ]
133
+ pieces = []
134
+ async with aclosing(
135
+ llm.chat(messages, LLMChatOptions(plain_text=True))
136
+ ) as stream:
137
+ async for chunk in stream:
138
+ if chunk.type in ("token", "segment"):
139
+ pieces.append(chunk.text)
140
+ if generation == self._generation and (summary := "".join(pieces).strip()):
141
+ self.summary = summary
142
+ del self.turns[:count]
143
+ self._generation += 1
144
+
145
+ def reset(self) -> None:
146
+ self._generation += 1
147
+ self.turns.clear()
148
+ self.summary = ""
149
+
150
+
151
+ class TurnDetector:
152
+ def __init__(self, on_turn_end: Callable[[], None], silence_timeout: float = 0.8):
153
+ self.callback = on_turn_end
154
+ self.timeout = silence_timeout
155
+ self.timer: asyncio.TimerHandle | None = None
156
+
157
+ def handle_transcription(self, text: str, is_final: bool) -> None:
158
+ self.reset()
159
+ if is_final and text.strip():
160
+ self.timer = asyncio.get_running_loop().call_later(
161
+ self.timeout, self.callback
162
+ )
163
+
164
+ def force_turn_end(self) -> None:
165
+ self.reset()
166
+ self.callback()
167
+
168
+ def reset(self) -> None:
169
+ if self.timer:
170
+ self.timer.cancel()
171
+ self.timer = None
172
+
173
+
174
+ class BargeIn:
175
+ def __init__(self) -> None:
176
+ self.interrupted = False
177
+ self.task: asyncio.Task | None = None
178
+
179
+ def start_cycle(self, task: asyncio.Task) -> None:
180
+ self.interrupted = False
181
+ self.task = task
182
+
183
+ def trigger(self) -> bool:
184
+ if self.interrupted or not self.task or self.task.done():
185
+ return False
186
+ self.interrupted = True
187
+ self.task.cancel()
188
+ return True
189
+
190
+ def reset(self) -> None:
191
+ self.task = None
192
+ self.interrupted = False