tz-voice-chat 1.1.2 → 1.2.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/README.md +607 -149
- package/bin/tz-voice-chat.js +46 -0
- package/dist/assets/whisperWorker-D69IwlqW.js +1 -0
- package/dist/index.cjs +2 -2
- package/dist/index.js +1327 -698
- package/dist/style.css +1 -1
- package/dist-app/assets/index-BDMCgrF_.css +1 -0
- package/dist-app/assets/index-CFWv17S2.js +41 -0
- package/dist-app/assets/llmWorker-CVEGn6yI.js +1 -0
- package/dist-app/assets/whisperWorker-D69IwlqW.js +1 -0
- package/dist-app/index.html +27 -0
- package/package.json +45 -11
- package/server/chat.js +91 -0
- package/server/elevenlabs.js +40 -0
- package/server/index.js +173 -92
- package/server/openai-stt.js +21 -0
- package/server/run.js +42 -0
- package/server/settings.js +102 -0
- package/server/tts.js +26 -3
- package/server/vendor.js +57 -0
- package/shared/settingsSchema.js +212 -0
- package/vendor/kokoro/kokoro.web.js +1 -0
- package/vendor/ort/ort-wasm-simd-threaded.jsep.mjs +125 -0
- package/vendor/ort/ort-wasm-simd-threaded.jsep.wasm +0 -0
- package/vendor/ort/ort-wasm-simd-threaded.mjs +70 -0
- package/vendor/ort/ort-wasm-simd-threaded.wasm +0 -0
- package/vendor/ort/ort.wasm.min.js +8 -0
- package/vendor/transformers/ort-wasm-simd-threaded.jsep.mjs +125 -0
- package/vendor/transformers/ort-wasm-simd-threaded.jsep.wasm +0 -0
- package/vendor/transformers/transformers.min.js +2 -0
- package/vendor/transformers/transformers.node.min.mjs +2 -0
- package/vendor/transformers/transformers.node.mjs +36472 -0
- package/vendor/vad/bundle.min.js +2 -0
- package/vendor/vad/silero_vad_legacy.onnx +0 -0
- package/vendor/vad/vad.worklet.bundle.min.js +1 -0
- package/dist/assets/whisperWorker-BJuP9cl9.js +0 -1
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tz-voice-chat",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "React hook
|
|
3
|
+
"version": "1.2.0",
|
|
4
|
+
"description": "Voice assistant: React hook + UI and a ready-to-run server/CLI. VAD → Whisper STT → LLM → Kokoro/OpenAI/WebSpeech TTS, configurable from a Settings page.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
7
7
|
"module": "./dist/index.js",
|
|
@@ -15,14 +15,34 @@
|
|
|
15
15
|
},
|
|
16
16
|
"files": [
|
|
17
17
|
"dist",
|
|
18
|
+
"dist-app",
|
|
19
|
+
"vendor",
|
|
18
20
|
"server",
|
|
21
|
+
"shared",
|
|
22
|
+
"bin",
|
|
19
23
|
"README.md"
|
|
20
24
|
],
|
|
21
25
|
"scripts": {
|
|
22
|
-
"build": "vite build",
|
|
23
|
-
"
|
|
26
|
+
"build": "node scripts/bundle-vendor.mjs && vite build && vite build --config vite.app.config.js",
|
|
27
|
+
"start": "node bin/tz-voice-chat.js",
|
|
28
|
+
"prepack": "npm run build"
|
|
24
29
|
},
|
|
25
|
-
"keywords": [
|
|
30
|
+
"keywords": [
|
|
31
|
+
"ai",
|
|
32
|
+
"chat",
|
|
33
|
+
"cli",
|
|
34
|
+
"hook",
|
|
35
|
+
"kokoro",
|
|
36
|
+
"react",
|
|
37
|
+
"server",
|
|
38
|
+
"speech",
|
|
39
|
+
"stt",
|
|
40
|
+
"tts",
|
|
41
|
+
"vad",
|
|
42
|
+
"voice",
|
|
43
|
+
"voice-assistant",
|
|
44
|
+
"whisper"
|
|
45
|
+
],
|
|
26
46
|
"license": "MIT",
|
|
27
47
|
"repository": {
|
|
28
48
|
"type": "git",
|
|
@@ -36,13 +56,27 @@
|
|
|
36
56
|
},
|
|
37
57
|
"peerDependencies": {
|
|
38
58
|
"react": ">=18",
|
|
39
|
-
"
|
|
40
|
-
"
|
|
41
|
-
|
|
42
|
-
|
|
59
|
+
"react-dom": ">=18",
|
|
60
|
+
"kokoro-js": "^1.2.1"
|
|
61
|
+
},
|
|
62
|
+
"bin": {
|
|
63
|
+
"tz-voice-chat": "bin/tz-voice-chat.js"
|
|
64
|
+
},
|
|
65
|
+
"dependencies": {
|
|
66
|
+
"express": "^4.18.2"
|
|
67
|
+
},
|
|
68
|
+
"engines": {
|
|
69
|
+
"node": ">=18"
|
|
70
|
+
},
|
|
71
|
+
"devDependencies": {
|
|
72
|
+
"@huggingface/transformers": "3.5.1",
|
|
73
|
+
"@ricky0123/vad-web": "0.0.29",
|
|
74
|
+
"kokoro-js": "1.2.1",
|
|
75
|
+
"onnxruntime-web": "1.22.0"
|
|
43
76
|
},
|
|
44
77
|
"peerDependenciesMeta": {
|
|
45
|
-
"kokoro-js": {
|
|
46
|
-
|
|
78
|
+
"kokoro-js": {
|
|
79
|
+
"optional": true
|
|
80
|
+
}
|
|
47
81
|
}
|
|
48
82
|
}
|
package/server/chat.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Chat provider adapters. Every provider is exposed to the browser as the same
|
|
3
|
+
* OpenAI-style SSE stream ("data: {choices:[{delta:{content}}]}" … "data: [DONE]"),
|
|
4
|
+
* so the client has a single parser.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
const OPENAI_BASE = () => (process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1').replace(/\/$/, '');
|
|
8
|
+
const ANTHROPIC_BASE = () => (process.env.ANTHROPIC_BASE_URL || 'https://api.anthropic.com').replace(/\/$/, '');
|
|
9
|
+
|
|
10
|
+
/** Forward an upstream error response to the client unchanged. Returns true if it was an error. */
|
|
11
|
+
async function forwardError(upstream, res) {
|
|
12
|
+
if (upstream.ok) return false;
|
|
13
|
+
res.status(upstream.status).send(await upstream.text());
|
|
14
|
+
return true;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Providers that already speak OpenAI-style streaming: pass the bytes straight through. */
|
|
18
|
+
export async function streamOpenAICompatible(res, { url, apiKey, body }) {
|
|
19
|
+
const upstream = await fetch(url, {
|
|
20
|
+
method: 'POST',
|
|
21
|
+
// The key is optional: most local / on-premise servers need none.
|
|
22
|
+
headers: { ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}), 'Content-Type': 'application/json' },
|
|
23
|
+
body: JSON.stringify({ ...body, stream: true }),
|
|
24
|
+
});
|
|
25
|
+
if (await forwardError(upstream, res)) return;
|
|
26
|
+
res.setHeader('Content-Type', 'text/plain;charset=UTF-8');
|
|
27
|
+
const reader = upstream.body.getReader();
|
|
28
|
+
const decoder = new TextDecoder();
|
|
29
|
+
while (true) {
|
|
30
|
+
const { done, value } = await reader.read();
|
|
31
|
+
if (done) break;
|
|
32
|
+
res.write(decoder.decode(value, { stream: true }));
|
|
33
|
+
}
|
|
34
|
+
res.end();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export const streamOpenAI = (res, { apiKey, model, messages }) =>
|
|
38
|
+
streamOpenAICompatible(res, {
|
|
39
|
+
url: `${OPENAI_BASE()}/chat/completions`,
|
|
40
|
+
apiKey,
|
|
41
|
+
body: { model, messages, max_tokens: 1250, temperature: 0.7 },
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Anthropic Messages API → OpenAI-style SSE. System messages go in the top-level
|
|
46
|
+
* `system` field; text deltas are re-emitted as OpenAI chunks.
|
|
47
|
+
*/
|
|
48
|
+
export async function streamAnthropic(res, { apiKey, model, messages }) {
|
|
49
|
+
const system = messages.filter(m => m.role === 'system').map(m => m.content).join('\n\n');
|
|
50
|
+
const chat = messages.filter(m => m.role !== 'system');
|
|
51
|
+
const upstream = await fetch(`${ANTHROPIC_BASE()}/v1/messages`, {
|
|
52
|
+
method: 'POST',
|
|
53
|
+
headers: {
|
|
54
|
+
'x-api-key': apiKey,
|
|
55
|
+
'anthropic-version': '2023-06-01',
|
|
56
|
+
'Content-Type': 'application/json',
|
|
57
|
+
},
|
|
58
|
+
body: JSON.stringify({
|
|
59
|
+
model,
|
|
60
|
+
max_tokens: 1250,
|
|
61
|
+
...(system ? { system } : {}),
|
|
62
|
+
messages: chat,
|
|
63
|
+
stream: true,
|
|
64
|
+
}),
|
|
65
|
+
});
|
|
66
|
+
if (await forwardError(upstream, res)) return;
|
|
67
|
+
|
|
68
|
+
res.setHeader('Content-Type', 'text/plain;charset=UTF-8');
|
|
69
|
+
const reader = upstream.body.getReader();
|
|
70
|
+
const decoder = new TextDecoder();
|
|
71
|
+
const emit = (text) => res.write(`data: ${JSON.stringify({ choices: [{ delta: { content: text } }] })}\n\n`);
|
|
72
|
+
let buffer = '';
|
|
73
|
+
while (true) {
|
|
74
|
+
const { done, value } = await reader.read();
|
|
75
|
+
if (done) break;
|
|
76
|
+
buffer += decoder.decode(value, { stream: true });
|
|
77
|
+
const lines = buffer.split('\n');
|
|
78
|
+
buffer = lines.pop();
|
|
79
|
+
for (const line of lines) {
|
|
80
|
+
const t = line.trim();
|
|
81
|
+
if (!t.startsWith('data:')) continue;
|
|
82
|
+
try {
|
|
83
|
+
const evt = JSON.parse(t.slice(5).trim());
|
|
84
|
+
if (evt.type === 'content_block_delta' && evt.delta?.type === 'text_delta' && evt.delta.text) emit(evt.delta.text);
|
|
85
|
+
else if (evt.type === 'error') console.error('[anthropic]', evt.error?.message ?? evt);
|
|
86
|
+
} catch (_) {}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
res.write('data: [DONE]\n\n');
|
|
90
|
+
res.end();
|
|
91
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** ElevenLabs adapters (speech-to-text and text-to-speech). The browser never sees the API key. */
|
|
2
|
+
|
|
3
|
+
const BASE = () => (process.env.ELEVENLABS_BASE_URL || 'https://api.elevenlabs.io').replace(/\/$/, '');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Scribe speech-to-text: POST /v1/speech-to-text (multipart: model_id, file).
|
|
7
|
+
* @returns {Promise<{ok: true, text: string} | {ok: false, status: number, body: string}>}
|
|
8
|
+
*/
|
|
9
|
+
export async function transcribeElevenLabs({ apiKey, model, language, audio, contentType = 'audio/wav' }) {
|
|
10
|
+
const form = new FormData();
|
|
11
|
+
form.append('model_id', model);
|
|
12
|
+
if (language) form.append('language_code', language);
|
|
13
|
+
form.append('tag_audio_events', 'false'); // no "(laughter)" style tags in a voice chat
|
|
14
|
+
form.append('file', new Blob([audio], { type: contentType }), 'speech.wav');
|
|
15
|
+
|
|
16
|
+
const res = await fetch(`${BASE()}/v1/speech-to-text`, {
|
|
17
|
+
method: 'POST',
|
|
18
|
+
headers: { 'xi-api-key': apiKey },
|
|
19
|
+
body: form,
|
|
20
|
+
});
|
|
21
|
+
if (!res.ok) return { ok: false, status: res.status, body: await res.text() };
|
|
22
|
+
const json = await res.json();
|
|
23
|
+
const text = json.text ?? (json.transcripts || []).map(t => t.text).join(' ') ?? '';
|
|
24
|
+
return { ok: true, text: String(text).trim() };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Text-to-speech: POST /v1/text-to-speech/{voice_id} -> MP3 bytes.
|
|
29
|
+
* @returns {Promise<{ok: true, audio: Buffer, contentType: string} | {ok: false, status: number, body: string}>}
|
|
30
|
+
*/
|
|
31
|
+
export async function synthesizeElevenLabs({ apiKey, voiceId, model, text }) {
|
|
32
|
+
if (!/^[\w-]+$/.test(voiceId || '')) return { ok: false, status: 400, body: 'Invalid ElevenLabs voice id' };
|
|
33
|
+
const res = await fetch(`${BASE()}/v1/text-to-speech/${voiceId}?output_format=mp3_44100_128`, {
|
|
34
|
+
method: 'POST',
|
|
35
|
+
headers: { 'xi-api-key': apiKey, 'Content-Type': 'application/json', Accept: 'audio/mpeg' },
|
|
36
|
+
body: JSON.stringify({ text, model_id: model }),
|
|
37
|
+
});
|
|
38
|
+
if (!res.ok) return { ok: false, status: res.status, body: await res.text() };
|
|
39
|
+
return { ok: true, audio: Buffer.from(await res.arrayBuffer()), contentType: res.headers.get('content-type') || 'audio/mpeg' };
|
|
40
|
+
}
|
package/server/index.js
CHANGED
|
@@ -5,82 +5,83 @@
|
|
|
5
5
|
* import { createVoiceAssistantRouter } from 'tz-voice-chat/server';
|
|
6
6
|
*
|
|
7
7
|
* const app = express();
|
|
8
|
-
* const { router, ready } = createVoiceAssistantRouter();
|
|
8
|
+
* const { router, ready } = createVoiceAssistantRouter();
|
|
9
9
|
* app.use('/api', router);
|
|
10
|
-
* await ready();
|
|
10
|
+
* await ready(); // pre-load server-side Kokoro, if selected
|
|
11
11
|
*
|
|
12
|
-
* Routes (relative to the mount point):
|
|
13
|
-
*
|
|
12
|
+
* Routes (relative to the mount point):
|
|
13
|
+
* GET /config public configuration + which required settings are missing
|
|
14
|
+
* GET /settings editable settings (secrets are never returned, only whether they are set)
|
|
15
|
+
* PUT /settings save a partial update (persisted to the settings file, applied immediately)
|
|
16
|
+
* GET /settings/export full settings INCLUDING secrets, as a downloadable JSON file
|
|
17
|
+
* GET /stats server process memory
|
|
18
|
+
* POST /chat POST /stt POST /tts GET /models/* (Hugging Face model proxy)
|
|
14
19
|
*
|
|
15
|
-
*
|
|
16
|
-
* `
|
|
17
|
-
*
|
|
20
|
+
* Configuration precedence: defaults < environment variables (see shared/settingsSchema.js)
|
|
21
|
+
* < `options` < the saved settings file (written by the Settings page).
|
|
22
|
+
* Nothing is required up front: with no chat provider configured the app starts, uses the
|
|
23
|
+
* pre-configured speech models, and asks the user to finish setup in Settings.
|
|
18
24
|
*/
|
|
19
25
|
|
|
20
26
|
import express from 'express';
|
|
21
27
|
import { Readable } from 'node:stream';
|
|
22
|
-
import { configureKokoro, loadKokoro, generateWav } from './tts.js';
|
|
28
|
+
import { configureKokoro, loadKokoro, generateWav, resetKokoro } from './tts.js';
|
|
29
|
+
import { createSettingsStore } from './settings.js';
|
|
30
|
+
import { streamOpenAI, streamAnthropic, streamOpenAICompatible } from './chat.js';
|
|
31
|
+
import { transcribeElevenLabs, synthesizeElevenLabs } from './elevenlabs.js';
|
|
32
|
+
import { transcribeOpenAI } from './openai-stt.js';
|
|
23
33
|
|
|
24
34
|
/**
|
|
25
|
-
* @param {object} [options]
|
|
26
|
-
* @param {
|
|
27
|
-
* @param {
|
|
28
|
-
*
|
|
29
|
-
* @
|
|
30
|
-
* @param {string} [options.ttsProvider] TTS_PROVIDER: server-kokoro | openai | kokoro | webspeech
|
|
31
|
-
* @param {string} [options.kokoroVoice] KOKORO_VOICE
|
|
32
|
-
* @param {string} [options.kokoroDtype] KOKORO_DTYPE
|
|
33
|
-
* @param {number} [options.kokoroSpeed] KOKORO_SPEED speech-rate multiplier (default 1)
|
|
34
|
-
* @param {string} [options.kokoroDevice] KOKORO_DEVICE (server-side)
|
|
35
|
-
* @param {string} [options.kokoroBrowserDevice] KOKORO_BROWSER_DEVICE
|
|
36
|
-
* @param {string} [options.openaiApiKey] OPENAI_API_KEY (for ttsProvider 'openai')
|
|
37
|
-
* @param {string} [options.openaiTtsModel] OPENAI_TTS_MODEL
|
|
38
|
-
* @param {string} [options.openaiTtsVoice] OPENAI_TTS_VOICE
|
|
39
|
-
* @param {string} [options.whisperModel] WHISPER_MODEL
|
|
40
|
-
* @param {string} [options.whisperDtype] WHISPER_DTYPE
|
|
41
|
-
* @param {string} [options.whisperDevice] WHISPER_DEVICE
|
|
42
|
-
* @param {string} [options.webSpeechVoice] WEBSPEECH_VOICE
|
|
43
|
-
* @param {number} [options.webSpeechRate] WEBSPEECH_RATE
|
|
44
|
-
* @param {number} [options.webSpeechPitch] WEBSPEECH_PITCH
|
|
45
|
-
* @returns {{ router: import('express').Router, ready: () => Promise<void> }}
|
|
35
|
+
* @param {object} [options]
|
|
36
|
+
* @param {string} [options.settingsFile] Where saved settings live. Default: $TZ_VOICE_CHAT_SETTINGS or ~/.tz-voice-chat/settings.json
|
|
37
|
+
* @param {object} [options.defaults] Initial values for any setting (keys from shared/settingsSchema.js);
|
|
38
|
+
* the saved settings file takes precedence over these.
|
|
39
|
+
* @returns {{ router: import('express').Router, ready: () => Promise<void>, settings: object }}
|
|
46
40
|
*/
|
|
47
|
-
export function createVoiceAssistantRouter(
|
|
48
|
-
const
|
|
49
|
-
const o = {
|
|
50
|
-
provider: env.OPENAI_PROVIDER || 'openrouter',
|
|
51
|
-
openrouterApiKey: env.OPENROUTER_API_KEY,
|
|
52
|
-
openrouterModel: env.OPENROUTER_MODEL || 'gpt-4o-mini',
|
|
53
|
-
huggingfaceApiKey: env.HUGGINGFACE_API_KEY,
|
|
54
|
-
ttsProvider: env.TTS_PROVIDER || 'server-kokoro',
|
|
55
|
-
kokoroVoice: env.KOKORO_VOICE || 'af_bella',
|
|
56
|
-
kokoroDtype: env.KOKORO_DTYPE || 'q8',
|
|
57
|
-
kokoroDevice: env.KOKORO_DEVICE || 'cpu',
|
|
58
|
-
kokoroSpeed: parseFloat(env.KOKORO_SPEED ?? '1') || 1,
|
|
59
|
-
kokoroBrowserDevice: env.KOKORO_BROWSER_DEVICE || 'wasm',
|
|
60
|
-
openaiApiKey: env.OPENAI_API_KEY || '',
|
|
61
|
-
openaiTtsModel: env.OPENAI_TTS_MODEL || 'tts-1',
|
|
62
|
-
openaiTtsVoice: env.OPENAI_TTS_VOICE || 'alloy',
|
|
63
|
-
whisperModel: env.WHISPER_MODEL || 'onnx-community/whisper-tiny.en',
|
|
64
|
-
whisperDtype: env.WHISPER_DTYPE || 'q8',
|
|
65
|
-
whisperDevice: env.WHISPER_DEVICE || 'cpu',
|
|
66
|
-
webSpeechVoice: env.WEBSPEECH_VOICE || '',
|
|
67
|
-
webSpeechRate: parseFloat(env.WEBSPEECH_RATE ?? '1'),
|
|
68
|
-
webSpeechPitch: parseFloat(env.WEBSPEECH_PITCH ?? '1'),
|
|
69
|
-
...options,
|
|
70
|
-
};
|
|
41
|
+
export function createVoiceAssistantRouter({ settingsFile, defaults = {} } = {}) {
|
|
42
|
+
const settings = createSettingsStore({ file: settingsFile, options: defaults });
|
|
71
43
|
|
|
72
|
-
configureKokoro({ dtype: o.kokoroDtype, device: o.kokoroDevice, voice: o.kokoroVoice });
|
|
44
|
+
const applyKokoro = (o) => configureKokoro({ dtype: o.kokoroDtype, device: o.kokoroDevice, voice: o.kokoroVoice });
|
|
45
|
+
applyKokoro(settings.get());
|
|
46
|
+
|
|
47
|
+
// Server-side Kokoro must be reloaded when its parameters (or the provider) change.
|
|
48
|
+
settings.onChange((now, before) => {
|
|
49
|
+
const changed = ['kokoroDtype', 'kokoroDevice', 'kokoroVoice', 'ttsProvider'].some(k => now[k] !== before[k]);
|
|
50
|
+
if (!changed) return;
|
|
51
|
+
applyKokoro(now);
|
|
52
|
+
resetKokoro();
|
|
53
|
+
if (now.ttsProvider === 'server-kokoro') loadKokoro().catch(err => console.error('[Kokoro]', err.message));
|
|
54
|
+
});
|
|
73
55
|
|
|
74
56
|
const router = express.Router();
|
|
75
57
|
router.use(express.json());
|
|
76
58
|
|
|
77
|
-
|
|
78
|
-
|
|
59
|
+
const chatModel = (o) => ({
|
|
60
|
+
huggingface: 'gpt2',
|
|
61
|
+
openrouter: o.openrouterModel,
|
|
62
|
+
openai: o.openaiChatModel,
|
|
63
|
+
'openai-compatible': o.compatModel,
|
|
64
|
+
anthropic: o.anthropicModel,
|
|
65
|
+
local: 'SmolLM2-360M-Instruct',
|
|
66
|
+
}[o.chatProvider] ?? '');
|
|
67
|
+
|
|
68
|
+
// Public configuration: tells the client how to wire STT/TTS/LLM, and what is still missing.
|
|
79
69
|
router.get('/config', (req, res) => {
|
|
70
|
+
const o = settings.get();
|
|
71
|
+
const { missing } = settings.getPublic();
|
|
72
|
+
const chatReady = !missing.some(m => m.scope === 'chat');
|
|
80
73
|
res.json({
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
74
|
+
chatProvider: o.chatProvider,
|
|
75
|
+
chatModel: chatModel(o),
|
|
76
|
+
chatReady,
|
|
77
|
+
hasApiKey: chatReady && o.chatProvider !== 'local', // true = chat goes through the server proxy
|
|
78
|
+
missing,
|
|
79
|
+
systemPrompt: o.systemPrompt,
|
|
80
|
+
sttProvider: o.sttProvider,
|
|
81
|
+
openaiSttModel: o.openaiSttModel,
|
|
82
|
+
elevenlabsSttModel: o.elevenlabsSttModel,
|
|
83
|
+
elevenlabsVoiceId: o.elevenlabsVoiceId,
|
|
84
|
+
elevenlabsTtsModel: o.elevenlabsTtsModel,
|
|
84
85
|
kokoroDevice: o.kokoroDevice,
|
|
85
86
|
kokoroSpeed: o.kokoroSpeed,
|
|
86
87
|
kokoroDtype: o.kokoroDtype,
|
|
@@ -98,6 +99,29 @@ export function createVoiceAssistantRouter(options = {}) {
|
|
|
98
99
|
});
|
|
99
100
|
});
|
|
100
101
|
|
|
102
|
+
// ── Settings ────────────────────────────────────────────────────────────────
|
|
103
|
+
router.get('/settings', (req, res) => {
|
|
104
|
+
res.json({ ...settings.getPublic(), file: settings.file });
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
router.put('/settings', (req, res) => {
|
|
108
|
+
// Accept either a bare object or the export format ({ settings: {...} }).
|
|
109
|
+
const body = req.body && typeof req.body === 'object' ? req.body : {};
|
|
110
|
+
const patch = body.settings && typeof body.settings === 'object' ? body.settings : body;
|
|
111
|
+
try {
|
|
112
|
+
const { ignored } = settings.update(patch);
|
|
113
|
+
res.json({ ...settings.getPublic(), file: settings.file, ignored });
|
|
114
|
+
} catch (err) {
|
|
115
|
+
console.error('[/settings]', err);
|
|
116
|
+
res.status(500).send(`Could not save settings: ${err.message}`);
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
router.get('/settings/export', (req, res) => {
|
|
121
|
+
res.setHeader('Content-Disposition', 'attachment; filename="tz-voice-chat-settings.json"');
|
|
122
|
+
res.json({ format: 'tz-voice-chat-settings', version: 1, settings: settings.exportAll() });
|
|
123
|
+
});
|
|
124
|
+
|
|
101
125
|
// Server process memory, shown in the client's info card.
|
|
102
126
|
router.get('/stats', (req, res) => {
|
|
103
127
|
const { rss, heapUsed } = process.memoryUsage();
|
|
@@ -105,15 +129,16 @@ export function createVoiceAssistantRouter(options = {}) {
|
|
|
105
129
|
});
|
|
106
130
|
|
|
107
131
|
router.post('/chat', async (req, res) => {
|
|
132
|
+
const o = settings.get();
|
|
108
133
|
const { messages } = req.body;
|
|
109
134
|
if (!messages || !Array.isArray(messages)) {
|
|
110
135
|
return res.status(400).send('Invalid request payload');
|
|
111
136
|
}
|
|
112
137
|
|
|
113
138
|
try {
|
|
114
|
-
if (o.
|
|
139
|
+
if (o.chatProvider === 'huggingface') {
|
|
115
140
|
if (!o.huggingfaceApiKey) {
|
|
116
|
-
return res.status(500).send('Hugging Face
|
|
141
|
+
return res.status(500).send('Hugging Face token is missing — set it in Settings');
|
|
117
142
|
}
|
|
118
143
|
const prompt = messages.map(m => `${m.role}: ${m.content}`).join('\n') + '\nassistant:';
|
|
119
144
|
const response = await fetch('https://api-inference.huggingface.co/models/gpt2', {
|
|
@@ -133,58 +158,97 @@ export function createVoiceAssistantRouter(options = {}) {
|
|
|
133
158
|
return;
|
|
134
159
|
}
|
|
135
160
|
|
|
136
|
-
if (
|
|
137
|
-
return res.status(500).send('
|
|
161
|
+
if (o.chatProvider === 'openai') {
|
|
162
|
+
if (!o.openaiApiKey) return res.status(500).send('OpenAI API key is missing — set it in Settings');
|
|
163
|
+
return await streamOpenAI(res, { apiKey: o.openaiApiKey, model: o.openaiChatModel, messages });
|
|
138
164
|
}
|
|
139
165
|
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
'
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
166
|
+
if (o.chatProvider === 'openai-compatible') {
|
|
167
|
+
let base;
|
|
168
|
+
try {
|
|
169
|
+
base = new URL(o.compatBaseUrl);
|
|
170
|
+
if (!/^https?:$/.test(base.protocol)) throw new Error('not http(s)');
|
|
171
|
+
} catch (_) {
|
|
172
|
+
return res.status(400).send('The OpenAI-compatible server URL is invalid — fix it in Settings');
|
|
173
|
+
}
|
|
174
|
+
if (!o.compatModel) return res.status(400).send('The OpenAI-compatible model name is missing — set it in Settings');
|
|
175
|
+
try {
|
|
176
|
+
return await streamOpenAICompatible(res, {
|
|
177
|
+
url: `${base.href.replace(/\/$/, '')}/chat/completions`,
|
|
178
|
+
apiKey: o.compatApiKey,
|
|
179
|
+
body: { model: o.compatModel, messages, max_tokens: 1250, temperature: 0.7 },
|
|
180
|
+
});
|
|
181
|
+
} catch (err) {
|
|
182
|
+
return res.status(502).send(`Could not reach the OpenAI-compatible server at ${base.origin}: ${err.cause?.code || err.message}`);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
154
185
|
|
|
155
|
-
if (
|
|
156
|
-
return res.status(
|
|
186
|
+
if (o.chatProvider === 'anthropic') {
|
|
187
|
+
if (!o.anthropicApiKey) return res.status(500).send('Anthropic API key is missing — set it in Settings');
|
|
188
|
+
return await streamAnthropic(res, { apiKey: o.anthropicApiKey, model: o.anthropicModel, messages });
|
|
157
189
|
}
|
|
158
190
|
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
if (done) break;
|
|
165
|
-
res.write(decoder.decode(value, { stream: true }));
|
|
191
|
+
if (o.chatProvider !== 'openrouter') {
|
|
192
|
+
return res.status(400).send('No server-side chat provider is configured — choose one in Settings');
|
|
193
|
+
}
|
|
194
|
+
if (!o.openrouterApiKey) {
|
|
195
|
+
return res.status(500).send('OpenRouter API key is missing — set it in Settings');
|
|
166
196
|
}
|
|
167
|
-
res
|
|
197
|
+
await streamOpenAICompatible(res, {
|
|
198
|
+
url: 'https://openrouter.ai/api/v1/chat/completions',
|
|
199
|
+
apiKey: o.openrouterApiKey,
|
|
200
|
+
body: { model: o.openrouterModel, messages, max_tokens: 1250, temperature: 0.7 },
|
|
201
|
+
});
|
|
168
202
|
} catch (err) {
|
|
169
203
|
console.error(err);
|
|
170
204
|
res.status(500).send(err.message || 'Unexpected proxy error');
|
|
171
205
|
}
|
|
172
206
|
});
|
|
173
207
|
|
|
208
|
+
// Speech-to-text for providers that run on the server (OpenAI, ElevenLabs). Body: a WAV file.
|
|
209
|
+
router.post('/stt', express.raw({ type: ['audio/*', 'application/octet-stream'], limit: '25mb' }), async (req, res) => {
|
|
210
|
+
const o = settings.get();
|
|
211
|
+
const providers = {
|
|
212
|
+
elevenlabs: { name: 'ElevenLabs', key: o.elevenlabsApiKey, run: transcribeElevenLabs, model: o.elevenlabsSttModel, language: o.elevenlabsLanguage },
|
|
213
|
+
openai: { name: 'OpenAI', key: o.openaiApiKey, run: transcribeOpenAI, model: o.openaiSttModel, language: o.openaiSttLanguage },
|
|
214
|
+
};
|
|
215
|
+
const sp = providers[o.sttProvider];
|
|
216
|
+
if (!sp) {
|
|
217
|
+
return res.status(400).send('Server-side speech-to-text is not enabled — choose a provider in Settings');
|
|
218
|
+
}
|
|
219
|
+
if (!sp.key) return res.status(500).send(`${sp.name} API key is missing — set it in Settings`);
|
|
220
|
+
if (!Buffer.isBuffer(req.body) || !req.body.length) return res.status(400).send('Send the audio as the request body (audio/wav)');
|
|
221
|
+
try {
|
|
222
|
+
const out = await sp.run({
|
|
223
|
+
apiKey: sp.key,
|
|
224
|
+
model: sp.model,
|
|
225
|
+
language: sp.language,
|
|
226
|
+
audio: req.body,
|
|
227
|
+
contentType: req.headers['content-type'] || 'audio/wav',
|
|
228
|
+
});
|
|
229
|
+
if (!out.ok) return res.status(out.status).send(out.body);
|
|
230
|
+
res.json({ text: out.text });
|
|
231
|
+
} catch (err) {
|
|
232
|
+
console.error('[/stt]', err);
|
|
233
|
+
res.status(500).send(err.message || 'STT error');
|
|
234
|
+
}
|
|
235
|
+
});
|
|
236
|
+
|
|
174
237
|
router.post('/tts', async (req, res) => {
|
|
238
|
+
const o = settings.get();
|
|
175
239
|
const { text, voice, model, speed } = req.body;
|
|
176
240
|
if (!text) return res.status(400).send('text is required');
|
|
177
241
|
|
|
178
242
|
try {
|
|
179
243
|
if (o.ttsProvider === 'server-kokoro') {
|
|
180
|
-
const wavBuf = await generateWav(text, voice || o.kokoroVoice, Number(speed) > 0 ? Number(speed) : 1);
|
|
244
|
+
const wavBuf = await generateWav(text, voice || o.kokoroVoice, Number(speed) > 0 ? Number(speed) : o.kokoroSpeed || 1);
|
|
181
245
|
res.setHeader('Content-Type', 'audio/wav');
|
|
182
246
|
res.setHeader('Content-Length', String(wavBuf.length));
|
|
183
247
|
return res.end(wavBuf);
|
|
184
248
|
}
|
|
185
249
|
|
|
186
250
|
if (o.ttsProvider === 'openai') {
|
|
187
|
-
if (!o.openaiApiKey) return res.status(500).send('
|
|
251
|
+
if (!o.openaiApiKey) return res.status(500).send('OpenAI API key is missing — set it in Settings');
|
|
188
252
|
const response = await fetch('https://api.openai.com/v1/audio/speech', {
|
|
189
253
|
method: 'POST',
|
|
190
254
|
headers: {
|
|
@@ -210,8 +274,22 @@ export function createVoiceAssistantRouter(options = {}) {
|
|
|
210
274
|
return res.end();
|
|
211
275
|
}
|
|
212
276
|
|
|
277
|
+
if (o.ttsProvider === 'elevenlabs') {
|
|
278
|
+
if (!o.elevenlabsApiKey) return res.status(500).send('ElevenLabs API key is missing — set it in Settings');
|
|
279
|
+
const out = await synthesizeElevenLabs({
|
|
280
|
+
apiKey: o.elevenlabsApiKey,
|
|
281
|
+
voiceId: voice || o.elevenlabsVoiceId,
|
|
282
|
+
model: model || o.elevenlabsTtsModel,
|
|
283
|
+
text,
|
|
284
|
+
});
|
|
285
|
+
if (!out.ok) return res.status(out.status).send(out.body);
|
|
286
|
+
res.setHeader('Content-Type', out.contentType);
|
|
287
|
+
res.setHeader('Content-Length', String(out.audio.length));
|
|
288
|
+
return res.end(out.audio);
|
|
289
|
+
}
|
|
290
|
+
|
|
213
291
|
// 'kokoro' (browser) / 'webspeech' — the client synthesises audio itself.
|
|
214
|
-
return res.status(400).send(`
|
|
292
|
+
return res.status(400).send(`TTS provider "${o.ttsProvider}" does not use a server-side audio endpoint`);
|
|
215
293
|
} catch (err) {
|
|
216
294
|
console.error('[/tts]', err);
|
|
217
295
|
res.status(500).send(err.message || 'TTS error');
|
|
@@ -254,10 +332,13 @@ export function createVoiceAssistantRouter(options = {}) {
|
|
|
254
332
|
|
|
255
333
|
// Load server-side Kokoro eagerly so the first TTS request has no cold start.
|
|
256
334
|
async function ready() {
|
|
257
|
-
if (
|
|
335
|
+
if (settings.get().ttsProvider === 'server-kokoro') {
|
|
336
|
+
try { await loadKokoro(); } catch (err) { console.warn('[tz-voice-chat]', err.message); }
|
|
337
|
+
}
|
|
258
338
|
}
|
|
259
339
|
|
|
260
|
-
return { router, ready };
|
|
340
|
+
return { router, ready, settings };
|
|
261
341
|
}
|
|
262
342
|
|
|
343
|
+
export { createVendorRouter } from './vendor.js';
|
|
263
344
|
export { loadKokoro, generateWav };
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** OpenAI speech-to-text: POST /v1/audio/transcriptions (multipart: file, model). */
|
|
2
|
+
|
|
3
|
+
const BASE = () => (process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1').replace(/\/$/, '');
|
|
4
|
+
|
|
5
|
+
/** @returns {Promise<{ok: true, text: string} | {ok: false, status: number, body: string}>} */
|
|
6
|
+
export async function transcribeOpenAI({ apiKey, model, language, audio, contentType = 'audio/wav' }) {
|
|
7
|
+
const form = new FormData();
|
|
8
|
+
form.append('model', model);
|
|
9
|
+
form.append('response_format', 'json');
|
|
10
|
+
if (language) form.append('language', language);
|
|
11
|
+
form.append('file', new Blob([audio], { type: contentType }), 'speech.wav');
|
|
12
|
+
|
|
13
|
+
const res = await fetch(`${BASE()}/audio/transcriptions`, {
|
|
14
|
+
method: 'POST',
|
|
15
|
+
headers: { Authorization: `Bearer ${apiKey}` },
|
|
16
|
+
body: form,
|
|
17
|
+
});
|
|
18
|
+
if (!res.ok) return { ok: false, status: res.status, body: await res.text() };
|
|
19
|
+
const json = await res.json();
|
|
20
|
+
return { ok: true, text: String(json.text ?? '').trim() };
|
|
21
|
+
}
|
package/server/run.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Starts a complete, self-contained voice-assistant server: the API router, the vendored
|
|
3
|
+
* browser runtime assets, and the prebuilt client page. Used by the `tz-voice-chat` CLI.
|
|
4
|
+
*/
|
|
5
|
+
import express from 'express';
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { createVoiceAssistantRouter } from './index.js';
|
|
10
|
+
import { createVendorRouter } from './vendor.js';
|
|
11
|
+
|
|
12
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
13
|
+
const appDir = path.resolve(here, '../dist-app');
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @param {object} [opts]
|
|
17
|
+
* @param {number} [opts.port=3000]
|
|
18
|
+
* @param {string} [opts.host='127.0.0.1'] Loopback by default: the Settings endpoints can read and
|
|
19
|
+
* write API keys, so only expose them on a network you trust.
|
|
20
|
+
* @param {string} [opts.settingsFile]
|
|
21
|
+
* @returns {Promise<{ url: string, server: import('node:http').Server, settings: object }>}
|
|
22
|
+
*/
|
|
23
|
+
export async function startServer({ port = 3000, host = '127.0.0.1', settingsFile } = {}) {
|
|
24
|
+
if (!fs.existsSync(path.join(appDir, 'index.html'))) {
|
|
25
|
+
throw new Error(`Client app not found at ${appDir}. Run "npm run build" in the tz-voice-chat package first.`);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const app = express();
|
|
29
|
+
const { router, ready, settings } = createVoiceAssistantRouter({ settingsFile });
|
|
30
|
+
app.use('/api', router);
|
|
31
|
+
app.use('/vendor', createVendorRouter());
|
|
32
|
+
app.use(express.static(appDir));
|
|
33
|
+
app.get('*', (req, res) => res.sendFile(path.join(appDir, 'index.html')));
|
|
34
|
+
|
|
35
|
+
await ready();
|
|
36
|
+
const server = await new Promise((resolve, reject) => {
|
|
37
|
+
const s = app.listen(port, host, () => resolve(s));
|
|
38
|
+
s.on('error', reject);
|
|
39
|
+
});
|
|
40
|
+
const shown = host === '0.0.0.0' || host === '::' ? 'localhost' : host;
|
|
41
|
+
return { url: `http://${shown}:${server.address().port}`, server, settings, host };
|
|
42
|
+
}
|