@livekit/agents-plugin-livekit 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,17 @@
1
+ <!--
2
+ SPDX-FileCopyrightText: 2024 LiveKit, Inc.
3
+
4
+ SPDX-License-Identifier: Apache-2.0
5
+ -->
6
+ # Additional utilities for LiveKit Agents
7
+
8
+ The Agents Framework is designed for building realtime, programmable
9
+ participants that run on servers. Use it to create conversational, multi-modal
10
+ voice agents that can see, hear, and understand.
11
+
12
+ This package contains additional utilities provided by LiveKit.
13
+ Refer to the [documentation](https://docs.livekit.io/agents/overview/) for
14
+ information on how to use it, or browse the [API
15
+ reference](https://docs.livekit.io/agents-js/modules/plugins_agents_plugin_livekit.html).
16
+ See the [repository](https://github.com/livekit/agents-js) for more information
17
+ about the framework as a whole.
package/dist/index.cjs ADDED
@@ -0,0 +1,45 @@
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 src_exports = {};
30
+ __export(src_exports, {
31
+ turnDetector: () => turnDetector
32
+ });
33
+ module.exports = __toCommonJS(src_exports);
34
+ var import_agents = require("@livekit/agents");
35
+ var turnDetector = __toESM(require("./turn_detector.cjs"), 1);
36
+ const import_meta = {};
37
+ import_agents.InferenceRunner.registerRunner(
38
+ turnDetector.EOURunner.INFERENCE_METHOD,
39
+ import_meta.resolve("./turn_detector.js")
40
+ );
41
+ // Annotate the CommonJS export names for ESM import in node:
42
+ 0 && (module.exports = {
43
+ turnDetector
44
+ });
45
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { InferenceRunner } from '@livekit/agents';\nimport * as turnDetector from './turn_detector.js';\n\nInferenceRunner.registerRunner(\n turnDetector.EOURunner.INFERENCE_METHOD,\n import.meta.resolve('./turn_detector.js'),\n);\nexport { turnDetector };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,oBAAgC;AAChC,mBAA8B;AAJ9B;AAMA,8BAAgB;AAAA,EACd,aAAa,UAAU;AAAA,EACvB,YAAY,QAAQ,oBAAoB;AAC1C;","names":[]}
@@ -0,0 +1,3 @@
1
+ import * as turnDetector from './turn_detector.js';
2
+ export { turnDetector };
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,YAAY,MAAM,oBAAoB,CAAC;AAMnD,OAAO,EAAE,YAAY,EAAE,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ import { InferenceRunner } from "@livekit/agents";
2
+ import * as turnDetector from "./turn_detector.js";
3
+ InferenceRunner.registerRunner(
4
+ turnDetector.EOURunner.INFERENCE_METHOD,
5
+ import.meta.resolve("./turn_detector.js")
6
+ );
7
+ export {
8
+ turnDetector
9
+ };
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { InferenceRunner } from '@livekit/agents';\nimport * as turnDetector from './turn_detector.js';\n\nInferenceRunner.registerRunner(\n turnDetector.EOURunner.INFERENCE_METHOD,\n import.meta.resolve('./turn_detector.js'),\n);\nexport { turnDetector };\n"],"mappings":"AAGA,SAAS,uBAAuB;AAChC,YAAY,kBAAkB;AAE9B,gBAAgB;AAAA,EACd,aAAa,UAAU;AAAA,EACvB,YAAY,QAAQ,oBAAoB;AAC1C;","names":[]}
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ //# sourceMappingURL=onnxruntime.d.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=onnxruntime.d.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,126 @@
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 turn_detector_exports = {};
20
+ __export(turn_detector_exports, {
21
+ EOUModel: () => EOUModel,
22
+ EOURunner: () => EOURunner,
23
+ default: () => turn_detector_default
24
+ });
25
+ module.exports = __toCommonJS(turn_detector_exports);
26
+ var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
27
+ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
28
+ var import_transformers = require("@huggingface/transformers");
29
+ var import_agents = require("@livekit/agents");
30
+ var import_node_url = require("node:url");
31
+ var import_onnxruntime_node = require("onnxruntime-node");
32
+ const MAX_HISTORY = 4;
33
+ class EOURunner extends import_agents.InferenceRunner {
34
+ static INFERENCE_METHOD = "lk_end_of_utterance";
35
+ #tokenizerPromise;
36
+ #session;
37
+ #tokenizer;
38
+ #logger = (0, import_agents.log)();
39
+ constructor() {
40
+ super();
41
+ this.#tokenizerPromise = import_transformers.AutoTokenizer.from_pretrained("livekit/turn-detector", {
42
+ revision: "v1.2.0"
43
+ // local_files_only: true, // TODO(nbsp): can't find it
44
+ });
45
+ this.#session = import_onnxruntime_node.InferenceSession.create(
46
+ (0, import_node_url.fileURLToPath)(new URL("turn_detector.onnx", importMetaUrl).href),
47
+ {
48
+ executionProviders: [{ name: "cpu" }]
49
+ }
50
+ );
51
+ }
52
+ async initialize() {
53
+ this.#tokenizer = await this.#tokenizerPromise;
54
+ }
55
+ async run(data) {
56
+ const text = this.#formatChatContext(data);
57
+ const startTime = Date.now();
58
+ const inputs = this.#tokenizer.encode(text, { add_special_tokens: false });
59
+ const outputs = await this.#session.then(
60
+ (session) => session.run({ input_ids: new import_onnxruntime_node.Tensor("int64", inputs, [1, inputs.length]) }, ["prob"])
61
+ );
62
+ const endTime = Date.now();
63
+ const logits = outputs.prob;
64
+ const eouProbability = logits.data[0];
65
+ this.#logger.child({ eouProbability, input: text, duration: endTime - startTime }).debug("eou prediction");
66
+ return eouProbability;
67
+ }
68
+ #formatChatContext(ctx) {
69
+ const newCtx = [];
70
+ for (const msg of ctx) {
71
+ if (!msg.content) continue;
72
+ newCtx.push(msg);
73
+ }
74
+ const convoText = this.#tokenizer.apply_chat_template(newCtx, {
75
+ add_generation_prompt: false,
76
+ tokenize: false
77
+ });
78
+ return convoText.slice(0, convoText.lastIndexOf("<|im_end|>"));
79
+ }
80
+ }
81
+ class EOUModel {
82
+ unlikelyThreshold;
83
+ #executor;
84
+ constructor(unlikelyThreshold = 0.15) {
85
+ this.unlikelyThreshold = unlikelyThreshold;
86
+ this.#executor = import_agents.CurrentJobContext.getCurrent().inferenceExecutor;
87
+ }
88
+ supportsLanguage(language) {
89
+ if (!language) return false;
90
+ const parts = language.toLowerCase().split("-");
91
+ return parts[0] === "en" || parts[0] === "english";
92
+ }
93
+ async predictEndOfTurn(chatCtx) {
94
+ let messages = [];
95
+ for (const msg of chatCtx.messages) {
96
+ if (msg.role !== import_agents.llm.ChatRole.ASSISTANT && msg.role !== import_agents.llm.ChatRole.USER) {
97
+ continue;
98
+ }
99
+ if (typeof msg.content === "string") {
100
+ messages.push({
101
+ role: msg.role === import_agents.llm.ChatRole.ASSISTANT ? "assistant" : "user",
102
+ content: msg.content
103
+ });
104
+ } else if (Array.isArray(msg.content)) {
105
+ for (const content of msg.content) {
106
+ if (typeof content === "string") {
107
+ messages.push({
108
+ role: msg.role === import_agents.llm.ChatRole.ASSISTANT ? "assistant" : "user",
109
+ content
110
+ });
111
+ }
112
+ }
113
+ }
114
+ }
115
+ messages = messages.slice(-MAX_HISTORY);
116
+ const result = await this.#executor.doInference(EOURunner.INFERENCE_METHOD, messages);
117
+ return result;
118
+ }
119
+ }
120
+ var turn_detector_default = EOURunner;
121
+ // Annotate the CommonJS export names for ESM import in node:
122
+ 0 && (module.exports = {
123
+ EOUModel,
124
+ EOURunner
125
+ });
126
+ //# sourceMappingURL=turn_detector.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/turn_detector.ts","../../../node_modules/.pnpm/tsup@8.3.5_@microsoft+api-extractor@7.43.7_@types+node@22.5.5__postcss@8.4.38_tsx@4.19.2_typescript@5.4.5/node_modules/tsup/assets/cjs_shims.js"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { PreTrainedTokenizer } from '@huggingface/transformers';\nimport { AutoTokenizer } from '@huggingface/transformers';\nimport type { ipc } from '@livekit/agents';\nimport { CurrentJobContext, InferenceRunner, llm, log } from '@livekit/agents';\nimport { fileURLToPath } from 'node:url';\nimport { InferenceSession, Tensor } from 'onnxruntime-node';\n\nconst MAX_HISTORY = 4;\n\ntype RawChatContext = { role: string; content: string }[];\n\nexport class EOURunner extends InferenceRunner {\n static INFERENCE_METHOD = 'lk_end_of_utterance';\n #tokenizerPromise: Promise<PreTrainedTokenizer>;\n #session: Promise<InferenceSession>;\n #tokenizer?: PreTrainedTokenizer;\n #logger = log();\n\n constructor() {\n super();\n this.#tokenizerPromise = AutoTokenizer.from_pretrained('livekit/turn-detector', {\n revision: 'v1.2.0',\n // local_files_only: true, // TODO(nbsp): can't find it\n });\n this.#session = InferenceSession.create(\n fileURLToPath(new URL('turn_detector.onnx', import.meta.url).href),\n {\n executionProviders: [{ name: 'cpu' }],\n },\n );\n }\n\n async initialize() {\n this.#tokenizer = await this.#tokenizerPromise;\n }\n\n async run(data: RawChatContext): Promise<number | undefined> {\n const text = this.#formatChatContext(data);\n const startTime = Date.now();\n const inputs = this.#tokenizer!.encode(text, { add_special_tokens: false });\n const outputs = await this.#session.then((session) =>\n session.run({ input_ids: new Tensor('int64', inputs, [1, inputs.length]) }, ['prob']),\n );\n const endTime = Date.now();\n const logits = outputs.prob!;\n const eouProbability = logits.data[0] as number;\n this.#logger\n .child({ eouProbability, input: text, duration: endTime - startTime })\n .debug('eou prediction');\n return eouProbability;\n }\n\n #formatChatContext(ctx: RawChatContext): string {\n const newCtx: RawChatContext = [];\n for (const msg of ctx) {\n if (!msg.content) continue;\n newCtx.push(msg);\n }\n\n const convoText = this.#tokenizer!.apply_chat_template(newCtx, {\n add_generation_prompt: false,\n tokenize: false,\n }) as string;\n // remove EOU token from current utterance\n return convoText.slice(0, convoText.lastIndexOf('<|im_end|>'));\n }\n}\n\nexport class EOUModel {\n readonly unlikelyThreshold: number;\n #executor: ipc.InferenceExecutor;\n\n constructor(unlikelyThreshold = 0.15) {\n this.unlikelyThreshold = unlikelyThreshold;\n this.#executor = CurrentJobContext.getCurrent().inferenceExecutor;\n }\n\n supportsLanguage(language?: string) {\n if (!language) return false;\n const parts = language.toLowerCase().split('-');\n return parts[0] === 'en' || parts[0] === 'english';\n }\n\n async predictEndOfTurn(chatCtx: llm.ChatContext): Promise<number> {\n let messages: RawChatContext = [];\n\n for (const msg of chatCtx.messages) {\n if (msg.role !== llm.ChatRole.ASSISTANT && msg.role !== llm.ChatRole.USER) {\n continue;\n }\n\n if (typeof msg.content === 'string') {\n messages.push({\n role: msg.role === llm.ChatRole.ASSISTANT ? 'assistant' : 'user',\n content: msg.content,\n });\n } else if (Array.isArray(msg.content)) {\n for (const content of msg.content) {\n if (typeof content === 'string') {\n messages.push({\n role: msg.role === llm.ChatRole.ASSISTANT ? 'assistant' : 'user',\n content: content,\n });\n }\n }\n }\n }\n messages = messages.slice(-MAX_HISTORY);\n const result = await this.#executor.doInference(EOURunner.INFERENCE_METHOD, messages);\n return result as any;\n }\n}\n\nexport default EOURunner;\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () =>\n typeof document === 'undefined'\n ? new URL(`file:${__filename}`).href\n : (document.currentScript && document.currentScript.src) ||\n new URL('main.js', document.baseURI).href\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n"],"mappings":"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","names":[]}
@@ -0,0 +1,21 @@
1
+ import { InferenceRunner, llm } from '@livekit/agents';
2
+ type RawChatContext = {
3
+ role: string;
4
+ content: string;
5
+ }[];
6
+ export declare class EOURunner extends InferenceRunner {
7
+ #private;
8
+ static INFERENCE_METHOD: string;
9
+ constructor();
10
+ initialize(): Promise<void>;
11
+ run(data: RawChatContext): Promise<number | undefined>;
12
+ }
13
+ export declare class EOUModel {
14
+ #private;
15
+ readonly unlikelyThreshold: number;
16
+ constructor(unlikelyThreshold?: number);
17
+ supportsLanguage(language?: string): boolean;
18
+ predictEndOfTurn(chatCtx: llm.ChatContext): Promise<number>;
19
+ }
20
+ export default EOURunner;
21
+ //# sourceMappingURL=turn_detector.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"turn_detector.d.ts","sourceRoot":"","sources":["../src/turn_detector.ts"],"names":[],"mappings":"AAMA,OAAO,EAAqB,eAAe,EAAE,GAAG,EAAO,MAAM,iBAAiB,CAAC;AAM/E,KAAK,cAAc,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,EAAE,CAAC;AAE1D,qBAAa,SAAU,SAAQ,eAAe;;IAC5C,MAAM,CAAC,gBAAgB,SAAyB;;IAoB1C,UAAU;IAIV,GAAG,CAAC,IAAI,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC;CA8B7D;AAED,qBAAa,QAAQ;;IACnB,QAAQ,CAAC,iBAAiB,EAAE,MAAM,CAAC;gBAGvB,iBAAiB,SAAO;IAKpC,gBAAgB,CAAC,QAAQ,CAAC,EAAE,MAAM;IAM5B,gBAAgB,CAAC,OAAO,EAAE,GAAG,CAAC,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC;CA4BlE;AAED,eAAe,SAAS,CAAC"}
@@ -0,0 +1,99 @@
1
+ import { AutoTokenizer } from "@huggingface/transformers";
2
+ import { CurrentJobContext, InferenceRunner, llm, log } from "@livekit/agents";
3
+ import { fileURLToPath } from "node:url";
4
+ import { InferenceSession, Tensor } from "onnxruntime-node";
5
+ const MAX_HISTORY = 4;
6
+ class EOURunner extends InferenceRunner {
7
+ static INFERENCE_METHOD = "lk_end_of_utterance";
8
+ #tokenizerPromise;
9
+ #session;
10
+ #tokenizer;
11
+ #logger = log();
12
+ constructor() {
13
+ super();
14
+ this.#tokenizerPromise = AutoTokenizer.from_pretrained("livekit/turn-detector", {
15
+ revision: "v1.2.0"
16
+ // local_files_only: true, // TODO(nbsp): can't find it
17
+ });
18
+ this.#session = InferenceSession.create(
19
+ fileURLToPath(new URL("turn_detector.onnx", import.meta.url).href),
20
+ {
21
+ executionProviders: [{ name: "cpu" }]
22
+ }
23
+ );
24
+ }
25
+ async initialize() {
26
+ this.#tokenizer = await this.#tokenizerPromise;
27
+ }
28
+ async run(data) {
29
+ const text = this.#formatChatContext(data);
30
+ const startTime = Date.now();
31
+ const inputs = this.#tokenizer.encode(text, { add_special_tokens: false });
32
+ const outputs = await this.#session.then(
33
+ (session) => session.run({ input_ids: new Tensor("int64", inputs, [1, inputs.length]) }, ["prob"])
34
+ );
35
+ const endTime = Date.now();
36
+ const logits = outputs.prob;
37
+ const eouProbability = logits.data[0];
38
+ this.#logger.child({ eouProbability, input: text, duration: endTime - startTime }).debug("eou prediction");
39
+ return eouProbability;
40
+ }
41
+ #formatChatContext(ctx) {
42
+ const newCtx = [];
43
+ for (const msg of ctx) {
44
+ if (!msg.content) continue;
45
+ newCtx.push(msg);
46
+ }
47
+ const convoText = this.#tokenizer.apply_chat_template(newCtx, {
48
+ add_generation_prompt: false,
49
+ tokenize: false
50
+ });
51
+ return convoText.slice(0, convoText.lastIndexOf("<|im_end|>"));
52
+ }
53
+ }
54
+ class EOUModel {
55
+ unlikelyThreshold;
56
+ #executor;
57
+ constructor(unlikelyThreshold = 0.15) {
58
+ this.unlikelyThreshold = unlikelyThreshold;
59
+ this.#executor = CurrentJobContext.getCurrent().inferenceExecutor;
60
+ }
61
+ supportsLanguage(language) {
62
+ if (!language) return false;
63
+ const parts = language.toLowerCase().split("-");
64
+ return parts[0] === "en" || parts[0] === "english";
65
+ }
66
+ async predictEndOfTurn(chatCtx) {
67
+ let messages = [];
68
+ for (const msg of chatCtx.messages) {
69
+ if (msg.role !== llm.ChatRole.ASSISTANT && msg.role !== llm.ChatRole.USER) {
70
+ continue;
71
+ }
72
+ if (typeof msg.content === "string") {
73
+ messages.push({
74
+ role: msg.role === llm.ChatRole.ASSISTANT ? "assistant" : "user",
75
+ content: msg.content
76
+ });
77
+ } else if (Array.isArray(msg.content)) {
78
+ for (const content of msg.content) {
79
+ if (typeof content === "string") {
80
+ messages.push({
81
+ role: msg.role === llm.ChatRole.ASSISTANT ? "assistant" : "user",
82
+ content
83
+ });
84
+ }
85
+ }
86
+ }
87
+ }
88
+ messages = messages.slice(-MAX_HISTORY);
89
+ const result = await this.#executor.doInference(EOURunner.INFERENCE_METHOD, messages);
90
+ return result;
91
+ }
92
+ }
93
+ var turn_detector_default = EOURunner;
94
+ export {
95
+ EOUModel,
96
+ EOURunner,
97
+ turn_detector_default as default
98
+ };
99
+ //# sourceMappingURL=turn_detector.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/turn_detector.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { PreTrainedTokenizer } from '@huggingface/transformers';\nimport { AutoTokenizer } from '@huggingface/transformers';\nimport type { ipc } from '@livekit/agents';\nimport { CurrentJobContext, InferenceRunner, llm, log } from '@livekit/agents';\nimport { fileURLToPath } from 'node:url';\nimport { InferenceSession, Tensor } from 'onnxruntime-node';\n\nconst MAX_HISTORY = 4;\n\ntype RawChatContext = { role: string; content: string }[];\n\nexport class EOURunner extends InferenceRunner {\n static INFERENCE_METHOD = 'lk_end_of_utterance';\n #tokenizerPromise: Promise<PreTrainedTokenizer>;\n #session: Promise<InferenceSession>;\n #tokenizer?: PreTrainedTokenizer;\n #logger = log();\n\n constructor() {\n super();\n this.#tokenizerPromise = AutoTokenizer.from_pretrained('livekit/turn-detector', {\n revision: 'v1.2.0',\n // local_files_only: true, // TODO(nbsp): can't find it\n });\n this.#session = InferenceSession.create(\n fileURLToPath(new URL('turn_detector.onnx', import.meta.url).href),\n {\n executionProviders: [{ name: 'cpu' }],\n },\n );\n }\n\n async initialize() {\n this.#tokenizer = await this.#tokenizerPromise;\n }\n\n async run(data: RawChatContext): Promise<number | undefined> {\n const text = this.#formatChatContext(data);\n const startTime = Date.now();\n const inputs = this.#tokenizer!.encode(text, { add_special_tokens: false });\n const outputs = await this.#session.then((session) =>\n session.run({ input_ids: new Tensor('int64', inputs, [1, inputs.length]) }, ['prob']),\n );\n const endTime = Date.now();\n const logits = outputs.prob!;\n const eouProbability = logits.data[0] as number;\n this.#logger\n .child({ eouProbability, input: text, duration: endTime - startTime })\n .debug('eou prediction');\n return eouProbability;\n }\n\n #formatChatContext(ctx: RawChatContext): string {\n const newCtx: RawChatContext = [];\n for (const msg of ctx) {\n if (!msg.content) continue;\n newCtx.push(msg);\n }\n\n const convoText = this.#tokenizer!.apply_chat_template(newCtx, {\n add_generation_prompt: false,\n tokenize: false,\n }) as string;\n // remove EOU token from current utterance\n return convoText.slice(0, convoText.lastIndexOf('<|im_end|>'));\n }\n}\n\nexport class EOUModel {\n readonly unlikelyThreshold: number;\n #executor: ipc.InferenceExecutor;\n\n constructor(unlikelyThreshold = 0.15) {\n this.unlikelyThreshold = unlikelyThreshold;\n this.#executor = CurrentJobContext.getCurrent().inferenceExecutor;\n }\n\n supportsLanguage(language?: string) {\n if (!language) return false;\n const parts = language.toLowerCase().split('-');\n return parts[0] === 'en' || parts[0] === 'english';\n }\n\n async predictEndOfTurn(chatCtx: llm.ChatContext): Promise<number> {\n let messages: RawChatContext = [];\n\n for (const msg of chatCtx.messages) {\n if (msg.role !== llm.ChatRole.ASSISTANT && msg.role !== llm.ChatRole.USER) {\n continue;\n }\n\n if (typeof msg.content === 'string') {\n messages.push({\n role: msg.role === llm.ChatRole.ASSISTANT ? 'assistant' : 'user',\n content: msg.content,\n });\n } else if (Array.isArray(msg.content)) {\n for (const content of msg.content) {\n if (typeof content === 'string') {\n messages.push({\n role: msg.role === llm.ChatRole.ASSISTANT ? 'assistant' : 'user',\n content: content,\n });\n }\n }\n }\n }\n messages = messages.slice(-MAX_HISTORY);\n const result = await this.#executor.doInference(EOURunner.INFERENCE_METHOD, messages);\n return result as any;\n }\n}\n\nexport default EOURunner;\n"],"mappings":"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","names":[]}
Binary file
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@livekit/agents-plugin-livekit",
3
+ "version": "0.1.0",
4
+ "description": "Additional utilities for LiveKit Node Agents",
5
+ "main": "dist/index.js",
6
+ "require": "dist/index.cjs",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "require": "./dist/index.cjs"
13
+ }
14
+ },
15
+ "author": "LiveKit",
16
+ "type": "module",
17
+ "repository": "git@github.com:livekit/agents-js.git",
18
+ "license": "Apache-2.0",
19
+ "files": [
20
+ "dist",
21
+ "src",
22
+ "README.md"
23
+ ],
24
+ "devDependencies": {
25
+ "@livekit/agents": "^x",
26
+ "@microsoft/api-extractor": "^7.35.0",
27
+ "onnxruntime-common": "^1.19.2",
28
+ "tsup": "^8.3.5",
29
+ "typescript": "^5.0.0"
30
+ },
31
+ "peerDependencies": {
32
+ "@livekit/agents": "^0.7.0x"
33
+ },
34
+ "dependencies": {
35
+ "@huggingface/transformers": "^3.2.1",
36
+ "onnxruntime-node": "^1.19.2"
37
+ },
38
+ "scripts": {
39
+ "build": "tsup --onSuccess \"tsc --declaration --emitDeclarationOnly\" && cp src/turn_detector.onnx dist/",
40
+ "clean": "rm -rf dist",
41
+ "clean:build": "pnpm clean && pnpm build",
42
+ "lint": "eslint -f unix \"src/**/*.{ts,js}\"",
43
+ "api:check": "api-extractor run --typescript-compiler-folder ../../node_modules/typescript",
44
+ "api:update": "api-extractor run --local --typescript-compiler-folder ../../node_modules/typescript --verbose"
45
+ }
46
+ }
package/src/index.ts ADDED
@@ -0,0 +1,11 @@
1
+ // SPDX-FileCopyrightText: 2024 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import { InferenceRunner } from '@livekit/agents';
5
+ import * as turnDetector from './turn_detector.js';
6
+
7
+ InferenceRunner.registerRunner(
8
+ turnDetector.EOURunner.INFERENCE_METHOD,
9
+ import.meta.resolve('./turn_detector.js'),
10
+ );
11
+ export { turnDetector };
@@ -0,0 +1,8 @@
1
+ // SPDX-FileCopyrightText: 2024 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ // https://github.com/microsoft/onnxruntime/issues/17979
6
+ declare module 'onnxruntime-node' {
7
+ export * from 'onnxruntime-common';
8
+ }
Binary file
@@ -0,0 +1,117 @@
1
+ // SPDX-FileCopyrightText: 2024 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import type { PreTrainedTokenizer } from '@huggingface/transformers';
5
+ import { AutoTokenizer } from '@huggingface/transformers';
6
+ import type { ipc } from '@livekit/agents';
7
+ import { CurrentJobContext, InferenceRunner, llm, log } from '@livekit/agents';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { InferenceSession, Tensor } from 'onnxruntime-node';
10
+
11
+ const MAX_HISTORY = 4;
12
+
13
+ type RawChatContext = { role: string; content: string }[];
14
+
15
+ export class EOURunner extends InferenceRunner {
16
+ static INFERENCE_METHOD = 'lk_end_of_utterance';
17
+ #tokenizerPromise: Promise<PreTrainedTokenizer>;
18
+ #session: Promise<InferenceSession>;
19
+ #tokenizer?: PreTrainedTokenizer;
20
+ #logger = log();
21
+
22
+ constructor() {
23
+ super();
24
+ this.#tokenizerPromise = AutoTokenizer.from_pretrained('livekit/turn-detector', {
25
+ revision: 'v1.2.0',
26
+ // local_files_only: true, // TODO(nbsp): can't find it
27
+ });
28
+ this.#session = InferenceSession.create(
29
+ fileURLToPath(new URL('turn_detector.onnx', import.meta.url).href),
30
+ {
31
+ executionProviders: [{ name: 'cpu' }],
32
+ },
33
+ );
34
+ }
35
+
36
+ async initialize() {
37
+ this.#tokenizer = await this.#tokenizerPromise;
38
+ }
39
+
40
+ async run(data: RawChatContext): Promise<number | undefined> {
41
+ const text = this.#formatChatContext(data);
42
+ const startTime = Date.now();
43
+ const inputs = this.#tokenizer!.encode(text, { add_special_tokens: false });
44
+ const outputs = await this.#session.then((session) =>
45
+ session.run({ input_ids: new Tensor('int64', inputs, [1, inputs.length]) }, ['prob']),
46
+ );
47
+ const endTime = Date.now();
48
+ const logits = outputs.prob!;
49
+ const eouProbability = logits.data[0] as number;
50
+ this.#logger
51
+ .child({ eouProbability, input: text, duration: endTime - startTime })
52
+ .debug('eou prediction');
53
+ return eouProbability;
54
+ }
55
+
56
+ #formatChatContext(ctx: RawChatContext): string {
57
+ const newCtx: RawChatContext = [];
58
+ for (const msg of ctx) {
59
+ if (!msg.content) continue;
60
+ newCtx.push(msg);
61
+ }
62
+
63
+ const convoText = this.#tokenizer!.apply_chat_template(newCtx, {
64
+ add_generation_prompt: false,
65
+ tokenize: false,
66
+ }) as string;
67
+ // remove EOU token from current utterance
68
+ return convoText.slice(0, convoText.lastIndexOf('<|im_end|>'));
69
+ }
70
+ }
71
+
72
+ export class EOUModel {
73
+ readonly unlikelyThreshold: number;
74
+ #executor: ipc.InferenceExecutor;
75
+
76
+ constructor(unlikelyThreshold = 0.15) {
77
+ this.unlikelyThreshold = unlikelyThreshold;
78
+ this.#executor = CurrentJobContext.getCurrent().inferenceExecutor;
79
+ }
80
+
81
+ supportsLanguage(language?: string) {
82
+ if (!language) return false;
83
+ const parts = language.toLowerCase().split('-');
84
+ return parts[0] === 'en' || parts[0] === 'english';
85
+ }
86
+
87
+ async predictEndOfTurn(chatCtx: llm.ChatContext): Promise<number> {
88
+ let messages: RawChatContext = [];
89
+
90
+ for (const msg of chatCtx.messages) {
91
+ if (msg.role !== llm.ChatRole.ASSISTANT && msg.role !== llm.ChatRole.USER) {
92
+ continue;
93
+ }
94
+
95
+ if (typeof msg.content === 'string') {
96
+ messages.push({
97
+ role: msg.role === llm.ChatRole.ASSISTANT ? 'assistant' : 'user',
98
+ content: msg.content,
99
+ });
100
+ } else if (Array.isArray(msg.content)) {
101
+ for (const content of msg.content) {
102
+ if (typeof content === 'string') {
103
+ messages.push({
104
+ role: msg.role === llm.ChatRole.ASSISTANT ? 'assistant' : 'user',
105
+ content: content,
106
+ });
107
+ }
108
+ }
109
+ }
110
+ }
111
+ messages = messages.slice(-MAX_HISTORY);
112
+ const result = await this.#executor.doInference(EOURunner.INFERENCE_METHOD, messages);
113
+ return result as any;
114
+ }
115
+ }
116
+
117
+ export default EOURunner;