@fonoster/autopilot 0.8.40 → 0.8.42

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/README.md CHANGED
@@ -35,7 +35,7 @@ The configuration file has two major sections: `conversationSettings` and `langu
35
35
  {
36
36
  "conversationSettings": {
37
37
  "firstMessage": "Hello, this is Olivia from Dr. Green's Family Medicine. How can I assist you today?",
38
- "systemTemplate": "You are a Customer Service Representative. You are here to help the caller with their needs.",
38
+ "systemPrompt": "You are a Customer Service Representative. You are here to help the caller with their needs.",
39
39
  "systemErrorMessage": "I'm sorry, but I seem to be having trouble. Please try again later.",
40
40
  "initialDtmf": "6589",
41
41
  "transferOptions": {
@@ -34,7 +34,7 @@ function createLanguageModel(params) {
34
34
  maxTokens: languageModelSettings.maxTokens,
35
35
  temperature: languageModelSettings.temperature,
36
36
  firstMessage: conversationSettings.firstMessage,
37
- systemTemplate: conversationSettings.systemTemplate,
37
+ systemPrompt: conversationSettings.systemPrompt,
38
38
  baseUrl: languageModelSettings.baseUrl,
39
39
  knowledgeBase,
40
40
  tools
package/dist/envs.d.ts CHANGED
@@ -7,7 +7,7 @@ export declare const KNOWLEDGE_BASE_ENABLED: boolean;
7
7
  export declare const NODE_ENV: string;
8
8
  export declare const UNSTRUCTURED_API_KEY: string | undefined;
9
9
  export declare const UNSTRUCTURED_API_URL: string;
10
- export declare const SILERO_VAD_MODEL_PATH: string;
10
+ export declare const SILERO_VAD_VERSION: string;
11
11
  export declare const CONVERSATION_PROVIDER: string;
12
12
  export declare const CONVERSATION_PROVIDER_FILE: string;
13
13
  export declare const APISERVER_ENDPOINT: string;
package/dist/envs.js CHANGED
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.INTEGRATIONS_FILE = exports.APISERVER_ENDPOINT = exports.CONVERSATION_PROVIDER_FILE = exports.CONVERSATION_PROVIDER = exports.SILERO_VAD_MODEL_PATH = exports.UNSTRUCTURED_API_URL = exports.UNSTRUCTURED_API_KEY = exports.NODE_ENV = exports.KNOWLEDGE_BASE_ENABLED = exports.AWS_S3_SECRET_ACCESS_KEY = exports.AWS_S3_REGION = exports.AWS_S3_ENDPOINT = exports.AWS_S3_ACCESS_KEY_ID = exports.SKIP_IDENTITY = void 0;
6
+ exports.INTEGRATIONS_FILE = exports.APISERVER_ENDPOINT = exports.CONVERSATION_PROVIDER_FILE = exports.CONVERSATION_PROVIDER = exports.SILERO_VAD_VERSION = exports.UNSTRUCTURED_API_URL = exports.UNSTRUCTURED_API_KEY = exports.NODE_ENV = exports.KNOWLEDGE_BASE_ENABLED = exports.AWS_S3_SECRET_ACCESS_KEY = exports.AWS_S3_REGION = exports.AWS_S3_ENDPOINT = exports.AWS_S3_ACCESS_KEY_ID = exports.SKIP_IDENTITY = void 0;
7
7
  /*
8
8
  * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
9
9
  * http://github.com/fonoster/fonoster
@@ -39,7 +39,7 @@ exports.KNOWLEDGE_BASE_ENABLED = e.KNOWLEDGE_BASE_ENABLED === "true";
39
39
  exports.NODE_ENV = e.NODE_ENV || "production";
40
40
  exports.UNSTRUCTURED_API_KEY = e.UNSTRUCTURED_API_KEY;
41
41
  exports.UNSTRUCTURED_API_URL = e.UNSTRUCTURED_API_URL ?? "https://api.unstructuredapp.io/general/v0/general";
42
- exports.SILERO_VAD_MODEL_PATH = e.SILERO_VAD_MODEL_PATH ?? (0, path_1.join)(__dirname, "..", "silero_vad.onnx");
42
+ exports.SILERO_VAD_VERSION = e.SILERO_VAD_VERSION ?? "v4";
43
43
  exports.CONVERSATION_PROVIDER = e.CONVERSATION_PROVIDER
44
44
  ? e.CONVERSATION_PROVIDER
45
45
  : types_1.ConversationProvider.FILE;
@@ -52,6 +52,10 @@ exports.APISERVER_ENDPOINT = e.APISERVER_ENDPOINT
52
52
  exports.INTEGRATIONS_FILE = e.INTEGRATIONS_FILE
53
53
  ? e.INTEGRATIONS_FILE
54
54
  : `${process.cwd()}/config/integrations.json`;
55
+ if (exports.SILERO_VAD_VERSION !== "v4" && exports.SILERO_VAD_VERSION !== "v5") {
56
+ console.error("SILERO_VAD_VERSION must be set to 'v4' or 'v5'");
57
+ process.exit(1);
58
+ }
55
59
  if (exports.CONVERSATION_PROVIDER.toLocaleLowerCase() !== types_1.ConversationProvider.API &&
56
60
  exports.CONVERSATION_PROVIDER.toLocaleLowerCase() !== types_1.ConversationProvider.FILE) {
57
61
  console.error("CONVERSATION_PROVIDER must be set to 'api' or 'file'");
@@ -9,8 +9,6 @@ declare const machine: import("xstate").StateMachine<AutopilotContext, {
9
9
  } | {
10
10
  type: "SPEECH_RESULT";
11
11
  speech: string;
12
- } | {
13
- type: "USER_REQUEST_PROCESSED";
14
12
  }, {
15
13
  [x: string]: import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<void, {
16
14
  context: AutopilotContext;
@@ -81,8 +79,6 @@ declare const machine: import("xstate").StateMachine<AutopilotContext, {
81
79
  } | {
82
80
  type: "SPEECH_RESULT";
83
81
  speech: string;
84
- } | {
85
- type: "USER_REQUEST_PROCESSED";
86
82
  }, {
87
83
  src: "doProcessUserRequest";
88
84
  logic: import("xstate").PromiseActorLogic<void, {
@@ -126,7 +126,7 @@ const machine = (0, xstate_1.setup)({
126
126
  return context.idleTimeoutCount + 1 > context.maxIdleTimeoutCount;
127
127
  },
128
128
  hasSpeechResult: function ({ context }) {
129
- return context.speechBuffer !== "";
129
+ return context.speechBuffer;
130
130
  },
131
131
  isSpeaking: function ({ context }) {
132
132
  logger.verbose("called isSpeaking guard", {
@@ -236,14 +236,11 @@ const machine = (0, xstate_1.setup)({
236
236
  }
237
237
  },
238
238
  idle: {
239
+ entry: { type: "cleanSpeech" },
239
240
  on: {
240
241
  SPEECH_START: {
241
242
  target: "waitingForUserRequest",
242
243
  description: "Event from VAD system."
243
- },
244
- SPEECH_RESULT: {
245
- target: "waitingForUserRequest",
246
- description: "Event from Speech to Text provider."
247
244
  }
248
245
  },
249
246
  after: {
@@ -274,18 +271,9 @@ const machine = (0, xstate_1.setup)({
274
271
  target: "updatingSpeech"
275
272
  },
276
273
  entry: [
277
- {
278
- type: "cleanSpeech"
279
- },
280
- {
281
- type: "interruptPlayback"
282
- },
283
- {
284
- type: "resetIdleTimeoutCount"
285
- },
286
- {
287
- type: "setSpeaking"
288
- }
274
+ { type: "interruptPlayback" },
275
+ { type: "resetIdleTimeoutCount" },
276
+ { type: "setSpeaking" }
289
277
  ]
290
278
  },
291
279
  hangup: {
@@ -293,45 +281,76 @@ const machine = (0, xstate_1.setup)({
293
281
  },
294
282
  updatingSpeech: {
295
283
  on: {
296
- SPEECH_END: {
297
- actions: [
298
- {
299
- type: "setSpeakingDone"
300
- }
301
- ]
302
- },
284
+ SPEECH_END: [
285
+ {
286
+ target: "processingUserRequest",
287
+ guard: "hasSpeechResult",
288
+ actions: [{ type: "setSpeakingDone" }],
289
+ description: "Process immediately if we have speech"
290
+ },
291
+ {
292
+ target: "waitingForSpeechTimeout",
293
+ guard: (0, xstate_1.not)("hasSpeechResult"),
294
+ actions: [{ type: "setSpeakingDone" }],
295
+ description: "Wait for more speech if no results yet"
296
+ }
297
+ ],
303
298
  SPEECH_RESULT: [
299
+ {
300
+ actions: { type: "appendSpeech" },
301
+ guard: "isSpeaking",
302
+ description: "Just append the speech result."
303
+ },
304
304
  {
305
305
  target: "processingUserRequest",
306
- actions: {
307
- type: "appendSpeech"
308
- },
306
+ actions: { type: "appendSpeech" },
309
307
  guard: (0, xstate_1.not)("isSpeaking"),
310
- description: "Speech result from the Speech to Text provider."
308
+ description: "Append the speech result and process it."
311
309
  }
312
310
  ]
313
- },
311
+ }
312
+ },
313
+ waitingForSpeechTimeout: {
314
314
  after: {
315
315
  MAX_SPEECH_WAIT_TIMEOUT: [
316
316
  {
317
317
  target: "processingUserRequest",
318
- guard: (0, xstate_1.and)([(0, xstate_1.not)("isSpeaking"), "hasSpeechResult"])
318
+ guard: "hasSpeechResult"
319
319
  },
320
320
  {
321
- target: "idle",
322
- guard: (0, xstate_1.not)("isSpeaking"),
323
- actions: {
324
- type: "announceIdleTimeout"
325
- }
321
+ target: "idle"
326
322
  }
327
323
  ]
324
+ },
325
+ on: {
326
+ SPEECH_START: {
327
+ target: "waitingForUserRequest",
328
+ description: "User started speaking again"
329
+ },
330
+ SPEECH_RESULT: {
331
+ target: "processingUserRequest",
332
+ actions: {
333
+ type: "appendSpeech"
334
+ },
335
+ description: "Append final speech and process the request"
336
+ }
328
337
  }
329
338
  },
330
339
  processingUserRequest: {
331
340
  on: {
332
341
  SPEECH_START: {
333
342
  target: "waitingForUserRequest",
334
- description: "Event from VAD or similar system."
343
+ description: "Event from VAD or similar system.",
344
+ actions: [{ type: "interruptPlayback" }, { type: "cleanSpeech" }]
345
+ },
346
+ SPEECH_RESULT: {
347
+ target: "waitingForUserRequest",
348
+ description: "User interrupted with new speech",
349
+ actions: [
350
+ { type: "interruptPlayback" },
351
+ { type: "cleanSpeech" },
352
+ { type: "appendSpeech" }
353
+ ]
335
354
  }
336
355
  },
337
356
  invoke: {
@@ -28,13 +28,13 @@ const tools_1 = require("../tools");
28
28
  const logger = (0, logger_1.getLogger)({ service: "autopilot", filePath: __filename });
29
29
  class AbstractLanguageModel {
30
30
  constructor(params, voice, telephonyContext) {
31
- const { model, firstMessage, systemTemplate, knowledgeBase, tools } = params;
31
+ const { model, firstMessage, systemPrompt, knowledgeBase, tools } = params;
32
32
  this.chatHistory = (0, chatHistory_1.createChatHistory)();
33
33
  this.toolsCatalog = new tools_1.ToolsCatalog(tools);
34
34
  this.voice = voice;
35
35
  const promptTemplate = (0, createPromptTemplate_1.createPromptTemplate)({
36
36
  firstMessage,
37
- systemTemplate,
37
+ systemPrompt,
38
38
  telephonyContext
39
39
  });
40
40
  this.chain = (0, createChain_1.createChain)(model, knowledgeBase, promptTemplate, this.chatHistory);
@@ -2,6 +2,6 @@ import { ChatPromptTemplate } from "@langchain/core/prompts";
2
2
  import { TelephonyContext } from "./types";
3
3
  export declare function createPromptTemplate(params: {
4
4
  firstMessage?: string;
5
- systemTemplate: string;
5
+ systemPrompt: string;
6
6
  telephonyContext: TelephonyContext;
7
7
  }): ChatPromptTemplate<any, any>;
@@ -21,11 +21,11 @@ exports.createPromptTemplate = createPromptTemplate;
21
21
  */
22
22
  const prompts_1 = require("@langchain/core/prompts");
23
23
  function createPromptTemplate(params) {
24
- const { firstMessage, systemTemplate, telephonyContext } = params;
24
+ const { firstMessage, systemPrompt, telephonyContext } = params;
25
25
  return prompts_1.ChatPromptTemplate.fromMessages([
26
26
  new prompts_1.MessagesPlaceholder("history"),
27
27
  prompts_1.SystemMessagePromptTemplate.fromTemplate(`firstMessage: ${firstMessage}`),
28
- prompts_1.SystemMessagePromptTemplate.fromTemplate(systemTemplate),
28
+ prompts_1.SystemMessagePromptTemplate.fromTemplate(systemPrompt),
29
29
  prompts_1.SystemMessagePromptTemplate.fromTemplate("{context}"),
30
30
  prompts_1.SystemMessagePromptTemplate.fromTemplate(`callReceivedAt:${new Date().toISOString()}
