@livekit/agents 0.3.4 → 0.4.0

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.
Files changed (188) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +40 -0
  3. package/dist/audio.js +17 -30
  4. package/dist/audio.js.map +1 -1
  5. package/dist/cli.js +3 -14
  6. package/dist/cli.js.map +1 -1
  7. package/dist/http_server.d.ts +1 -1
  8. package/dist/http_server.js +5 -9
  9. package/dist/http_server.js.map +1 -1
  10. package/dist/index.d.ts +3 -2
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +14 -2
  13. package/dist/index.js.map +1 -1
  14. package/dist/ipc/job_executor.js +3 -5
  15. package/dist/ipc/job_executor.js.map +1 -1
  16. package/dist/ipc/job_main.d.ts +1 -1
  17. package/dist/ipc/proc_job_executor.js +66 -80
  18. package/dist/ipc/proc_job_executor.js.map +1 -1
  19. package/dist/ipc/proc_pool.d.ts +3 -3
  20. package/dist/ipc/proc_pool.d.ts.map +1 -1
  21. package/dist/ipc/proc_pool.js +16 -11
  22. package/dist/ipc/proc_pool.js.map +1 -1
  23. package/dist/job.js +56 -73
  24. package/dist/job.js.map +1 -1
  25. package/dist/llm/chat_context.d.ts +66 -0
  26. package/dist/llm/chat_context.d.ts.map +1 -0
  27. package/dist/llm/chat_context.js +93 -0
  28. package/dist/llm/chat_context.js.map +1 -0
  29. package/dist/llm/function_context.d.ts +19 -1
  30. package/dist/llm/function_context.d.ts.map +1 -1
  31. package/dist/llm/function_context.js +54 -18
  32. package/dist/llm/function_context.js.map +1 -1
  33. package/dist/llm/function_context.test.d.ts +2 -0
  34. package/dist/llm/function_context.test.d.ts.map +1 -0
  35. package/dist/llm/function_context.test.js +218 -0
  36. package/dist/llm/function_context.test.js.map +1 -0
  37. package/dist/llm/index.d.ts +3 -2
  38. package/dist/llm/index.d.ts.map +1 -1
  39. package/dist/llm/index.js +3 -2
  40. package/dist/llm/index.js.map +1 -1
  41. package/dist/llm/llm.d.ts +53 -0
  42. package/dist/llm/llm.d.ts.map +1 -0
  43. package/dist/llm/llm.js +45 -0
  44. package/dist/llm/llm.js.map +1 -0
  45. package/dist/multimodal/agent_playout.d.ts +1 -1
  46. package/dist/multimodal/agent_playout.js +116 -153
  47. package/dist/multimodal/agent_playout.js.map +1 -1
  48. package/dist/multimodal/multimodal_agent.d.ts +4 -3
  49. package/dist/multimodal/multimodal_agent.d.ts.map +1 -1
  50. package/dist/multimodal/multimodal_agent.js +214 -237
  51. package/dist/multimodal/multimodal_agent.js.map +1 -1
  52. package/dist/pipeline/agent_output.d.ts +30 -0
  53. package/dist/pipeline/agent_output.d.ts.map +1 -0
  54. package/dist/pipeline/agent_output.js +155 -0
  55. package/dist/pipeline/agent_output.js.map +1 -0
  56. package/dist/pipeline/agent_playout.d.ts +38 -0
  57. package/dist/pipeline/agent_playout.d.ts.map +1 -0
  58. package/dist/pipeline/agent_playout.js +142 -0
  59. package/dist/pipeline/agent_playout.js.map +1 -0
  60. package/dist/pipeline/human_input.d.ts +28 -0
  61. package/dist/pipeline/human_input.d.ts.map +1 -0
  62. package/dist/pipeline/human_input.js +134 -0
  63. package/dist/pipeline/human_input.js.map +1 -0
  64. package/dist/pipeline/index.d.ts +2 -0
  65. package/dist/pipeline/index.d.ts.map +1 -0
  66. package/dist/pipeline/index.js +5 -0
  67. package/dist/pipeline/index.js.map +1 -0
  68. package/dist/pipeline/pipeline_agent.d.ts +134 -0
  69. package/dist/pipeline/pipeline_agent.d.ts.map +1 -0
  70. package/dist/pipeline/pipeline_agent.js +661 -0
  71. package/dist/pipeline/pipeline_agent.js.map +1 -0
  72. package/dist/pipeline/speech_handle.d.ts +27 -0
  73. package/dist/pipeline/speech_handle.d.ts.map +1 -0
  74. package/dist/pipeline/speech_handle.js +102 -0
  75. package/dist/pipeline/speech_handle.js.map +1 -0
  76. package/dist/plugin.js +7 -20
  77. package/dist/plugin.js.map +1 -1
  78. package/dist/stt/index.d.ts +1 -2
  79. package/dist/stt/index.d.ts.map +1 -1
  80. package/dist/stt/index.js +1 -2
  81. package/dist/stt/index.js.map +1 -1
  82. package/dist/stt/stt.d.ts +62 -24
  83. package/dist/stt/stt.d.ts.map +1 -1
  84. package/dist/stt/stt.js +77 -27
  85. package/dist/stt/stt.js.map +1 -1
  86. package/dist/tokenize/basic/basic.d.ts +16 -0
  87. package/dist/tokenize/basic/basic.d.ts.map +1 -0
  88. package/dist/tokenize/basic/basic.js +50 -0
  89. package/dist/tokenize/basic/basic.js.map +1 -0
  90. package/dist/tokenize/basic/hyphenator.d.ts +17 -0
  91. package/dist/tokenize/basic/hyphenator.d.ts.map +1 -0
  92. package/dist/tokenize/basic/hyphenator.js +420 -0
  93. package/dist/tokenize/basic/hyphenator.js.map +1 -0
  94. package/dist/tokenize/basic/index.d.ts +2 -0
  95. package/dist/tokenize/basic/index.d.ts.map +1 -0
  96. package/dist/tokenize/basic/index.js +5 -0
  97. package/dist/tokenize/basic/index.js.map +1 -0
  98. package/dist/tokenize/basic/paragraph.d.ts +5 -0
  99. package/dist/tokenize/basic/paragraph.d.ts.map +1 -0
  100. package/dist/tokenize/basic/paragraph.js +38 -0
  101. package/dist/tokenize/basic/paragraph.js.map +1 -0
  102. package/dist/tokenize/basic/sentence.d.ts +5 -0
  103. package/dist/tokenize/basic/sentence.d.ts.map +1 -0
  104. package/dist/tokenize/basic/sentence.js +60 -0
  105. package/dist/tokenize/basic/sentence.js.map +1 -0
  106. package/dist/tokenize/basic/word.d.ts +5 -0
  107. package/dist/tokenize/basic/word.d.ts.map +1 -0
  108. package/dist/tokenize/basic/word.js +23 -0
  109. package/dist/tokenize/basic/word.js.map +1 -0
  110. package/dist/tokenize/index.d.ts +5 -0
  111. package/dist/tokenize/index.d.ts.map +1 -0
  112. package/dist/tokenize/index.js +8 -0
  113. package/dist/tokenize/index.js.map +1 -0
  114. package/dist/tokenize/token_stream.d.ts +36 -0
  115. package/dist/tokenize/token_stream.d.ts.map +1 -0
  116. package/dist/tokenize/token_stream.js +136 -0
  117. package/dist/tokenize/token_stream.js.map +1 -0
  118. package/dist/tokenize/tokenizer.d.ts +55 -0
  119. package/dist/tokenize/tokenizer.d.ts.map +1 -0
  120. package/dist/tokenize/tokenizer.js +117 -0
  121. package/dist/tokenize/tokenizer.js.map +1 -0
  122. package/dist/transcription.js +78 -89
  123. package/dist/transcription.js.map +1 -1
  124. package/dist/tts/index.d.ts +1 -3
  125. package/dist/tts/index.d.ts.map +1 -1
  126. package/dist/tts/index.js +1 -3
  127. package/dist/tts/index.js.map +1 -1
  128. package/dist/tts/tts.d.ts +66 -37
  129. package/dist/tts/tts.d.ts.map +1 -1
  130. package/dist/tts/tts.js +79 -74
  131. package/dist/tts/tts.js.map +1 -1
  132. package/dist/utils.d.ts +21 -6
  133. package/dist/utils.d.ts.map +1 -1
  134. package/dist/utils.js +120 -76
  135. package/dist/utils.js.map +1 -1
  136. package/dist/vad.d.ts +43 -39
  137. package/dist/vad.d.ts.map +1 -1
  138. package/dist/vad.js +51 -4
  139. package/dist/vad.js.map +1 -1
  140. package/dist/worker.d.ts +1 -1
  141. package/dist/worker.js +257 -247
  142. package/dist/worker.js.map +1 -1
  143. package/package.json +4 -3
  144. package/src/index.ts +16 -2
  145. package/src/ipc/proc_pool.ts +4 -4
  146. package/src/llm/chat_context.ts +147 -0
  147. package/src/llm/function_context.test.ts +248 -0
  148. package/src/llm/function_context.ts +77 -18
  149. package/src/llm/index.ts +21 -2
  150. package/src/llm/llm.ts +102 -0
  151. package/src/multimodal/multimodal_agent.ts +19 -6
  152. package/src/pipeline/agent_output.ts +185 -0
  153. package/src/pipeline/agent_playout.ts +187 -0
  154. package/src/pipeline/human_input.ts +166 -0
  155. package/src/pipeline/index.ts +15 -0
  156. package/src/pipeline/pipeline_agent.ts +917 -0
  157. package/src/pipeline/speech_handle.ts +136 -0
  158. package/src/stt/index.ts +8 -2
  159. package/src/stt/stt.ts +98 -31
  160. package/src/tokenize/basic/basic.ts +73 -0
  161. package/src/tokenize/basic/hyphenator.ts +436 -0
  162. package/src/tokenize/basic/index.ts +5 -0
  163. package/src/tokenize/basic/paragraph.ts +43 -0
  164. package/src/tokenize/basic/sentence.ts +69 -0
  165. package/src/tokenize/basic/word.ts +27 -0
  166. package/src/tokenize/index.ts +16 -0
  167. package/src/tokenize/token_stream.ts +163 -0
  168. package/src/tokenize/tokenizer.ts +152 -0
  169. package/src/tts/index.ts +1 -20
  170. package/src/tts/tts.ts +110 -57
  171. package/src/utils.ts +95 -25
  172. package/src/vad.ts +86 -45
  173. package/tsconfig.tsbuildinfo +1 -1
  174. package/dist/stt/stream_adapter.d.ts +0 -19
  175. package/dist/stt/stream_adapter.d.ts.map +0 -1
  176. package/dist/stt/stream_adapter.js +0 -96
  177. package/dist/stt/stream_adapter.js.map +0 -1
  178. package/dist/tokenize.d.ts +0 -15
  179. package/dist/tokenize.d.ts.map +0 -1
  180. package/dist/tokenize.js +0 -12
  181. package/dist/tokenize.js.map +0 -1
  182. package/dist/tts/stream_adapter.d.ts +0 -19
  183. package/dist/tts/stream_adapter.d.ts.map +0 -1
  184. package/dist/tts/stream_adapter.js +0 -111
  185. package/dist/tts/stream_adapter.js.map +0 -1
  186. package/src/stt/stream_adapter.ts +0 -104
  187. package/src/tokenize.ts +0 -22
  188. package/src/tts/stream_adapter.ts +0 -93
