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