31
31
  ingressNumber:${telephonyContext.ingressNumber}
@@ -7,7 +7,7 @@ type LanguageModel = {
7
7
  };
8
8
  type BaseModelParams = {
9
9
  firstMessage?: string;
10
- systemTemplate: string;
10
+ systemPrompt: string;
11
11
  knowledgeBase: KnowledgeBase;
12
12
  tools: Tool[];
13
13
  telephonyContext: TelephonyContext;
@@ -1,14 +1,14 @@
1
1
  import { Vad } from "./types";
2
2
  declare class SileroVad implements Vad {
3
3
  private vad;
4
- private readonly params;
4
+ private params;
5
5
  constructor(params: {
6
- pathToModel: string;
6
+ pathToModel?: string;
7
7
  activationThreshold: number;
8
8
  deactivationThreshold: number;
9
9
  debounceFrames: number;
10
10
  });
11
- pathToModel: string;
11
+ pathToModel?: string;
12
12
  activationThreshold: number;
13
13
  deactivationThreshold: number;
14
14
  debounceFrames: number;
@@ -21,15 +21,15 @@ exports.SileroVad = void 0;
21
21
  * limitations under the License.
22
22
  */
23
23
  const logger_1 = require("@fonoster/logger");
24
- const createVad_1 = require("./createVad");
24
+ const makeVad_1 = require("./makeVad");
25
25
  const logger = (0, logger_1.getLogger)({ service: "autopilot", filePath: __filename });
26
26
  class SileroVad {
27
27
  constructor(params) {
28
- logger.verbose("starting instance of silero vad", { ...params });
28
+ logger.verbose("starting instance of silero vad v4", { ...params });
29
29
  this.params = params;
30
30
  }
31
31
  async init() {
32
- this.vad = await (0, createVad_1.createVad)(this.params);
32
+ this.vad = await (0, makeVad_1.makeVad)(this.params);
33
33
  }
34
34
  processChunk(data, callback) {
35
35
  if (!this.vad) {
@@ -1,14 +1,15 @@
1
1
  import { ONNXRuntimeAPI, SpeechProbabilities } from "./types";
2
2
  declare class SileroVadModel {
3
- private readonly ort;
4
- private readonly pathToModel;
5
- private _session;
6
- private _state;
7
- private _sr;
3
+ private ort;
4
+ private pathToModel;
5
+ _session: any;
6
+ _h: unknown;
7
+ _c: unknown;
8
+ _sr: unknown;
8
9
  constructor(ort: ONNXRuntimeAPI, pathToModel: string);
9
- static readonly new: (ort: ONNXRuntimeAPI, pathToModel: string) => Promise<SileroVadModel>;
10
+ static new: (ort: ONNXRuntimeAPI, pathToModel: string) => Promise<SileroVadModel>;
10
11
  init(): Promise<void>;
11
- resetState: () => void;
12
12
  process(audioFrame: Float32Array): Promise<SpeechProbabilities>;
13
+ resetState(): void;
13
14
  }
14
15
  export { SileroVadModel };
@@ -21,24 +21,16 @@ exports.SileroVadModel = void 0;
21
21
  * limitations under the License.
22
22
  */
23
23
  const fs_1 = require("fs");
24
- function getNewState(ortInstance) {
25
- const zeroes = Array(2 * 128).fill(0);
26
- return new ortInstance.Tensor("float32", zeroes, [2, 1, 128]);
27
- }
28
24
  class SileroVadModel {
29
25
  constructor(ort, pathToModel) {
30
26
  this.ort = ort;
31
27
  this.pathToModel = pathToModel;
32
- this.resetState = () => {
33
- this._state = getNewState(this.ort);
34
- };
35
28
  }
36
29
  async init() {
37
30
  const modelArrayBuffer = (0, fs_1.readFileSync)(this.pathToModel).buffer;
38
- const sessionOption = { interOpNumThreads: 1, intraOpNumThreads: 1 };
39
- this._session = await this.ort.InferenceSession.create(modelArrayBuffer, sessionOption);
31
+ this._session = await this.ort.InferenceSession.create(modelArrayBuffer);
40
32
  this._sr = new this.ort.Tensor("int64", [16000n]);
41
- this._state = getNewState(this.ort);
33
+ this.resetState();
42
34
  }
43
35
  async process(audioFrame) {
44
36
  const t = new this.ort.Tensor("float32", audioFrame, [
@@ -47,15 +39,22 @@ class SileroVadModel {
47
39
  ]);
48
40
  const inputs = {
49
41
  input: t,
50
- state: this._state,
42
+ h: this._h,
43
+ c: this._c,
51
44
  sr: this._sr
52
45
  };
53
46
  const out = await this._session.run(inputs);
54
- this._state = out["stateN"];
55
- const [isSpeech] = out["output"].data;
47
+ this._h = out.hn;
48
+ this._c = out.cn;
49
+ const [isSpeech] = out.output.data;
56
50
  const notSpeech = 1 - isSpeech;
57
51
  return { notSpeech, isSpeech };
58
52
  }
53
+ resetState() {
54
+ const zeroes = Array(2 * 64).fill(0);
55
+ this._h = new this.ort.Tensor("float32", zeroes, [2, 1, 64]);
56
+ this._c = new this.ort.Tensor("float32", zeroes, [2, 1, 64]);
57
+ }
59
58
  }
60
59
  exports.SileroVadModel = SileroVadModel;
61
60
  _a = SileroVadModel;
@@ -24,12 +24,14 @@ exports.chunkToFloat32Array = chunkToFloat32Array;
24
24
  //
25
25
  // Q. Would it be the same if we just created a new Uint8Array from the chunk?
26
26
  function chunkToFloat32Array(chunk) {
27
- let int16Array;
27
+ // Check if byteOffset is not aligned
28
28
  const alignedByteOffset = chunk.byteOffset % Int16Array.BYTES_PER_ELEMENT === 0;
29
+ let int16Array;
29
30
  if (alignedByteOffset) {
30
31
  int16Array = new Int16Array(chunk.buffer, chunk.byteOffset, chunk.byteLength / Int16Array.BYTES_PER_ELEMENT);
31
32
  }
32
33
  else {
34
+ // Create a new aligned Uint8Array and then an Int16Array from it
33
35
  const alignedChunk = new Uint8Array(chunk);
34
36
  int16Array = new Int16Array(alignedChunk.buffer, alignedChunk.byteOffset, alignedChunk.byteLength / Int16Array.BYTES_PER_ELEMENT);
35
37
  }
@@ -0,0 +1,7 @@
1
+ declare function makeVad(params: {
2
+ pathToModel?: string;
3
+ activationThreshold: number;
4
+ deactivationThreshold: number;
5
+ debounceFrames: number;
6
+ }): Promise<(chunk: Uint8Array, callback: (event: "SPEECH_START" | "SPEECH_END") => void) => Promise<void>>;
7
+ export { makeVad };
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.makeVad = makeVad;
37
+ /* eslint-disable no-loops/no-loops */
38
+ /*
39
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
40
+ * http://github.com/fonoster/fonoster
41
+ *
42
+ * This file is part of Fonoster
43
+ *
44
+ * Licensed under the MIT License (the "License");
45
+ * you may not use this file except in compliance with
46
+ * the License. You may obtain a copy of the License at
47
+ *
48
+ * https://opensource.org/licenses/MIT
49
+ *
50
+ * Unless required by applicable law or agreed to in writing, software
51
+ * distributed under the License is distributed on an "AS IS" BASIS,
52
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
53
+ * See the License for the specific language governing permissions and
54
+ * limitations under the License.
55
+ */
56
+ const path_1 = require("path");
57
+ const logger_1 = require("@fonoster/logger");
58
+ const ort = __importStar(require("onnxruntime-node"));
59
+ const chunkToFloat32Array_1 = require("./chunkToFloat32Array");
60
+ const SileroVadModel_1 = require("./SileroVadModel");
61
+ const logger = (0, logger_1.getLogger)({ service: "autopilot", filePath: __filename });
62
+ const BUFFER_SIZE = 16000;
63
+ async function makeVad(params) {
64
+ const { pathToModel, activationThreshold, deactivationThreshold, debounceFrames } = params;
65
+ const effectivePath = pathToModel || (0, path_1.join)(__dirname, "..", "..", "silero_vad.onnx");
66
+ const silero = await SileroVadModel_1.SileroVadModel.new(ort, effectivePath);
67
+ let audioBuffer = [];
68
+ let isSpeechActive = false;
69
+ let consecutiveSpeechFrames = 0;
70
+ let consecutiveNonSpeechFrames = 0;
71
+ return async function process(chunk, callback) {
72
+ const float32Array = (0, chunkToFloat32Array_1.chunkToFloat32Array)(chunk);
73
+ audioBuffer.push(...float32Array);
74
+ const processBuffer = async (buffer) => {
75
+ if (buffer.length < BUFFER_SIZE)
76
+ return buffer;
77
+ const audioFrame = buffer.slice(0, BUFFER_SIZE);
78
+ const remainingBuffer = buffer.slice(BUFFER_SIZE);
79
+ const result = await silero.process(new Float32Array(audioFrame));
80
+ logger.silly("last vad result", { ...result });
81
+ if (result.isSpeech > activationThreshold) {
82
+ consecutiveNonSpeechFrames = 0; // Reset non-speech counter
83
+ consecutiveSpeechFrames++;
84
+ if (consecutiveSpeechFrames >= debounceFrames && !isSpeechActive) {
85
+ isSpeechActive = true;
86
+ callback("SPEECH_START");
87
+ }
88
+ }
89
+ else {
90
+ consecutiveSpeechFrames = 0; // Reset speech counter
91
+ consecutiveNonSpeechFrames++;
92
+ if (consecutiveNonSpeechFrames >= debounceFrames &&
93
+ isSpeechActive &&
94
+ result.isSpeech < deactivationThreshold) {
95
+ isSpeechActive = false;
96
+ callback("SPEECH_END");
97
+ silero.resetState(); // Reset VAD state after speech ends
98
+ }
99
+ }
100
+ return processBuffer(remainingBuffer);
101
+ };
102
+ audioBuffer = await processBuffer(audioBuffer);
103
+ };
104
+ }
@@ -8,15 +8,12 @@ type SpeechProbabilities = {
8
8
  };
9
9
  type ONNXRuntimeAPI = {
10
10
  InferenceSession: {
11
- create(modelArrayBuffer: ArrayBuffer, sessionOption: {
12
- interOpNumThreads: number;
13
- intraOpNumThreads: number;
14
- }): Promise<unknown>;
11
+ create(modelArrayBuffer: ArrayBuffer): Promise<unknown>;
15
12
  };
16
13
  Tensor: {
17
- new (type: "int64", data: BigInt[]): unknown;
18
- new (type: "int64", data: BigInt[], dims: [1]): unknown;
19
- new (type: "float32", data: Float32Array | number[], dims: [2, 1, 128]): unknown;
14
+ new (type: "int64", dims: [16000n]): unknown;
15
+ new (type: "float32", data: number[], dims: [2, 1, 64]): unknown;
16
+ new (type: "float32", data: Float32Array, dims: [1, number]): unknown;
20
17
  new (type: "float32", data: Float32Array, dims: [1, number]): unknown;
21
18
  };
22
19
  };
package/dist/vadWorker.js CHANGED
@@ -20,11 +20,18 @@ Object.defineProperty(exports, "__esModule", { value: true });
20
20
  */
21
21
  const worker_threads_1 = require("worker_threads");
22
22
  const SileroVad_1 = require("./vad/SileroVad");
23
+ const SileroVad_2 = require("./vadv5/SileroVad");
23
24
  const envs_1 = require("./envs");
24
- const vad = new SileroVad_1.SileroVad({
25
- ...worker_threads_1.workerData,
26
- pathToModel: envs_1.SILERO_VAD_MODEL_PATH
27
- });
25
+ const path_1 = require("path");
26
+ const vad = envs_1.SILERO_VAD_VERSION === "v4"
27
+ ? new SileroVad_1.SileroVad({
28
+ ...worker_threads_1.workerData,
29
+ pathToModel: (0, path_1.join)(__dirname, "..", "silero_vad.onnx")
30
+ })
31
+ : new SileroVad_2.SileroVad({
32
+ ...worker_threads_1.workerData,
33
+ pathToModel: (0, path_1.join)(__dirname, "..", "silero_vad_v5.onnx")
34
+ });
28
35
  vad.init().then(() => {
29
36
  worker_threads_1.parentPort?.on("message", (chunk) => {
30
37
  vad.processChunk(chunk, (voiceActivity) => {
@@ -0,0 +1,18 @@
1
+ import { Vad } from "./types";
2
+ declare class SileroVad implements Vad {
3
+ private vad;
4
+ private readonly params;
5
+ constructor(params: {
6
+ pathToModel: string;
7
+ activationThreshold: number;
8
+ deactivationThreshold: number;
9
+ debounceFrames: number;
10
+ });
11
+ pathToModel: string;
12
+ activationThreshold: number;
13
+ deactivationThreshold: number;
14
+ debounceFrames: number;
15
+ init(): Promise<void>;
16
+ processChunk(data: Uint8Array, callback: (event: "SPEECH_START" | "SPEECH_END") => void): void;
17
+ }
18
+ export { SileroVad };
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SileroVad = void 0;
4
+ /* eslint-disable no-loops/no-loops */
5
+ /*
6
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
7
+ * http://github.com/fonoster/fonoster
8
+ *
9
+ * This file is part of Fonoster
10
+ *
11
+ * Licensed under the MIT License (the "License");
12
+ * you may not use this file except in compliance with
13
+ * the License. You may obtain a copy of the License at
14
+ *
15
+ * https://opensource.org/licenses/MIT
16
+ *
17
+ * Unless required by applicable law or agreed to in writing, software
18
+ * distributed under the License is distributed on an "AS IS" BASIS,
19
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ * See the License for the specific language governing permissions and
21
+ * limitations under the License.
22
+ */
23
+ const logger_1 = require("@fonoster/logger");
24
+ const createVad_1 = require("./createVad");
25
+ const logger = (0, logger_1.getLogger)({ service: "autopilot", filePath: __filename });
26
+ class SileroVad {
27
+ constructor(params) {
28
+ logger.verbose("starting instance of silero vad v5", { ...params });
29
+ this.params = params;
30
+ }
31
+ async init() {
32
+ this.vad = await (0, createVad_1.createVad)(this.params);
33
+ }
34
+ processChunk(data, callback) {
35
+ if (!this.vad) {
36
+ throw new Error("VAD not initialized)");
37
+ }
38
+ this.vad(data, callback);
39
+ }
40
+ }
41
+ exports.SileroVad = SileroVad;
@@ -0,0 +1,14 @@
1
+ import { ONNXRuntimeAPI, SpeechProbabilities } from "./types";
2
+ declare class SileroVadModel {
3
+ private readonly ort;
4
+ private readonly pathToModel;
5
+ private _session;
6
+ private _state;
7
+ private _sr;
8
+ constructor(ort: ONNXRuntimeAPI, pathToModel: string);
9
+ static readonly new: (ort: ONNXRuntimeAPI, pathToModel: string) => Promise<SileroVadModel>;
10
+ init(): Promise<void>;
11
+ resetState: () => void;
12
+ process(audioFrame: Float32Array): Promise<SpeechProbabilities>;
13
+ }
14
+ export { SileroVadModel };
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ var _a;
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.SileroVadModel = void 0;
5
+ /*
6
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
7
+ * http://github.com/fonoster/fonoster
8
+ *
9
+ * This file is part of Fonoster
10
+ *
11
+ * Licensed under the MIT License (the "License");
12
+ * you may not use this file except in compliance with
13
+ * the License. You may obtain a copy of the License at
14
+ *
15
+ * https://opensource.org/licenses/MIT
16
+ *
17
+ * Unless required by applicable law or agreed to in writing, software
18
+ * distributed under the License is distributed on an "AS IS" BASIS,
19
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ * See the License for the specific language governing permissions and
21
+ * limitations under the License.
22
+ */
23
+ const fs_1 = require("fs");
24
+ function getNewState(ortInstance) {
25
+ const zeroes = Array(2 * 128).fill(0);
26
+ return new ortInstance.Tensor("float32", zeroes, [2, 1, 128]);
27
+ }
28
+ class SileroVadModel {
29
+ constructor(ort, pathToModel) {
30
+ this.ort = ort;
31
+ this.pathToModel = pathToModel;
32
+ this.resetState = () => {
33
+ this._state = getNewState(this.ort);
34
+ };
35
+ }
36
+ async init() {
37
+ const modelArrayBuffer = (0, fs_1.readFileSync)(this.pathToModel).buffer;
38
+ const sessionOption = { interOpNumThreads: 1, intraOpNumThreads: 1 };
39
+ this._session = await this.ort.InferenceSession.create(modelArrayBuffer, sessionOption);
40
+ this._sr = new this.ort.Tensor("int64", [16000n]);
41
+ this._state = getNewState(this.ort);
42
+ }
43
+ async process(audioFrame) {
44
+ const t = new this.ort.Tensor("float32", audioFrame, [
45
+ 1,
46
+ audioFrame.length
47
+ ]);
48
+ const inputs = {
49
+ input: t,
50
+ state: this._state,
51
+ sr: this._sr
52
+ };
53
+ const out = await this._session.run(inputs);
54
+ this._state = out["stateN"];
55
+ const [isSpeech] = out["output"].data;
56
+ const notSpeech = 1 - isSpeech;
57
+ return { notSpeech, isSpeech };
58
+ }
59
+ }
60
+ exports.SileroVadModel = SileroVadModel;
61
+ _a = SileroVadModel;
62
+ SileroVadModel.new = async (ort, pathToModel) => {
63
+ const model = new _a(ort, pathToModel);
64
+ await model.init();
65
+ return model;
66
+ };
@@ -0,0 +1,2 @@
1
+ declare function chunkToFloat32Array(chunk: Uint8Array): Float32Array;
2
+ export { chunkToFloat32Array };
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
4
+ * http://github.com/fonoster/fonoster
5
+ *
6
+ * This file is part of Fonoster
7
+ *
8
+ * Licensed under the MIT License (the "License");
9
+ * you may not use this file except in compliance with
10
+ * the License. You may obtain a copy of the License at
11
+ *
12
+ * https://opensource.org/licenses/MIT
13
+ *
14
+ * Unless required by applicable law or agreed to in writing, software
15
+ * distributed under the License is distributed on an "AS IS" BASIS,
16
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ * See the License for the specific language governing permissions and
18
+ * limitations under the License.
19
+ */
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.chunkToFloat32Array = chunkToFloat32Array;
22
+ // This version of the chunkToFloat32Array accounts for the case where
23
+ // the byteOffset is misaligned.
24
+ //
25
+ // Q. Would it be the same if we just created a new Uint8Array from the chunk?
26
+ function chunkToFloat32Array(chunk) {
27
+ let int16Array;
28
+ const alignedByteOffset = chunk.byteOffset % Int16Array.BYTES_PER_ELEMENT === 0;
29
+ if (alignedByteOffset) {
30
+ int16Array = new Int16Array(chunk.buffer, chunk.byteOffset, chunk.byteLength / Int16Array.BYTES_PER_ELEMENT);
31
+ }
32
+ else {
33
+ const alignedChunk = new Uint8Array(chunk);
34
+ int16Array = new Int16Array(alignedChunk.buffer, alignedChunk.byteOffset, alignedChunk.byteLength / Int16Array.BYTES_PER_ELEMENT);
35
+ }
36
+ const floatArray = new Float32Array(int16Array.length);
37
+ for (let i = 0; i < int16Array.length; i++) {
38
+ floatArray[i] = int16Array[i] / 32768.0;
39
+ }
40
+ return floatArray;
41
+ }
@@ -0,0 +1,2 @@
1
+ export * from "./SileroVad";
2
+ export * from "./types";
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ /* eslint-disable no-loops/no-loops */
18
+ /*
19
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
20
+ * http://github.com/fonoster/fonoster
21
+ *
22
+ * This file is part of Fonoster
23
+ *
24
+ * Licensed under the MIT License (the "License");
25
+ * you may not use this file except in compliance with
26
+ * the License. You may obtain a copy of the License at
27
+ *
28
+ * https://opensource.org/licenses/MIT
29
+ *
30
+ * Unless required by applicable law or agreed to in writing, software
31
+ * distributed under the License is distributed on an "AS IS" BASIS,
32
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33
+ * See the License for the specific language governing permissions and
34
+ * limitations under the License.
35
+ */
36
+ __exportStar(require("./SileroVad"), exports);
37
+ __exportStar(require("./types"), exports);
@@ -0,0 +1,23 @@
1
+ type VadEvent = "SPEECH_START" | "SPEECH_END";
2
+ type Vad = {
3
+ processChunk: (chunk: Uint8Array, callback: (event: VadEvent) => void) => void;
4
+ };
5
+ type SpeechProbabilities = {
6
+ notSpeech: number;
7
+ isSpeech: number;
8
+ };
9
+ type ONNXRuntimeAPI = {
10
+ InferenceSession: {
11
+ create(modelArrayBuffer: ArrayBuffer, sessionOption: {
12
+ interOpNumThreads: number;
13
+ intraOpNumThreads: number;
14
+ }): Promise<unknown>;
15
+ };
16
+ Tensor: {
17
+ new (type: "int64", data: BigInt[]): unknown;
18
+ new (type: "int64", data: BigInt[], dims: [1]): unknown;
19
+ new (type: "float32", data: Float32Array | number[], dims: [2, 1, 128]): unknown;
20
+ new (type: "float32", data: Float32Array, dims: [1, number]): unknown;
21
+ };
22
+ };
23
+ export { ONNXRuntimeAPI, SpeechProbabilities, Vad, VadEvent };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fonoster/autopilot",
3
- "version": "0.8.40",
3
+ "version": "0.8.42",
4
4
  "description": "Voice AI for the Fonoster platform",
5
5
  "author": "Pedro Sanders <psanders@fonoster.com>",
6
6
  "homepage": "https://github.com/fonoster/fonoster#readme",
@@ -33,11 +33,11 @@
33
33
  },
34
34
  "dependencies": {
35
35
  "@aws-sdk/client-s3": "^3.712.0",
36
- "@fonoster/common": "^0.8.40",
37
- "@fonoster/logger": "^0.8.40",
38
- "@fonoster/sdk": "^0.8.40",
39
- "@fonoster/types": "^0.8.40",
40
- "@fonoster/voice": "^0.8.40",
36
+ "@fonoster/common": "^0.8.42",
37
+ "@fonoster/logger": "^0.8.42",
38
+ "@fonoster/sdk": "^0.8.42",
39
+ "@fonoster/types": "^0.8.42",
40
+ "@fonoster/voice": "^0.8.42",
41
41
  "@langchain/community": "^0.3.19",
42
42
  "@langchain/core": "^0.3.23",
43
43
  "@langchain/groq": "^0.1.2",
@@ -55,5 +55,5 @@
55
55
  "devDependencies": {
56
56
  "typescript": "^5.5.4"
57
57
  },
58
- "gitHead": "2bbf3dadb6e1e178c4eefdeb4291a2e05eef0f2b"
58
+ "gitHead": "640d47090720fc3ce5adc9346b4fdbfde4175445"
59
59
  }
package/silero_vad.onnx CHANGED
Binary file
File without changes
File without changes