@@ -0,0 +1,661 @@
1
+ var _a;
2
+ import { AudioSource, LocalAudioTrack, RoomEvent, TrackPublishOptions, TrackSource, } from '@livekit/rtc-node';
3
+ import EventEmitter from 'node:events';
4
+ import { LLMStream } from '../llm/index.js';
5
+ import { ChatContext, ChatMessage, ChatRole } from '../llm/index.js';
6
+ import { log } from '../log.js';
7
+ import { SentenceTokenizer as BasicSentenceTokenizer, WordTokenizer as BasicWordTokenizer, hyphenateWord, } from '../tokenize/basic/index.js';
8
+ import { AsyncIterableQueue, CancellablePromise, Future, gracefullyCancel } from '../utils.js';
9
+ import { AgentOutput } from './agent_output.js';
10
+ import { AgentPlayout, AgentPlayoutEvent } from './agent_playout.js';
11
+ import { HumanInput, HumanInputEvent } from './human_input.js';
12
+ import { SpeechHandle } from './speech_handle.js';
13
+ export var VPAEvent;
14
+ (function (VPAEvent) {
15
+ VPAEvent[VPAEvent["USER_STARTED_SPEAKING"] = 0] = "USER_STARTED_SPEAKING";
16
+ VPAEvent[VPAEvent["USER_STOPPED_SPEAKING"] = 1] = "USER_STOPPED_SPEAKING";
17
+ VPAEvent[VPAEvent["AGENT_STARTED_SPEAKING"] = 2] = "AGENT_STARTED_SPEAKING";
18
+ VPAEvent[VPAEvent["AGENT_STOPPED_SPEAKING"] = 3] = "AGENT_STOPPED_SPEAKING";
19
+ VPAEvent[VPAEvent["USER_SPEECH_COMMITTED"] = 4] = "USER_SPEECH_COMMITTED";
20
+ VPAEvent[VPAEvent["AGENT_SPEECH_COMMITTED"] = 5] = "AGENT_SPEECH_COMMITTED";
21
+ VPAEvent[VPAEvent["AGENT_SPEECH_INTERRUPTED"] = 6] = "AGENT_SPEECH_INTERRUPTED";
22
+ VPAEvent[VPAEvent["FUNCTION_CALLS_COLLECTED"] = 7] = "FUNCTION_CALLS_COLLECTED";
23
+ VPAEvent[VPAEvent["FUNCTION_CALLS_FINISHED"] = 8] = "FUNCTION_CALLS_FINISHED";
24
+ })(VPAEvent || (VPAEvent = {}));
25
+ export class AgentCallContext {
26
+ #agent;
27
+ #llmStream;
28
+ #metadata = new Map();
29
+ static #current;
30
+ constructor(agent, llmStream) {
31
+ this.#agent = agent;
32
+ this.#llmStream = llmStream;
33
+ AgentCallContext.#current = this;
34
+ }
35
+ static getCurrent() {
36
+ return AgentCallContext.#current;
37
+ }
38
+ get agent() {
39
+ return this.#agent;
40
+ }
41
+ storeMetadata(key, value) {
42
+ this.#metadata.set(key, value);
43
+ }
44
+ getMetadata(key, orDefault = undefined) {
45
+ return this.#metadata.get(key) || orDefault;
46
+ }
47
+ get llmStream() {
48
+ return this.#llmStream;
49
+ }
50
+ }
51
+ const defaultBeforeLLMCallback = (agent, chatCtx) => {
52
+ return agent.llm.chat({ chatCtx, fncCtx: agent.fncCtx });
53
+ };
54
+ const defaultBeforeTTSCallback = (
55
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
56
+ _, text) => {
57
+ return text;
58
+ };
59
+ const defaultAgentTranscriptionOptions = {
60
+ userTranscription: true,
61
+ agentTranscription: true,
62
+ agentTranscriptionSpeech: 1,
63
+ sentenceTokenizer: new BasicSentenceTokenizer(),
64
+ wordTokenizer: new BasicWordTokenizer(false),
65
+ hyphenateWord: hyphenateWord,
66
+ };
67
+ const defaultVPAOptions = {
68
+ chatCtx: new ChatContext(),
69
+ allowInterruptions: true,
70
+ interruptSpeechDuration: 50,
71
+ interruptMinWords: 0,
72
+ minEndpointingDelay: 500,
73
+ maxRecursiveFncCalls: 1,
74
+ preemptiveSynthesis: false,
75
+ beforeLLMCallback: defaultBeforeLLMCallback,
76
+ beforeTTSCallback: defaultBeforeTTSCallback,
77
+ transcription: defaultAgentTranscriptionOptions,
78
+ };
79
+ /** A pipeline agent (VAD + STT + LLM + TTS) implementation. */
80
+ export class VoicePipelineAgent extends EventEmitter {
81
+ /** Minimum time played for the user speech to be committed to the chat context. */
82
+ MIN_TIME_PLAYED_FOR_COMMIT = 1.5;
83
+ static FLUSH_SENTINEL = Symbol('FLUSH_SENTINEL');
84
+ #vad;
85
+ #stt;
86
+ #llm;
87
+ #tts;
88
+ #opts;
89
+ #humanInput;
90
+ #agentOutput;
91
+ #trackPublishedFut = new Future();
92
+ #pendingAgentReply;
93
+ #agentReplyTask;
94
+ #playingSpeech;
95
+ #transcribedText = '';
96
+ #transcribedInterimText = '';
97
+ #speechQueueOpen = new Future();
98
+ #speechQueue = new AsyncIterableQueue();
99
+ #lastEndOfSpeechTime;
100
+ #updateStateTask;
101
+ #started = false;
102
+ #room;
103
+ #participant = null;
104
+ #deferredValidation;
105
+ #logger = log();
106
+ #agentPublication;
107
+ constructor(
108
+ /** Voice Activity Detection instance. */
109
+ vad,
110
+ /** Speech-to-Text instance. */
111
+ stt,
112
+ /** Large Language Model instance. */
113
+ llm,
114
+ /** Text-to-Speech instance. */
115
+ tts,
116
+ /** Additional VoicePipelineAgent options. */
117
+ opts = defaultVPAOptions) {
118
+ super();
119
+ this.#opts = { ...defaultVPAOptions, ...opts };
120
+ this.#vad = vad;
121
+ this.#stt = stt;
122
+ this.#llm = llm;
123
+ this.#tts = tts;
124
+ this.#deferredValidation = new DeferredReplyValidation(this.#validateReplyIfPossible.bind(this), this.#opts.minEndpointingDelay);
125
+ }
126
+ get fncCtx() {
127
+ return this.#opts.fncCtx;
128
+ }
129
+ set fncCtx(ctx) {
130
+ this.#opts.fncCtx = ctx;
131
+ }
132
+ get chatCtx() {
133
+ return this.#opts.chatCtx;
134
+ }
135
+ get llm() {
136
+ return this.#llm;
137
+ }
138
+ get tts() {
139
+ return this.#tts;
140
+ }
141
+ get stt() {
142
+ return this.#stt;
143
+ }
144
+ get vad() {
145
+ return this.#vad;
146
+ }
147
+ /** Start the voice assistant. */
148
+ start(
149
+ /** The room to connect to. */
150
+ room,
151
+ /**
152
+ * The participant to listen to.
153
+ *
154
+ * @remarks
155
+ * Can be a participant or an identity.
156
+ * If omitted, the first participant in the room will be selected.
157
+ */
158
+ participant = null) {
159
+ if (this.#started) {
160
+ throw new Error('voice assistant already started');
161
+ }
162
+ room.on(RoomEvent.ParticipantConnected, (participant) => {
163
+ // automatically link to the first participant that connects, if not already linked
164
+ if (this.#participant) {
165
+ return;
166
+ }
167
+ this.#linkParticipant.call(this, participant.identity);
168
+ });
169
+ this.#room = room;
170
+ this.#participant = participant;
171
+ if (participant) {
172
+ if (typeof participant === 'string') {
173
+ this.#linkParticipant(participant);
174
+ }
175
+ else {
176
+ this.#linkParticipant(participant.identity);
177
+ }
178
+ }
179
+ this.#run();
180
+ }
181
+ /** Play a speech source through the voice assistant. */
182
+ async say(source, allowInterruptions = true, addToChatCtx = true) {
183
+ await this.#trackPublishedFut.await;
184
+ const newHandle = SpeechHandle.createAssistantSpeech(allowInterruptions, addToChatCtx);
185
+ const synthesisHandle = this.#synthesizeAgentSpeech(newHandle.id, source);
186
+ newHandle.initialize(source, synthesisHandle);
187
+ this.#addSpeechForPlayout(newHandle);
188
+ }
189
+ #updateState(state, delay = 0) {
190
+ const runTask = (delay) => {
191
+ return new CancellablePromise(async (resolve, _, onCancel) => {
192
+ let cancelled = false;
193
+ onCancel(() => {
194
+ cancelled = true;
195
+ });
196
+ await new Promise((resolve) => setTimeout(resolve, delay));
197
+ if (this.#room?.isConnected) {
198
+ if (!cancelled) {
199
+ await this.#room.localParticipant?.setAttributes({ ATTRIBUTE_AGENT_STATE: state });
200
+ }
201
+ }
202
+ resolve();
203
+ });
204
+ };
205
+ if (this.#updateStateTask) {
206
+ this.#updateStateTask.cancel();
207
+ }
208
+ this.#updateStateTask = runTask(delay);
209
+ }
210
+ #linkParticipant(participantIdentity) {
211
+ if (!this.#room) {
212
+ this.#logger.error('Room is not set');
213
+ return;
214
+ }
215
+ this.#participant = this.#room.remoteParticipants.get(participantIdentity) || null;
216
+ if (!this.#participant) {
217
+ this.#logger.error(`Participant with identity ${participantIdentity} not found`);
218
+ return;
219
+ }
220
+ this.#humanInput = new HumanInput(this.#room, this.#vad, this.#stt, this.#participant);
221
+ this.#humanInput.on(HumanInputEvent.START_OF_SPEECH, (event) => {
222
+ this.emit(VPAEvent.USER_STARTED_SPEAKING);
223
+ this.#deferredValidation.onHumanStartOfSpeech(event);
224
+ });
225
+ this.#humanInput.on(HumanInputEvent.VAD_INFERENCE_DONE, (event) => {
226
+ if (!this.#trackPublishedFut.done) {
227
+ return;
228
+ }
229
+ if (!this.#agentOutput) {
230
+ throw new Error('agent output is undefined');
231
+ }
232
+ let tv = 1;
233
+ if (this.#opts.allowInterruptions) {
234
+ tv = Math.max(0, 1 - event.probability);
235
+ this.#agentOutput.playout.targetVolume = tv;
236
+ }
237
+ if (event.speechDuration >= this.#opts.interruptSpeechDuration) {
238
+ this.#interruptIfPossible();
239
+ }
240
+ });
241
+ this.#humanInput.on(HumanInputEvent.END_OF_SPEECH, (event) => {
242
+ this.emit(VPAEvent.USER_STARTED_SPEAKING);
243
+ this.#deferredValidation.onHumanEndOfSpeech(event);
244
+ this.#lastEndOfSpeechTime = Date.now();
245
+ });
246
+ this.#humanInput.on(HumanInputEvent.INTERIM_TRANSCRIPT, (event) => {
247
+ this.#transcribedInterimText = event.alternatives[0].text;
248
+ });
249
+ this.#humanInput.on(HumanInputEvent.FINAL_TRANSCRIPT, (event) => {
250
+ const newTranscript = event.alternatives[0].text;
251
+ if (!newTranscript)
252
+ return;
253
+ this.#logger.child({ userTranscript: newTranscript }).debug('received user transcript');
254
+ this.#transcribedText += (this.#transcribedText ? ' ' : '') + newTranscript;
255
+ if (this.#opts.preemptiveSynthesis &&
256
+ (!this.#playingSpeech || this.#playingSpeech.allowInterruptions)) {
257
+ this.#synthesizeAgentReply();
258
+ }
259
+ this.#deferredValidation.onHumanFinalTranscript(newTranscript);
260
+ const words = this.#opts.transcription.wordTokenizer.tokenize(newTranscript);
261
+ if (words.length >= 3) {
262
+ // VAD can sometimes not detect that the human is speaking.
263
+ // to make the interruption more reliable, we also interrupt on the final transcript.
264
+ this.#interruptIfPossible();
265
+ }
266
+ });
267
+ }
268
+ async #run() {
269
+ this.#updateState('initializing');
270
+ const audioSource = new AudioSource(this.#tts.sampleRate, this.#tts.numChannels);
271
+ const track = LocalAudioTrack.createAudioTrack('assistant_voice', audioSource);
272
+ this.#agentPublication = await this.#room?.localParticipant?.publishTrack(track, new TrackPublishOptions({ source: TrackSource.SOURCE_MICROPHONE }));
273
+ const agentPlayout = new AgentPlayout(audioSource);
274
+ this.#agentOutput = new AgentOutput(agentPlayout, this.#tts);
275
+ agentPlayout.on(AgentPlayoutEvent.PLAYOUT_STARTED, () => {
276
+ this.emit(VPAEvent.AGENT_STARTED_SPEAKING);
277
+ this.#updateState('speaking');
278
+ });
279
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
280
+ agentPlayout.on(AgentPlayoutEvent.PLAYOUT_STOPPED, (_) => {
281
+ this.emit(VPAEvent.AGENT_STOPPED_SPEAKING);
282
+ this.#updateState('listening');
283
+ });
284
+ this.#trackPublishedFut.resolve();
285
+ while (true) {
286
+ await this.#speechQueueOpen.await;
287
+ for await (const speech of this.#speechQueue) {
288
+ if (speech === _a.FLUSH_SENTINEL)
289
+ break;
290
+ this.#playingSpeech = speech;
291
+ await this.#playSpeech(speech);
292
+ this.#playingSpeech = undefined;
293
+ }
294
+ this.#speechQueueOpen = new Future();
295
+ }
296
+ }
297
+ #synthesizeAgentReply() {
298
+ this.#pendingAgentReply?.cancel();
299
+ if (this.#humanInput && this.#humanInput.speaking) {
300
+ this.#updateState('thinking', 200);
301
+ }
302
+ this.#pendingAgentReply = SpeechHandle.createAssistantReply(this.#opts.allowInterruptions, true, this.#transcribedText);
303
+ const newHandle = this.#pendingAgentReply;
304
+ this.#agentReplyTask = this.#synthesizeAnswerTask(this.#agentReplyTask, newHandle);
305
+ }
306
+ #synthesizeAnswerTask(oldTask, handle) {
307
+ return new CancellablePromise(async (resolve, _, onCancel) => {
308
+ let cancelled = false;
309
+ onCancel(() => {
310
+ cancelled = true;
311
+ });
312
+ if (oldTask) {
313
+ await gracefullyCancel(oldTask);
314
+ }
315
+ const copiedCtx = this.chatCtx.copy();
316
+ const playingSpeech = this.#playingSpeech;
317
+ if (playingSpeech && playingSpeech.initialized) {
318
+ if ((!playingSpeech.userQuestion || playingSpeech.userCommitted) &&
319
+ !playingSpeech.speechCommitted) {
320
+ // the speech is playing but not committed yet,
321
+ // add it to the chat context for this new reply synthesis
322
+ copiedCtx.messages.push(ChatMessage.create({
323
+ // TODO(nbsp): uhhh unsure where to get the played text here
324
+ // text: playingSpeech.synthesisHandle.(theres no ttsForwarder here)
325
+ role: ChatRole.ASSISTANT,
326
+ }));
327
+ }
328
+ }
329
+ copiedCtx.messages.push(ChatMessage.create({
330
+ text: handle?.userQuestion,
331
+ role: ChatRole.USER,
332
+ }));
333
+ if (cancelled)
334
+ resolve();
335
+ let llmStream = await this.#opts.beforeLLMCallback(this, copiedCtx);
336
+ if (llmStream === false) {
337
+ handle?.cancel();
338
+ return;
339
+ }
340
+ if (cancelled)
341
+ resolve();
342
+ // fallback to default impl if no custom/user stream is returned
343
+ if (!(llmStream instanceof LLMStream)) {
344
+ llmStream = (await defaultBeforeLLMCallback(this, copiedCtx));
345
+ }
346
+ if (handle.interrupted) {
347
+ return;
348
+ }
349
+ const synthesisHandle = this.#synthesizeAgentSpeech(handle.id, llmStream);
350
+ handle.initialize(llmStream, synthesisHandle);
351
+ // TODO(theomonnom): find a more reliable way to get the elapsed time from the last EOS
352
+ // (VAD could not have detected any speech — maybe unlikely?)
353
+ const elapsed = !!this.#lastEndOfSpeechTime
354
+ ? Math.round((Date.now() - this.#lastEndOfSpeechTime) * 1000) / 1000
355
+ : -1;
356
+ this.#logger.child({ speechId: handle.id, elapsed }).debug('synthesizing agent reply');
357
+ resolve();
358
+ });
359
+ }
360
+ async #playSpeech(handle) {
361
+ try {
362
+ await handle.waitForInitialization();
363
+ }
364
+ catch {
365
+ return;
366
+ }
367
+ await this.#agentPublication.waitForSubscription();
368
+ const synthesisHandle = handle.synthesisHandle;
369
+ if (synthesisHandle.interrupted)
370
+ return;
371
+ const userQuestion = handle.userQuestion;
372
+ const playHandle = synthesisHandle.play();
373
+ const joinFut = playHandle.join();
374
+ const commitUserQuestionIfNeeded = () => {
375
+ if (!userQuestion || synthesisHandle.interrupted || handle.userCommitted)
376
+ return;
377
+ const isUsingTools = handle.source instanceof LLMStream && !!handle.source.functionCalls.length;
378
+ // make sure at least some speech was played before committing the user message
379
+ // since we try to validate as fast as possible it is possible the agent gets interrupted
380
+ // really quickly (barely audible), we don't want to mark this question as "answered".
381
+ if (handle.allowInterruptions &&
382
+ !isUsingTools &&
383
+ playHandle.timePlayed < this.MIN_TIME_PLAYED_FOR_COMMIT &&
384
+ !joinFut.done) {
385
+ return;
386
+ }
387
+ this.#logger.child({ userTranscript: userQuestion }).debug('committed user transcript');
388
+ const userMsg = ChatMessage.create({ text: userQuestion, role: ChatRole.USER });
389
+ this.chatCtx.messages.push(userMsg);
390
+ this.emit(VPAEvent.USER_SPEECH_COMMITTED, userMsg);
391
+ this.#transcribedText = this.#transcribedText.slice(userQuestion.length);
392
+ };
393
+ // wait for the playHandle to finish and check every 1s if user question should be committed
394
+ commitUserQuestionIfNeeded();
395
+ while (!joinFut.done) {
396
+ await new Promise(async (resolve) => {
397
+ setTimeout(resolve, 500);
398
+ await joinFut.await;
399
+ resolve();
400
+ });
401
+ commitUserQuestionIfNeeded();
402
+ if (handle.interrupted)
403
+ break;
404
+ }
405
+ commitUserQuestionIfNeeded();
406
+ // TODO(nbsp): what goes here
407
+ let collectedText = '';
408
+ const isUsingTools = handle.source instanceof LLMStream && !!handle.source.functionCalls.length;
409
+ const extraToolsMessages = []; // additional messages from the functions to add to the context
410
+ let interrupted = handle.interrupted;
411
+ // if the answer is using tools, execute the functions and automatically generate
412
+ // a response to the user question from the returned values
413
+ if (isUsingTools && !interrupted) {
414
+ if (!userQuestion || handle.userCommitted) {
415
+ throw new Error('user speech should have been committed before using tools');
416
+ }
417
+ const llmStream = handle.source;
418
+ let newFunctionCalls = llmStream.functionCalls;
419
+ for (let i = 0; i < this.#opts.maxRecursiveFncCalls; i++) {
420
+ this.emit(VPAEvent.FUNCTION_CALLS_COLLECTED, newFunctionCalls);
421
+ const calledFuncs = [];
422
+ for (const func of newFunctionCalls) {
423
+ const task = func.func.execute(func.params).then((result) => ({ name: func.name, toolCallId: func.toolCallId, result }), (error) => ({ name: func.name, toolCallId: func.toolCallId, error }));
424
+ calledFuncs.push({ ...func, task });
425
+ this.#logger
426
+ .child({ function: func.name, speechId: handle.id })
427
+ .debug('executing AI function');
428
+ try {
429
+ await task;
430
+ }
431
+ catch {
432
+ this.#logger
433
+ .child({ function: func.name, speechId: handle.id })
434
+ .error('error executing AI function');
435
+ }
436
+ }
437
+ const toolCallsInfo = [];
438
+ const toolCallsResults = [];
439
+ for (const fnc of calledFuncs) {
440
+ // ignore the function calls that return void
441
+ const task = await fnc.task;
442
+ if (!task || task.result === undefined)
443
+ continue;
444
+ toolCallsInfo.push(fnc);
445
+ toolCallsResults.push(ChatMessage.createToolFromFunctionResult(task));
446
+ }
447
+ if (!toolCallsInfo.length)
448
+ break;
449
+ // generate an answer from the tool calls
450
+ extraToolsMessages.push(ChatMessage.createToolCalls(toolCallsInfo, collectedText));
451
+ extraToolsMessages.push(...toolCallsResults);
452
+ const chatCtx = handle.source.chatCtx.copy();
453
+ chatCtx.messages.push(...extraToolsMessages);
454
+ const answerLLMStream = this.llm.chat({
455
+ chatCtx,
456
+ fncCtx: this.fncCtx,
457
+ });
458
+ const answerSynthesis = this.#synthesizeAgentSpeech(handle.id, answerLLMStream);
459
+ // replace the synthesis handle with the new one to allow interruption
460
+ handle.synthesisHandle = answerSynthesis;
461
+ const playHandle = answerSynthesis.play();
462
+ await playHandle.join().await;
463
+ // TODO(nbsp): what text goes here
464
+ collectedText = '';
465
+ interrupted = answerSynthesis.interrupted;
466
+ newFunctionCalls = answerLLMStream.functionCalls;
467
+ this.emit(VPAEvent.FUNCTION_CALLS_FINISHED, calledFuncs);
468
+ if (!newFunctionCalls)
469
+ break;
470
+ }
471
+ if (handle.addToChatCtx && (!userQuestion || handle.userCommitted)) {
472
+ this.chatCtx.messages.push(...extraToolsMessages);
473
+ if (interrupted) {
474
+ collectedText + '…';
475
+ }
476
+ const msg = ChatMessage.create({ text: collectedText, role: ChatRole.ASSISTANT });
477
+ this.chatCtx.messages.push(msg);
478
+ handle.markSpeechCommitted();
479
+ if (interrupted) {
480
+ this.emit(VPAEvent.AGENT_SPEECH_INTERRUPTED, msg);
481
+ }
482
+ else {
483
+ this.emit(VPAEvent.AGENT_SPEECH_COMMITTED, msg);
484
+ }
485
+ this.#logger
486
+ .child({
487
+ agentTranscript: collectedText,
488
+ interrupted,
489
+ speechId: handle.id,
490
+ })
491
+ .debug('committed agent speech');
492
+ }
493
+ }
494
+ }
495
+ #synthesizeAgentSpeech(speechId, source) {
496
+ if (!this.#agentOutput) {
497
+ throw new Error('agent output should be initialized when ready');
498
+ }
499
+ if (source instanceof LLMStream) {
500
+ source = llmStreamToStringIterable(speechId, source);
501
+ }
502
+ const ogSource = source;
503
+ if (!(typeof source === 'string')) {
504
+ // TODO(nbsp): itertools.tee
505
+ }
506
+ const ttsSource = this.#opts.beforeTTSCallback(this, ogSource);
507
+ if (!ttsSource) {
508
+ throw new Error('beforeTTSCallback must return string or AsyncIterable<string>');
509
+ }
510
+ return this.#agentOutput.synthesize(speechId, ttsSource);
511
+ }
512
+ async #validateReplyIfPossible() {
513
+ if (this.#playingSpeech && this.#playingSpeech.allowInterruptions) {
514
+ this.#logger
515
+ .child({ speechId: this.#playingSpeech.id })
516
+ .debug('skipping validation, agent is speaking and does not allow interruptions');
517
+ return;
518
+ }
519
+ if (!this.#pendingAgentReply) {
520
+ if (this.#opts.preemptiveSynthesis || !this.#transcribedText) {
521
+ return;
522
+ }
523
+ this.#synthesizeAgentReply();
524
+ }
525
+ if (!this.#pendingAgentReply) {
526
+ throw new Error('pending agent reply is undefined');
527
+ }
528
+ // in some bad timimg, we could end up with two pushed agent replies inside the speech queue.
529
+ // so make sure we directly interrupt every reply when validating a new one
530
+ if (this.#speechQueueOpen.done) {
531
+ for await (const speech of this.#speechQueue) {
532
+ if (speech === _a.FLUSH_SENTINEL)
533
+ break;
534
+ if (!speech.isReply)
535
+ continue;
536
+ if (!speech.allowInterruptions)
537
+ speech.interrupt();
538
+ }
539
+ }
540
+ this.#logger.child({ speechId: this.#pendingAgentReply.id }).debug('validated agent reply');
541
+ this.#addSpeechForPlayout(this.#pendingAgentReply);
542
+ this.#pendingAgentReply = undefined;
543
+ this.#transcribedInterimText = '';
544
+ }
545
+ #interruptIfPossible() {
546
+ if (!this.#playingSpeech ||
547
+ !this.#playingSpeech.allowInterruptions ||
548
+ this.#playingSpeech.interrupted) {
549
+ return;
550
+ }
551
+ if (this.#opts.interruptMinWords !== 0) {
552
+ // check the final/interim transcribed text for the minimum word count
553
+ // to interrupt the agent speech
554
+ const interimWords = this.#opts.transcription.wordTokenizer.tokenize(this.#transcribedInterimText);
555
+ if (interimWords.length < this.#opts.interruptMinWords) {
556
+ return;
557
+ }
558
+ }
559
+ this.#playingSpeech.interrupt();
560
+ }
561
+ #addSpeechForPlayout(handle) {
562
+ this.#speechQueue.put(handle);
563
+ this.#speechQueue.put(_a.FLUSH_SENTINEL);
564
+ this.#speechQueueOpen.resolve();
565
+ }
566
+ /** Close the voice assistant. */
567
+ async close() {
568
+ if (!this.#started) {
569
+ return;
570
+ }
571
+ this.#room?.removeAllListeners(RoomEvent.ParticipantConnected);
572
+ // TODO(nbsp): await this.#deferredValidation.close()
573
+ }
574
+ }
575
+ _a = VoicePipelineAgent;
576
+ async function* llmStreamToStringIterable(speechId, stream) {
577
+ const startTime = Date.now();
578
+ let firstFrame = true;
579
+ for await (const chunk of stream) {
580
+ const content = chunk.choices[0].delta.content;
581
+ if (!content)
582
+ continue;
583
+ if (firstFrame) {
584
+ firstFrame = false;
585
+ log()
586
+ .child({ speechId, elapsed: Math.round(Date.now() * 1000 - startTime) / 1000 })
587
+ .debug('received first LLM token');
588
+ }
589
+ yield content;
590
+ }
591
+ }
592
+ /** This class is used to try to find the best time to validate the agent reply. */
593
+ class DeferredReplyValidation {
594
+ // if the STT gives us punctuation, we can try to validate the reply faster.
595
+ PUNCTUATION = '.!?';
596
+ PUNCTUATION_REDUCE_FACTOR = 0.75;
597
+ LATE_TRANSCRIPT_TOLERANCE = 1.5; // late compared to end of speech
598
+ #validateFunc;
599
+ #validatingPromise;
600
+ #validatingFuture = new Future();
601
+ #lastFinalTranscript = '';
602
+ #lastRecvEndOfSpeechTime = 0;
603
+ #speaking = false;
604
+ #endOfSpeechDelay;
605
+ #finalTranscriptDelay;
606
+ constructor(validateFunc, minEndpointingDelay) {
607
+ this.#validateFunc = validateFunc;
608
+ this.#endOfSpeechDelay = minEndpointingDelay;
609
+ this.#finalTranscriptDelay = minEndpointingDelay;
610
+ }
611
+ get validating() {
612
+ return !this.#validatingFuture.done;
613
+ }
614
+ onHumanFinalTranscript(transcript) {
615
+ this.#lastFinalTranscript = transcript.trim();
616
+ if (this.#speaking)
617
+ return;
618
+ const hasRecentEndOfSpeech = Date.now() - this.#lastRecvEndOfSpeechTime < this.LATE_TRANSCRIPT_TOLERANCE;
619
+ let delay = hasRecentEndOfSpeech ? this.#endOfSpeechDelay : this.#finalTranscriptDelay;
620
+ delay = this.#endWithPunctuation() ? delay * this.PUNCTUATION_REDUCE_FACTOR : 1;
621
+ this.#run(delay);
622
+ }
623
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
624
+ onHumanStartOfSpeech(_) {
625
+ this.#speaking = true;
626
+ // TODO(nbsp):
627
+ // if (this.validating) {
628
+ // this.#validatingPromise.cancel()
629
+ // }
630
+ }
631
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
632
+ onHumanEndOfSpeech(_) {
633
+ this.#speaking = false;
634
+ this.#lastRecvEndOfSpeechTime = Date.now();
635
+ if (this.#lastFinalTranscript) {
636
+ const delay = this.#endWithPunctuation()
637
+ ? this.#endOfSpeechDelay * this.PUNCTUATION_REDUCE_FACTOR
638
+ : 1;
639
+ this.#run(delay);
640
+ }
641
+ }
642
+ // TODO(nbsp): aclose
643
+ #endWithPunctuation() {
644
+ return (this.#lastFinalTranscript.length > 0 &&
645
+ this.PUNCTUATION.includes(this.#lastFinalTranscript[this.#lastFinalTranscript.length - 1]));
646
+ }
647
+ #resetStates() {
648
+ this.#lastFinalTranscript = '';
649
+ this.#lastRecvEndOfSpeechTime = 0;
650
+ }
651
+ #run(delay) {
652
+ const runTask = async (delay) => {
653
+ await new Promise((resolve) => setTimeout(resolve, delay));
654
+ this.#resetStates();
655
+ await this.#validateFunc();
656
+ };
657
+ this.#validatingFuture = new Future();
658
+ this.#validatingPromise = runTask(delay);
659
+ }
660
+ }
661
+ //# sourceMappingURL=pipeline_agent.js.map