@livekit/agents-plugin-livekit 0.0.0-next-20260624041820

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 (88) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +17 -0
  3. package/dist/hf_utils.cjs +272 -0
  4. package/dist/hf_utils.cjs.map +1 -0
  5. package/dist/hf_utils.d.cts +40 -0
  6. package/dist/hf_utils.d.ts +40 -0
  7. package/dist/hf_utils.d.ts.map +1 -0
  8. package/dist/hf_utils.js +237 -0
  9. package/dist/hf_utils.js.map +1 -0
  10. package/dist/hf_utils.test.cjs +330 -0
  11. package/dist/hf_utils.test.cjs.map +1 -0
  12. package/dist/hf_utils.test.d.cts +2 -0
  13. package/dist/hf_utils.test.d.ts +2 -0
  14. package/dist/hf_utils.test.d.ts.map +1 -0
  15. package/dist/hf_utils.test.js +307 -0
  16. package/dist/hf_utils.test.js.map +1 -0
  17. package/dist/index.cjs +63 -0
  18. package/dist/index.cjs.map +1 -0
  19. package/dist/index.d.cts +3 -0
  20. package/dist/index.d.ts +3 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +28 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/onnxruntime.d.cjs +2 -0
  25. package/dist/onnxruntime.d.cjs.map +1 -0
  26. package/dist/onnxruntime.d.js +1 -0
  27. package/dist/onnxruntime.d.js.map +1 -0
  28. package/dist/turn_detector/base.cjs +228 -0
  29. package/dist/turn_detector/base.cjs.map +1 -0
  30. package/dist/turn_detector/base.d.cts +54 -0
  31. package/dist/turn_detector/base.d.ts +54 -0
  32. package/dist/turn_detector/base.d.ts.map +1 -0
  33. package/dist/turn_detector/base.js +198 -0
  34. package/dist/turn_detector/base.js.map +1 -0
  35. package/dist/turn_detector/constants.cjs +44 -0
  36. package/dist/turn_detector/constants.cjs.map +1 -0
  37. package/dist/turn_detector/constants.d.cts +7 -0
  38. package/dist/turn_detector/constants.d.ts +7 -0
  39. package/dist/turn_detector/constants.d.ts.map +1 -0
  40. package/dist/turn_detector/constants.js +16 -0
  41. package/dist/turn_detector/constants.js.map +1 -0
  42. package/dist/turn_detector/english.cjs +52 -0
  43. package/dist/turn_detector/english.cjs.map +1 -0
  44. package/dist/turn_detector/english.d.cts +11 -0
  45. package/dist/turn_detector/english.d.ts +11 -0
  46. package/dist/turn_detector/english.d.ts.map +1 -0
  47. package/dist/turn_detector/english.js +26 -0
  48. package/dist/turn_detector/english.js.map +1 -0
  49. package/dist/turn_detector/index.cjs +58 -0
  50. package/dist/turn_detector/index.cjs.map +1 -0
  51. package/dist/turn_detector/index.d.cts +5 -0
  52. package/dist/turn_detector/index.d.ts +5 -0
  53. package/dist/turn_detector/index.d.ts.map +1 -0
  54. package/dist/turn_detector/index.js +28 -0
  55. package/dist/turn_detector/index.js.map +1 -0
  56. package/dist/turn_detector/multilingual.cjs +145 -0
  57. package/dist/turn_detector/multilingual.cjs.map +1 -0
  58. package/dist/turn_detector/multilingual.d.cts +15 -0
  59. package/dist/turn_detector/multilingual.d.ts +15 -0
  60. package/dist/turn_detector/multilingual.d.ts.map +1 -0
  61. package/dist/turn_detector/multilingual.js +119 -0
  62. package/dist/turn_detector/multilingual.js.map +1 -0
  63. package/dist/turn_detector/utils.cjs +54 -0
  64. package/dist/turn_detector/utils.cjs.map +1 -0
  65. package/dist/turn_detector/utils.d.cts +35 -0
  66. package/dist/turn_detector/utils.d.ts +35 -0
  67. package/dist/turn_detector/utils.d.ts.map +1 -0
  68. package/dist/turn_detector/utils.js +29 -0
  69. package/dist/turn_detector/utils.js.map +1 -0
  70. package/dist/turn_detector/utils.test.cjs +196 -0
  71. package/dist/turn_detector/utils.test.cjs.map +1 -0
  72. package/dist/turn_detector/utils.test.d.cts +2 -0
  73. package/dist/turn_detector/utils.test.d.ts +2 -0
  74. package/dist/turn_detector/utils.test.d.ts.map +1 -0
  75. package/dist/turn_detector/utils.test.js +195 -0
  76. package/dist/turn_detector/utils.test.js.map +1 -0
  77. package/package.json +51 -0
  78. package/src/hf_utils.test.ts +392 -0
  79. package/src/hf_utils.ts +365 -0
  80. package/src/index.ts +34 -0
  81. package/src/onnxruntime.d.ts +8 -0
  82. package/src/turn_detector/base.ts +268 -0
  83. package/src/turn_detector/constants.ts +16 -0
  84. package/src/turn_detector/english.ts +27 -0
  85. package/src/turn_detector/index.ts +31 -0
  86. package/src/turn_detector/multilingual.ts +147 -0
  87. package/src/turn_detector/utils.test.ts +231 -0
  88. package/src/turn_detector/utils.ts +76 -0
@@ -0,0 +1,228 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var base_exports = {};
30
+ __export(base_exports, {
31
+ EOUModel: () => EOUModel,
32
+ EOURunnerBase: () => EOURunnerBase
33
+ });
34
+ module.exports = __toCommonJS(base_exports);
35
+ var import_transformers = require("@huggingface/transformers");
36
+ var import_agents = require("@livekit/agents");
37
+ var import_node_fs = require("node:fs");
38
+ var import_node_os = __toESM(require("node:os"), 1);
39
+ var import_onnxruntime_node = require("onnxruntime-node");
40
+ var import_hf_utils = require("../hf_utils.cjs");
41
+ var import_constants = require("./constants.cjs");
42
+ var import_utils = require("./utils.cjs");
43
+ class EOURunnerBase extends import_agents.InferenceRunner {
44
+ modelType;
45
+ modelRevision;
46
+ session;
47
+ tokenizer;
48
+ #logger = (0, import_agents.log)();
49
+ constructor(modelType) {
50
+ super();
51
+ this.modelType = modelType;
52
+ this.modelRevision = import_constants.MODEL_REVISIONS[modelType];
53
+ }
54
+ async initialize() {
55
+ const { AutoTokenizer } = await import("@huggingface/transformers");
56
+ try {
57
+ const onnxModelPath = await (0, import_hf_utils.downloadFileToCacheDir)({
58
+ repo: import_constants.HG_MODEL_REPO,
59
+ path: import_constants.ONNX_FILEPATH,
60
+ revision: this.modelRevision,
61
+ localFileOnly: true
62
+ });
63
+ const sessOptions = {
64
+ intraOpNumThreads: Math.max(1, Math.floor(import_node_os.default.cpus().length / 2)),
65
+ interOpNumThreads: 1,
66
+ executionProviders: [{ name: "cpu" }]
67
+ };
68
+ this.session = await import_onnxruntime_node.InferenceSession.create(onnxModelPath, sessOptions);
69
+ this.tokenizer = await AutoTokenizer.from_pretrained("livekit/turn-detector", {
70
+ revision: this.modelRevision,
71
+ local_files_only: true
72
+ });
73
+ } catch (e) {
74
+ const errorMessage = String(e);
75
+ if (errorMessage.includes("local_files_only=true") || errorMessage.includes("file was not found locally") || errorMessage.includes("File not found in cache")) {
76
+ throw new Error(
77
+ `agents-plugins-livekit failed to initialize ${this.modelType} EOU turn detector: Required model files not found locally.
78
+
79
+ This usually means you need to download the model files first. Please run one of these commands:
80
+
81
+ If using Node.js starter template:
82
+ pnpm download-files
83
+
84
+ If using the agent directly:
85
+ npx livekit-agents download-files
86
+
87
+ Then try running your application again.
88
+
89
+ Original error: ${e}`
90
+ );
91
+ }
92
+ throw new Error(
93
+ `agents-plugins-livekit failed to initialize ${this.modelType} EOU turn detector: ${e}`
94
+ );
95
+ }
96
+ }
97
+ async run(data) {
98
+ const startTime = Date.now();
99
+ const text = this.formatChatCtx(data);
100
+ const inputs = this.tokenizer.encode(text, { add_special_tokens: false });
101
+ this.#logger.debug({ inputs: JSON.stringify(inputs), text }, "EOU inputs");
102
+ const outputs = await this.session.run(
103
+ { input_ids: new import_onnxruntime_node.Tensor("int64", inputs, [1, inputs.length]) },
104
+ ["prob"]
105
+ );
106
+ const probData = outputs.prob.data;
107
+ const eouProbability = probData[probData.length - 1];
108
+ const endTime = Date.now();
109
+ const result = {
110
+ eouProbability,
111
+ input: text,
112
+ duration: (endTime - startTime) / 1e3
113
+ };
114
+ this.#logger.child({ result }).debug("eou prediction");
115
+ return result;
116
+ }
117
+ async close() {
118
+ var _a;
119
+ await ((_a = this.session) == null ? void 0 : _a.release());
120
+ }
121
+ formatChatCtx(chatCtx) {
122
+ const newChatCtx = [];
123
+ let lastMsg = void 0;
124
+ for (const msg of chatCtx) {
125
+ const content = msg.content;
126
+ if (!content) continue;
127
+ const norm = (0, import_utils.normalizeText)(content);
128
+ if (lastMsg !== void 0 && lastMsg.role === msg.role) {
129
+ lastMsg.content += ` ${norm}`;
130
+ } else {
131
+ newChatCtx.push({ role: msg.role, content: norm });
132
+ lastMsg = newChatCtx[newChatCtx.length - 1];
133
+ }
134
+ }
135
+ const convoText = this.tokenizer.apply_chat_template(newChatCtx, {
136
+ add_generation_prompt: false,
137
+ tokenize: false
138
+ });
139
+ return convoText.slice(0, convoText.lastIndexOf("<|im_end|>"));
140
+ }
141
+ }
142
+ class EOUModel {
143
+ modelType;
144
+ executor;
145
+ threshold;
146
+ loadLanguages;
147
+ languagesFuture = new import_agents.Future();
148
+ #logger = (0, import_agents.log)();
149
+ get model() {
150
+ return import_constants.MODEL_REVISIONS[this.modelType];
151
+ }
152
+ get provider() {
153
+ return "livekit";
154
+ }
155
+ constructor(opts) {
156
+ const {
157
+ modelType = "en",
158
+ executor = (0, import_agents.getJobContext)().inferenceExecutor,
159
+ unlikelyThreshold,
160
+ loadLanguages = true
161
+ } = opts;
162
+ this.modelType = modelType;
163
+ this.executor = executor;
164
+ this.threshold = unlikelyThreshold;
165
+ this.loadLanguages = loadLanguages;
166
+ if (loadLanguages) {
167
+ (0, import_hf_utils.downloadFileToCacheDir)({
168
+ repo: import_constants.HG_MODEL_REPO,
169
+ path: "languages.json",
170
+ revision: import_constants.MODEL_REVISIONS[modelType],
171
+ localFileOnly: true
172
+ }).then((path) => {
173
+ this.languagesFuture.resolve(JSON.parse((0, import_node_fs.readFileSync)(path, "utf8")));
174
+ });
175
+ }
176
+ }
177
+ async unlikelyThreshold(language) {
178
+ if (language === void 0) {
179
+ return this.threshold;
180
+ }
181
+ const lang = language.toLowerCase();
182
+ const languages = await this.languagesFuture.await;
183
+ let langData = languages[lang];
184
+ if (langData === void 0 && lang.includes("-")) {
185
+ langData = languages[(0, import_agents.getBaseLanguage)(lang)];
186
+ }
187
+ if (langData === void 0) {
188
+ this.#logger.warn(`Language ${language} not supported by EOU model`);
189
+ return void 0;
190
+ }
191
+ return this.threshold !== void 0 ? this.threshold : langData.threshold;
192
+ }
193
+ async supportsLanguage(language) {
194
+ return await this.unlikelyThreshold(language) !== void 0;
195
+ }
196
+ // `_timeoutMs` is part of the unified `_TurnDetector` contract (milliseconds,
197
+ // matching the audio EOT detector). Text-based inference is bounded by the IPC
198
+ // executor itself, so this detector does not use the value.
199
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
200
+ async predictEndOfTurn(chatCtx, _timeoutMs) {
201
+ let messages = [];
202
+ for (const message of chatCtx.items) {
203
+ if (message.type !== "message" || message.role === "system" || message.role === "developer") {
204
+ continue;
205
+ }
206
+ for (const content of message.content) {
207
+ if (typeof content === "string") {
208
+ messages.push({
209
+ role: message.role === "assistant" ? "assistant" : "user",
210
+ content
211
+ });
212
+ }
213
+ }
214
+ }
215
+ messages = messages.slice(-import_constants.MAX_HISTORY_TURNS);
216
+ const result = await this.executor.doInference(this.inferenceMethod(), messages);
217
+ if (result === void 0) {
218
+ throw new Error("EOU inference should always returns a result");
219
+ }
220
+ return result.eouProbability;
221
+ }
222
+ }
223
+ // Annotate the CommonJS export names for ESM import in node:
224
+ 0 && (module.exports = {
225
+ EOUModel,
226
+ EOURunnerBase
227
+ });
228
+ //# sourceMappingURL=base.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/turn_detector/base.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { type PreTrainedTokenizer } from '@huggingface/transformers';\nimport type { ipc, llm } from '@livekit/agents';\nimport { Future, InferenceRunner, getBaseLanguage, getJobContext, log } from '@livekit/agents';\nimport { readFileSync } from 'node:fs';\nimport os from 'node:os';\nimport { InferenceSession, Tensor } from 'onnxruntime-node';\nimport { downloadFileToCacheDir } from '../hf_utils.js';\nimport {\n type EOUModelType,\n HG_MODEL_REPO,\n MAX_HISTORY_TURNS,\n MODEL_REVISIONS,\n ONNX_FILEPATH,\n} from './constants.js';\nimport { normalizeText } from './utils.js';\n\ntype RawChatItem = { role: string; content: string };\n\ntype EOUOutput = { eouProbability: number; input: string; duration: number };\n\nexport abstract class EOURunnerBase extends InferenceRunner<RawChatItem[], EOUOutput> {\n private modelType: EOUModelType;\n private modelRevision: string;\n\n private session?: InferenceSession;\n private tokenizer?: PreTrainedTokenizer;\n\n #logger = log();\n\n constructor(modelType: EOUModelType) {\n super();\n this.modelType = modelType;\n this.modelRevision = MODEL_REVISIONS[modelType];\n }\n\n async initialize() {\n const { AutoTokenizer } = await import('@huggingface/transformers');\n\n try {\n const onnxModelPath = await downloadFileToCacheDir({\n repo: HG_MODEL_REPO,\n path: ONNX_FILEPATH,\n revision: this.modelRevision,\n localFileOnly: true,\n });\n\n // TODO(brian): support session config once onnxruntime-node supports it\n const sessOptions: InferenceSession.SessionOptions = {\n intraOpNumThreads: Math.max(1, Math.floor(os.cpus().length / 2)),\n interOpNumThreads: 1,\n executionProviders: [{ name: 'cpu' }],\n };\n\n this.session = await InferenceSession.create(onnxModelPath, sessOptions);\n\n this.tokenizer = await AutoTokenizer.from_pretrained('livekit/turn-detector', {\n revision: this.modelRevision,\n local_files_only: true,\n });\n } catch (e) {\n const errorMessage = String(e);\n\n // Check if the error is related to missing local files\n if (\n errorMessage.includes('local_files_only=true') ||\n errorMessage.includes('file was not found locally') ||\n errorMessage.includes('File not found in cache')\n ) {\n throw new Error(\n `agents-plugins-livekit failed to initialize ${this.modelType} EOU turn detector: Required model files not found locally.\\n\\n` +\n `This usually means you need to download the model files first. Please run one of these commands:\\n\\n` +\n ` If using Node.js starter template:\\n` +\n ` pnpm download-files\\n\\n` +\n ` If using the agent directly:\\n` +\n ` npx livekit-agents download-files\\n\\n` +\n `Then try running your application again.\\n\\n` +\n `Original error: ${e}`,\n );\n }\n\n throw new Error(\n `agents-plugins-livekit failed to initialize ${this.modelType} EOU turn detector: ${e}`,\n );\n }\n }\n\n async run(data: RawChatItem[]) {\n const startTime = Date.now();\n\n const text = this.formatChatCtx(data);\n\n const inputs = this.tokenizer!.encode(text, { add_special_tokens: false });\n this.#logger.debug({ inputs: JSON.stringify(inputs), text }, 'EOU inputs');\n\n const outputs = await this.session!.run(\n { input_ids: new Tensor('int64', inputs, [1, inputs.length]) },\n ['prob'],\n );\n\n const probData = outputs.prob!.data;\n // should be the logits of the last token\n const eouProbability = probData[probData.length - 1] as number;\n const endTime = Date.now();\n\n const result = {\n eouProbability,\n input: text,\n duration: (endTime - startTime) / 1000,\n };\n\n this.#logger.child({ result }).debug('eou prediction');\n return result;\n }\n\n async close() {\n await this.session?.release();\n }\n\n private formatChatCtx(chatCtx: RawChatItem[]): string {\n const newChatCtx: RawChatItem[] = [];\n let lastMsg: RawChatItem | undefined = undefined;\n\n for (const msg of chatCtx) {\n const content = msg.content;\n if (!content) continue;\n\n const norm = normalizeText(content);\n\n // need to combine adjacent turns together to match training data\n if (lastMsg !== undefined && lastMsg.role === msg.role) {\n lastMsg.content += ` ${norm}`;\n } else {\n newChatCtx.push({ role: msg.role, content: norm });\n lastMsg = newChatCtx[newChatCtx.length - 1]!;\n }\n }\n\n // TODO(brian): investigate add_special_tokens options\n const convoText = this.tokenizer!.apply_chat_template(newChatCtx, {\n add_generation_prompt: false,\n tokenize: false,\n }) as string;\n\n // remove the EOU token from current utterance\n return convoText.slice(0, convoText.lastIndexOf('<|im_end|>'));\n }\n}\n\nexport interface EOUModelOptions {\n modelType: EOUModelType;\n executor?: ipc.InferenceExecutor;\n unlikelyThreshold?: number;\n loadLanguages?: boolean;\n}\n\ntype LanguageData = {\n threshold: number;\n};\n\nexport abstract class EOUModel {\n private modelType: EOUModelType;\n private executor: ipc.InferenceExecutor;\n private threshold: number | undefined;\n private loadLanguages: boolean;\n\n protected languagesFuture: Future<Record<string, LanguageData>> = new Future();\n\n #logger = log();\n\n get model(): string {\n return MODEL_REVISIONS[this.modelType];\n }\n\n get provider(): string {\n return 'livekit';\n }\n\n constructor(opts: EOUModelOptions) {\n const {\n modelType = 'en',\n executor = getJobContext().inferenceExecutor,\n unlikelyThreshold,\n loadLanguages = true,\n } = opts;\n\n this.modelType = modelType;\n this.executor = executor;\n this.threshold = unlikelyThreshold;\n this.loadLanguages = loadLanguages;\n\n if (loadLanguages) {\n downloadFileToCacheDir({\n repo: HG_MODEL_REPO,\n path: 'languages.json',\n revision: MODEL_REVISIONS[modelType],\n localFileOnly: true,\n }).then((path) => {\n this.languagesFuture.resolve(JSON.parse(readFileSync(path, 'utf8')));\n });\n }\n }\n\n async unlikelyThreshold(language?: string): Promise<number | undefined> {\n if (language === undefined) {\n return this.threshold;\n }\n\n const lang = language.toLowerCase();\n const languages = await this.languagesFuture.await;\n\n // try the full language code first\n let langData = languages[lang];\n\n if (langData === undefined && lang.includes('-')) {\n langData = languages[getBaseLanguage(lang)];\n }\n\n if (langData === undefined) {\n this.#logger.warn(`Language ${language} not supported by EOU model`);\n return undefined;\n }\n\n // if a custom threshold is provided, use it\n return this.threshold !== undefined ? this.threshold : langData.threshold;\n }\n\n async supportsLanguage(language?: string): Promise<boolean> {\n return (await this.unlikelyThreshold(language)) !== undefined;\n }\n\n // `_timeoutMs` is part of the unified `_TurnDetector` contract (milliseconds,\n // matching the audio EOT detector). Text-based inference is bounded by the IPC\n // executor itself, so this detector does not use the value.\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async predictEndOfTurn(chatCtx: llm.ChatContext, _timeoutMs?: number): Promise<number> {\n let messages: RawChatItem[] = [];\n\n for (const message of chatCtx.items) {\n // skip system and developer messages or tool call messages\n if (message.type !== 'message' || message.role === 'system' || message.role === 'developer') {\n continue;\n }\n\n for (const content of message.content) {\n if (typeof content === 'string') {\n messages.push({\n role: message.role === 'assistant' ? 'assistant' : 'user',\n content: content,\n });\n }\n }\n }\n\n messages = messages.slice(-MAX_HISTORY_TURNS);\n\n const result = await this.executor.doInference(this.inferenceMethod(), messages);\n if (result === undefined) {\n throw new Error('EOU inference should always returns a result');\n }\n\n return (result as EOUOutput).eouProbability;\n }\n\n abstract inferenceMethod(): string;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,0BAAyC;AAEzC,oBAA6E;AAC7E,qBAA6B;AAC7B,qBAAe;AACf,8BAAyC;AACzC,sBAAuC;AACvC,uBAMO;AACP,mBAA8B;AAMvB,MAAe,sBAAsB,8BAA0C;AAAA,EAC5E;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EAER,cAAU,mBAAI;AAAA,EAEd,YAAY,WAAyB;AACnC,UAAM;AACN,SAAK,YAAY;AACjB,SAAK,gBAAgB,iCAAgB,SAAS;AAAA,EAChD;AAAA,EAEA,MAAM,aAAa;AACjB,UAAM,E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AQ,SAAS,YAAY,QAAQ,SAAS,aAAa;AAC3F;AAAA,MACF;AAEA,iBAAW,WAAW,QAAQ,SAAS;AACrC,YAAI,OAAO,YAAY,UAAU;AAC/B,mBAAS,KAAK;AAAA,YACZ,MAAM,QAAQ,SAAS,cAAc,cAAc;AAAA,YACnD;AAAA,UACF,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAEA,eAAW,SAAS,MAAM,CAAC,kCAAiB;AAE5C,UAAM,SAAS,MAAM,KAAK,SAAS,YAAY,KAAK,gBAAgB,GAAG,QAAQ;AAC/E,QAAI,WAAW,QAAW;AACxB,YAAM,IAAI,MAAM,8CAA8C;AAAA,IAChE;AAEA,WAAQ,OAAqB;AAAA,EAC/B;AAGF;","names":["os"]}
@@ -0,0 +1,54 @@
1
+ import type { ipc, llm } from '@livekit/agents';
2
+ import { Future, InferenceRunner } from '@livekit/agents';
3
+ import { type EOUModelType } from './constants.js';
4
+ type RawChatItem = {
5
+ role: string;
6
+ content: string;
7
+ };
8
+ type EOUOutput = {
9
+ eouProbability: number;
10
+ input: string;
11
+ duration: number;
12
+ };
13
+ export declare abstract class EOURunnerBase extends InferenceRunner<RawChatItem[], EOUOutput> {
14
+ #private;
15
+ private modelType;
16
+ private modelRevision;
17
+ private session?;
18
+ private tokenizer?;
19
+ constructor(modelType: EOUModelType);
20
+ initialize(): Promise<void>;
21
+ run(data: RawChatItem[]): Promise<{
22
+ eouProbability: number;
23
+ input: string;
24
+ duration: number;
25
+ }>;
26
+ close(): Promise<void>;
27
+ private formatChatCtx;
28
+ }
29
+ export interface EOUModelOptions {
30
+ modelType: EOUModelType;
31
+ executor?: ipc.InferenceExecutor;
32
+ unlikelyThreshold?: number;
33
+ loadLanguages?: boolean;
34
+ }
35
+ type LanguageData = {
36
+ threshold: number;
37
+ };
38
+ export declare abstract class EOUModel {
39
+ #private;
40
+ private modelType;
41
+ private executor;
42
+ private threshold;
43
+ private loadLanguages;
44
+ protected languagesFuture: Future<Record<string, LanguageData>>;
45
+ get model(): string;
46
+ get provider(): string;
47
+ constructor(opts: EOUModelOptions);
48
+ unlikelyThreshold(language?: string): Promise<number | undefined>;
49
+ supportsLanguage(language?: string): Promise<boolean>;
50
+ predictEndOfTurn(chatCtx: llm.ChatContext, _timeoutMs?: number): Promise<number>;
51
+ abstract inferenceMethod(): string;
52
+ }
53
+ export {};
54
+ //# sourceMappingURL=base.d.ts.map
@@ -0,0 +1,54 @@
1
+ import type { ipc, llm } from '@livekit/agents';
2
+ import { Future, InferenceRunner } from '@livekit/agents';
3
+ import { type EOUModelType } from './constants.js';
4
+ type RawChatItem = {
5
+ role: string;
6
+ content: string;
7
+ };
8
+ type EOUOutput = {
9
+ eouProbability: number;
10
+ input: string;
11
+ duration: number;
12
+ };
13
+ export declare abstract class EOURunnerBase extends InferenceRunner<RawChatItem[], EOUOutput> {
14
+ #private;
15
+ private modelType;
16
+ private modelRevision;
17
+ private session?;
18
+ private tokenizer?;
19
+ constructor(modelType: EOUModelType);
20
+ initialize(): Promise<void>;
21
+ run(data: RawChatItem[]): Promise<{
22
+ eouProbability: number;
23
+ input: string;
24
+ duration: number;
25
+ }>;
26
+ close(): Promise<void>;
27
+ private formatChatCtx;
28
+ }
29
+ export interface EOUModelOptions {
30
+ modelType: EOUModelType;
31
+ executor?: ipc.InferenceExecutor;
32
+ unlikelyThreshold?: number;
33
+ loadLanguages?: boolean;
34
+ }
35
+ type LanguageData = {
36
+ threshold: number;
37
+ };
38
+ export declare abstract class EOUModel {
39
+ #private;
40
+ private modelType;
41
+ private executor;
42
+ private threshold;
43
+ private loadLanguages;
44
+ protected languagesFuture: Future<Record<string, LanguageData>>;
45
+ get model(): string;
46
+ get provider(): string;
47
+ constructor(opts: EOUModelOptions);
48
+ unlikelyThreshold(language?: string): Promise<number | undefined>;
49
+ supportsLanguage(language?: string): Promise<boolean>;
50
+ predictEndOfTurn(chatCtx: llm.ChatContext, _timeoutMs?: number): Promise<number>;
51
+ abstract inferenceMethod(): string;
52
+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C,OAAO,CAAC,SAAS,CAAqB;IACtC,OAAO,CAAC,aAAa,CAAU;IAE/B,SAAS,CAAC,eAAe,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC,CAAgB;IAI/E,IAAI,KAAK,IAAI,MAAM,CAElB;IAED,IAAI,QAAQ,IAAI,MAAM,CAErB;gBAEW,IAAI,EAAE,eAAe;IAyB3B,iBAAiB,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC;IAwBjE,gBAAgB,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAQrD,gBAAgB,CAAC,OAAO,EAAE,GAAG,CAAC,WAAW,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IA6BtF,QAAQ,CAAC,eAAe,IAAI,MAAM;CACnC"}
@@ -0,0 +1,198 @@
1
+ import {} from "@huggingface/transformers";
2
+ import { Future, InferenceRunner, getBaseLanguage, getJobContext, log } from "@livekit/agents";
3
+ import { readFileSync } from "node:fs";
4
+ import os from "node:os";
5
+ import { InferenceSession, Tensor } from "onnxruntime-node";
6
+ import { downloadFileToCacheDir } from "../hf_utils.js";
7
+ import {
8
+ HG_MODEL_REPO,
9
+ MAX_HISTORY_TURNS,
10
+ MODEL_REVISIONS,
11
+ ONNX_FILEPATH
12
+ } from "./constants.js";
13
+ import { normalizeText } from "./utils.js";
14
+ class EOURunnerBase extends InferenceRunner {
15
+ modelType;
16
+ modelRevision;
17
+ session;
18
+ tokenizer;
19
+ #logger = log();
20
+ constructor(modelType) {
21
+ super();
22
+ this.modelType = modelType;
23
+ this.modelRevision = MODEL_REVISIONS[modelType];
24
+ }
25
+ async initialize() {
26
+ const { AutoTokenizer } = await import("@huggingface/transformers");
27
+ try {
28
+ const onnxModelPath = await downloadFileToCacheDir({
29
+ repo: HG_MODEL_REPO,
30
+ path: ONNX_FILEPATH,
31
+ revision: this.modelRevision,
32
+ localFileOnly: true
33
+ });
34
+ const sessOptions = {
35
+ intraOpNumThreads: Math.max(1, Math.floor(os.cpus().length / 2)),
36
+ interOpNumThreads: 1,
37
+ executionProviders: [{ name: "cpu" }]
38
+ };
39
+ this.session = await InferenceSession.create(onnxModelPath, sessOptions);
40
+ this.tokenizer = await AutoTokenizer.from_pretrained("livekit/turn-detector", {
41
+ revision: this.modelRevision,
42
+ local_files_only: true
43
+ });
44
+ } catch (e) {
45
+ const errorMessage = String(e);
46
+ if (errorMessage.includes("local_files_only=true") || errorMessage.includes("file was not found locally") || errorMessage.includes("File not found in cache")) {
47
+ throw new Error(
48
+ `agents-plugins-livekit failed to initialize ${this.modelType} EOU turn detector: Required model files not found locally.
49
+
50
+ This usually means you need to download the model files first. Please run one of these commands:
51
+
52
+ If using Node.js starter template:
53
+ pnpm download-files
54
+
55
+ If using the agent directly:
56
+ npx livekit-agents download-files
57
+
58
+ Then try running your application again.
59
+
60
+ Original error: ${e}`
61
+ );
62
+ }
63
+ throw new Error(
64
+ `agents-plugins-livekit failed to initialize ${this.modelType} EOU turn detector: ${e}`
65
+ );
66
+ }
67
+ }
68
+ async run(data) {
69
+ const startTime = Date.now();
70
+ const text = this.formatChatCtx(data);
71
+ const inputs = this.tokenizer.encode(text, { add_special_tokens: false });
72
+ this.#logger.debug({ inputs: JSON.stringify(inputs), text }, "EOU inputs");
73
+ const outputs = await this.session.run(
74
+ { input_ids: new Tensor("int64", inputs, [1, inputs.length]) },
75
+ ["prob"]
76
+ );
77
+ const probData = outputs.prob.data;
78
+ const eouProbability = probData[probData.length - 1];
79
+ const endTime = Date.now();
80
+ const result = {
81
+ eouProbability,
82
+ input: text,
83
+ duration: (endTime - startTime) / 1e3
84
+ };
85
+ this.#logger.child({ result }).debug("eou prediction");
86
+ return result;
87
+ }
88
+ async close() {
89
+ var _a;
90
+ await ((_a = this.session) == null ? void 0 : _a.release());
91
+ }
92
+ formatChatCtx(chatCtx) {
93
+ const newChatCtx = [];
94
+ let lastMsg = void 0;
95
+ for (const msg of chatCtx) {
96
+ const content = msg.content;
97
+ if (!content) continue;
98
+ const norm = normalizeText(content);
99
+ if (lastMsg !== void 0 && lastMsg.role === msg.role) {
100
+ lastMsg.content += ` ${norm}`;
101
+ } else {
102
+ newChatCtx.push({ role: msg.role, content: norm });
103
+ lastMsg = newChatCtx[newChatCtx.length - 1];
104
+ }
105
+ }
106
+ const convoText = this.tokenizer.apply_chat_template(newChatCtx, {
107
+ add_generation_prompt: false,
108
+ tokenize: false
109
+ });
110
+ return convoText.slice(0, convoText.lastIndexOf("<|im_end|>"));
111
+ }
112
+ }
113
+ class EOUModel {
114
+ modelType;
115
+ executor;
116
+ threshold;
117
+ loadLanguages;
118
+ languagesFuture = new Future();
119
+ #logger = log();
120
+ get model() {
121
+ return MODEL_REVISIONS[this.modelType];
122
+ }
123
+ get provider() {
124
+ return "livekit";
125
+ }
126
+ constructor(opts) {
127
+ const {
128
+ modelType = "en",
129
+ executor = getJobContext().inferenceExecutor,
130
+ unlikelyThreshold,
131
+ loadLanguages = true
132
+ } = opts;
133
+ this.modelType = modelType;
134
+ this.executor = executor;
135
+ this.threshold = unlikelyThreshold;
136
+ this.loadLanguages = loadLanguages;
137
+ if (loadLanguages) {
138
+ downloadFileToCacheDir({
139
+ repo: HG_MODEL_REPO,
140
+ path: "languages.json",
141
+ revision: MODEL_REVISIONS[modelType],
142
+ localFileOnly: true
143
+ }).then((path) => {
144
+ this.languagesFuture.resolve(JSON.parse(readFileSync(path, "utf8")));
145
+ });
146
+ }
147
+ }
148
+ async unlikelyThreshold(language) {
149
+ if (language === void 0) {
150
+ return this.threshold;
151
+ }
152
+ const lang = language.toLowerCase();
153
+ const languages = await this.languagesFuture.await;
154
+ let langData = languages[lang];
155
+ if (langData === void 0 && lang.includes("-")) {
156
+ langData = languages[getBaseLanguage(lang)];
157
+ }
158
+ if (langData === void 0) {
159
+ this.#logger.warn(`Language ${language} not supported by EOU model`);
160
+ return void 0;
161
+ }
162
+ return this.threshold !== void 0 ? this.threshold : langData.threshold;
163
+ }
164
+ async supportsLanguage(language) {
165
+ return await this.unlikelyThreshold(language) !== void 0;
166
+ }
167
+ // `_timeoutMs` is part of the unified `_TurnDetector` contract (milliseconds,
168
+ // matching the audio EOT detector). Text-based inference is bounded by the IPC
169
+ // executor itself, so this detector does not use the value.
170
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
171
+ async predictEndOfTurn(chatCtx, _timeoutMs) {
172
+ let messages = [];
173
+ for (const message of chatCtx.items) {
174
+ if (message.type !== "message" || message.role === "system" || message.role === "developer") {
175
+ continue;
176
+ }
177
+ for (const content of message.content) {
178
+ if (typeof content === "string") {
179
+ messages.push({
180
+ role: message.role === "assistant" ? "assistant" : "user",
181
+ content
182
+ });
183
+ }
184
+ }
185
+ }
186
+ messages = messages.slice(-MAX_HISTORY_TURNS);
187
+ const result = await this.executor.doInference(this.inferenceMethod(), messages);
188
+ if (result === void 0) {
189
+ throw new Error("EOU inference should always returns a result");
190
+ }
191
+ return result.eouProbability;
192
+ }
193
+ }
194
+ export {
195
+ EOUModel,
196
+ EOURunnerBase
197
+ };
198
+ //# sourceMappingURL=base.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/turn_detector/base.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { type PreTrainedTokenizer } from '@huggingface/transformers';\nimport type { ipc, llm } from '@livekit/agents';\nimport { Future, InferenceRunner, getBaseLanguage, getJobContext, log } from '@livekit/agents';\nimport { readFileSync } from 'node:fs';\nimport os from 'node:os';\nimport { InferenceSession, Tensor } from 'onnxruntime-node';\nimport { downloadFileToCacheDir } from '../hf_utils.js';\nimport {\n type EOUModelType,\n HG_MODEL_REPO,\n MAX_HISTORY_TURNS,\n MODEL_REVISIONS,\n ONNX_FILEPATH,\n} from './constants.js';\nimport { normalizeText } from './utils.js';\n\ntype RawChatItem = { role: string; content: string };\n\ntype EOUOutput = { eouProbability: number; input: string; duration: number };\n\nexport abstract class EOURunnerBase extends InferenceRunner<RawChatItem[], EOUOutput> {\n private modelType: EOUModelType;\n private modelRevision: string;\n\n private session?: InferenceSession;\n private tokenizer?: PreTrainedTokenizer;\n\n #logger = log();\n\n constructor(modelType: EOUModelType) {\n super();\n this.modelType = modelType;\n this.modelRevision = MODEL_REVISIONS[modelType];\n }\n\n async initialize() {\n const { AutoTokenizer } = await import('@huggingface/transformers');\n\n try {\n const onnxModelPath = await downloadFileToCacheDir({\n repo: HG_MODEL_REPO,\n path: ONNX_FILEPATH,\n revision: this.modelRevision,\n localFileOnly: true,\n });\n\n // TODO(brian): support session config once onnxruntime-node supports it\n const sessOptions: InferenceSession.SessionOptions = {\n intraOpNumThreads: Math.max(1, Math.floor(os.cpus().length / 2)),\n interOpNumThreads: 1,\n executionProviders: [{ name: 'cpu' }],\n };\n\n this.session = await InferenceSession.create(onnxModelPath, sessOptions);\n\n this.tokenizer = await AutoTokenizer.from_pretrained('livekit/turn-detector', {\n revision: this.modelRevision,\n local_files_only: true,\n });\n } catch (e) {\n const errorMessage = String(e);\n\n // Check if the error is related to missing local files\n if (\n errorMessage.includes('local_files_only=true') ||\n errorMessage.includes('file was not found locally') ||\n errorMessage.includes('File not found in cache')\n ) {\n throw new Error(\n `agents-plugins-livekit failed to initialize ${this.modelType} EOU turn detector: Required model files not found locally.\\n\\n` +\n `This usually means you need to download the model files first. Please run one of these commands:\\n\\n` +\n ` If using Node.js starter template:\\n` +\n ` pnpm download-files\\n\\n` +\n ` If using the agent directly:\\n` +\n ` npx livekit-agents download-files\\n\\n` +\n `Then try running your application again.\\n\\n` +\n `Original error: ${e}`,\n );\n }\n\n throw new Error(\n `agents-plugins-livekit failed to initialize ${this.modelType} EOU turn detector: ${e}`,\n );\n }\n }\n\n async run(data: RawChatItem[]) {\n const startTime = Date.now();\n\n const text = this.formatChatCtx(data);\n\n const inputs = this.tokenizer!.encode(text, { add_special_tokens: false });\n this.#logger.debug({ inputs: JSON.stringify(inputs), text }, 'EOU inputs');\n\n const outputs = await this.session!.run(\n { input_ids: new Tensor('int64', inputs, [1, inputs.length]) },\n ['prob'],\n );\n\n const probData = outputs.prob!.data;\n // should be the logits of the last token\n const eouProbability = probData[probData.length - 1] as number;\n const endTime = Date.now();\n\n const result = {\n eouProbability,\n input: text,\n duration: (endTime - startTime) / 1000,\n };\n\n this.#logger.child({ result }).debug('eou prediction');\n return result;\n }\n\n async close() {\n await this.session?.release();\n }\n\n private formatChatCtx(chatCtx: RawChatItem[]): string {\n const newChatCtx: RawChatItem[] = [];\n let lastMsg: RawChatItem | undefined = undefined;\n\n for (const msg of chatCtx) {\n const content = msg.content;\n if (!content) continue;\n\n const norm = normalizeText(content);\n\n // need to combine adjacent turns together to match training data\n if (lastMsg !== undefined && lastMsg.role === msg.role) {\n lastMsg.content += ` ${norm}`;\n } else {\n newChatCtx.push({ role: msg.role, content: norm });\n lastMsg = newChatCtx[newChatCtx.length - 1]!;\n }\n }\n\n // TODO(brian): investigate add_special_tokens options\n const convoText = this.tokenizer!.apply_chat_template(newChatCtx, {\n add_generation_prompt: false,\n tokenize: false,\n }) as string;\n\n // remove the EOU token from current utterance\n return convoText.slice(0, convoText.lastIndexOf('<|im_end|>'));\n }\n}\n\nexport interface EOUModelOptions {\n modelType: EOUModelType;\n executor?: ipc.InferenceExecutor;\n unlikelyThreshold?: number;\n loadLanguages?: boolean;\n}\n\ntype LanguageData = {\n threshold: number;\n};\n\nexport abstract class EOUModel {\n private modelType: EOUModelType;\n private executor: ipc.InferenceExecutor;\n private threshold: number | undefined;\n private loadLanguages: boolean;\n\n protected languagesFuture: Future<Record<string, LanguageData>> = new Future();\n\n #logger = log();\n\n get model(): string {\n return MODEL_REVISIONS[this.modelType];\n }\n\n get provider(): string {\n return 'livekit';\n }\n\n constructor(opts: EOUModelOptions) {\n const {\n modelType = 'en',\n executor = getJobContext().inferenceExecutor,\n unlikelyThreshold,\n loadLanguages = true,\n } = opts;\n\n this.modelType = modelType;\n this.executor = executor;\n this.threshold = unlikelyThreshold;\n this.loadLanguages = loadLanguages;\n\n if (loadLanguages) {\n downloadFileToCacheDir({\n repo: HG_MODEL_REPO,\n path: 'languages.json',\n revision: MODEL_REVISIONS[modelType],\n localFileOnly: true,\n }).then((path) => {\n this.languagesFuture.resolve(JSON.parse(readFileSync(path, 'utf8')));\n });\n }\n }\n\n async unlikelyThreshold(language?: string): Promise<number | undefined> {\n if (language === undefined) {\n return this.threshold;\n }\n\n const lang = language.toLowerCase();\n const languages = await this.languagesFuture.await;\n\n // try the full language code first\n let langData = languages[lang];\n\n if (langData === undefined && lang.includes('-')) {\n langData = languages[getBaseLanguage(lang)];\n }\n\n if (langData === undefined) {\n this.#logger.warn(`Language ${language} not supported by EOU model`);\n return undefined;\n }\n\n // if a custom threshold is provided, use it\n return this.threshold !== undefined ? this.threshold : langData.threshold;\n }\n\n async supportsLanguage(language?: string): Promise<boolean> {\n return (await this.unlikelyThreshold(language)) !== undefined;\n }\n\n // `_timeoutMs` is part of the unified `_TurnDetector` contract (milliseconds,\n // matching the audio EOT detector). Text-based inference is bounded by the IPC\n // executor itself, so this detector does not use the value.\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async predictEndOfTurn(chatCtx: llm.ChatContext, _timeoutMs?: number): Promise<number> {\n let messages: RawChatItem[] = [];\n\n for (const message of chatCtx.items) {\n // skip system and developer messages or tool call messages\n if (message.type !== 'message' || message.role === 'system' || message.role === 'developer') {\n continue;\n }\n\n for (const content of message.content) {\n if (typeof content === 'string') {\n messages.push({\n role: message.role === 'assistant' ? 'assistant' : 'user',\n content: content,\n });\n }\n }\n }\n\n messages = messages.slice(-MAX_HISTORY_TURNS);\n\n const result = await this.executor.doInference(this.inferenceMethod(), messages);\n if (result === undefined) {\n throw new Error('EOU inference should always returns a result');\n }\n\n return (result as EOUOutput).eouProbability;\n }\n\n abstract inferenceMethod(): string;\n}\n"],"mappings":"AAGA,eAAy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AU,gBAAgB,IAAI,CAAC;AAAA,IAC5C;AAEA,QAAI,aAAa,QAAW;AAC1B,WAAK,QAAQ,KAAK,YAAY,QAAQ,6BAA6B;AACnE,aAAO;AAAA,IACT;AAGA,WAAO,KAAK,cAAc,SAAY,KAAK,YAAY,SAAS;AAAA,EAClE;AAAA,EAEA,MAAM,iBAAiB,UAAqC;AAC1D,WAAQ,MAAM,KAAK,kBAAkB,QAAQ,MAAO;AAAA,EACtD;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,iBAAiB,SAA0B,YAAsC;AACrF,QAAI,WAA0B,CAAC;AAE/B,eAAW,WAAW,QAAQ,OAAO;AAEnC,UAAI,QAAQ,SAAS,aAAa,QAAQ,SAAS,YAAY,QAAQ,SAAS,aAAa;AAC3F;AAAA,MACF;AAEA,iBAAW,WAAW,QAAQ,SAAS;AACrC,YAAI,OAAO,YAAY,UAAU;AAC/B,mBAAS,KAAK;AAAA,YACZ,MAAM,QAAQ,SAAS,cAAc,cAAc;AAAA,YACnD;AAAA,UACF,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAEA,eAAW,SAAS,MAAM,CAAC,iBAAiB;AAE5C,UAAM,SAAS,MAAM,KAAK,SAAS,YAAY,KAAK,gBAAgB,GAAG,QAAQ;AAC/E,QAAI,WAAW,QAAW;AACxB,YAAM,IAAI,MAAM,8CAA8C;AAAA,IAChE;AAEA,WAAQ,OAAqB;AAAA,EAC/B;AAGF;","names":[]}
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var constants_exports = {};
20
+ __export(constants_exports, {
21
+ HG_MODEL_REPO: () => HG_MODEL_REPO,
22
+ MAX_HISTORY_TOKENS: () => MAX_HISTORY_TOKENS,
23
+ MAX_HISTORY_TURNS: () => MAX_HISTORY_TURNS,
24
+ MODEL_REVISIONS: () => MODEL_REVISIONS,
25
+ ONNX_FILEPATH: () => ONNX_FILEPATH
26
+ });
27
+ module.exports = __toCommonJS(constants_exports);
28
+ const MAX_HISTORY_TOKENS = 128;
29
+ const MAX_HISTORY_TURNS = 6;
30
+ const MODEL_REVISIONS = {
31
+ en: "v1.2.2-en",
32
+ multilingual: "v0.4.1-intl"
33
+ };
34
+ const HG_MODEL_REPO = "livekit/turn-detector";
35
+ const ONNX_FILEPATH = "onnx/model_q8.onnx";
36
+ // Annotate the CommonJS export names for ESM import in node:
37
+ 0 && (module.exports = {
38
+ HG_MODEL_REPO,
39
+ MAX_HISTORY_TOKENS,
40
+ MAX_HISTORY_TURNS,
41
+ MODEL_REVISIONS,
42
+ ONNX_FILEPATH
43
+ });
44
+ //# sourceMappingURL=constants.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/turn_detector/constants.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nexport type EOUModelType = 'en' | 'multilingual';\n\nexport const MAX_HISTORY_TOKENS = 128;\nexport const MAX_HISTORY_TURNS = 6;\n\nexport const MODEL_REVISIONS: Record<EOUModelType, string> = {\n en: 'v1.2.2-en',\n multilingual: 'v0.4.1-intl',\n};\n\nexport const HG_MODEL_REPO = 'livekit/turn-detector';\n\nexport const ONNX_FILEPATH = 'onnx/model_q8.onnx';\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKO,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAE1B,MAAM,kBAAgD;AAAA,EAC3D,IAAI;AAAA,EACJ,cAAc;AAChB;AAEO,MAAM,gBAAgB;AAEtB,MAAM,gBAAgB;","names":[]}
@@ -0,0 +1,7 @@
1
+ export type EOUModelType = 'en' | 'multilingual';
2
+ export declare const MAX_HISTORY_TOKENS = 128;
3
+ export declare const MAX_HISTORY_TURNS = 6;
4
+ export declare const MODEL_REVISIONS: Record<EOUModelType, string>;
5
+ export declare const HG_MODEL_REPO = "livekit/turn-detector";
6
+ export declare const ONNX_FILEPATH = "onnx/model_q8.onnx";
7
+ //# sourceMappingURL=constants.d.ts.map
@@ -0,0 +1,7 @@
1
+ export type EOUModelType = 'en' | 'multilingual';
2
+ export declare const MAX_HISTORY_TOKENS = 128;
3
+ export declare const MAX_HISTORY_TURNS = 6;
4
+ export declare const MODEL_REVISIONS: Record<EOUModelType, string>;
5
+ export declare const HG_MODEL_REPO = "livekit/turn-detector";
6
+ export declare const ONNX_FILEPATH = "onnx/model_q8.onnx";
7
+ //# sourceMappingURL=constants.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/turn_detector/constants.ts"],"names":[],"mappings":"AAGA,MAAM,MAAM,YAAY,GAAG,IAAI,GAAG,cAAc,CAAC;AAEjD,eAAO,MAAM,kBAAkB,MAAM,CAAC;AACtC,eAAO,MAAM,iBAAiB,IAAI,CAAC;AAEnC,eAAO,MAAM,eAAe,EAAE,MAAM,CAAC,YAAY,EAAE,MAAM,CAGxD,CAAC;AAEF,eAAO,MAAM,aAAa,0BAA0B,CAAC;AAErD,eAAO,MAAM,aAAa,uBAAuB,CAAC"}