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/README.md
CHANGED
|
@@ -1,211 +1,669 @@
|
|
|
1
1
|
# tz-voice-chat
|
|
2
2
|
|
|
3
|
-
A
|
|
3
|
+
A complete **voice assistant** you can run in one command, and the building blocks to make your own:
|
|
4
4
|
|
|
5
5
|
```
|
|
6
|
-
Microphone → VAD →
|
|
6
|
+
Microphone → VAD → speech-to-text → your chat logic (or an LLM) → text-to-speech → speaker
|
|
7
7
|
```
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
- **Run it now:** `npx tz-voice-chat` — a ready web app with a Settings page. No `.env`, no code.
|
|
10
|
+
- **Make it yours:** React hooks and components for the browser, plus an Express router for the server. Replace any stage — in particular the "chat logic" — with your own.
|
|
11
|
+
- **Pick your providers:** every stage works locally for free *or* in the cloud, switchable at runtime.
|
|
12
|
+
|
|
13
|
+
| Stage | Local · free | Cloud |
|
|
14
|
+
|---|---|---|
|
|
15
|
+
| Speech-to-text | Whisper in the browser | OpenAI transcription, ElevenLabs Scribe |
|
|
16
|
+
| Chat | In-browser SmolLM2 (slow and simple), any OpenAI-compatible server (Ollama, LM Studio, vLLM, on-premise) | OpenRouter, OpenAI, Anthropic (Claude), Hugging Face |
|
|
17
|
+
| Text-to-speech | Kokoro (browser or server), Web Speech API | OpenAI, ElevenLabs |
|
|
18
|
+
|
|
19
|
+
## Contents
|
|
20
|
+
|
|
21
|
+
1. [Quick start](#quick-start)
|
|
22
|
+
2. [Architecture overview](#architecture-overview) — the big picture, **why a server is needed**, one conversation turn, the state machine
|
|
23
|
+
3. [Components](#components) — what each piece does and where it lives
|
|
24
|
+
4. [Build your own chat](#build-your-own-chat) — a complete, tested project, step by step
|
|
25
|
+
5. [Reference](#reference) — hooks, components, server API, settings
|
|
26
|
+
6. [Troubleshooting](#troubleshooting)
|
|
10
27
|
|
|
11
28
|
---
|
|
12
29
|
|
|
13
|
-
##
|
|
30
|
+
## Quick start
|
|
14
31
|
|
|
15
32
|
```bash
|
|
16
|
-
|
|
33
|
+
npx tz-voice-chat # then open http://127.0.0.1:3000
|
|
17
34
|
```
|
|
18
35
|
|
|
19
|
-
|
|
36
|
+
Requires Node 18+ and a modern browser. The install is light: one runtime dependency (`express`), no native code and no install scripts. Defaults work without any keys: Whisper `small.en` for speech-to-text, Kokoro (`af_bella`) for text-to-speech — both on WebGPU — and the in-browser SmolLM2 model for chat. The first load downloads the models (hundreds of MB).
|
|
20
37
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
38
|
+
Open the **Settings** page (gear icon) to choose a better chat model (OpenAI, Claude, Ollama…), cloud speech, voices and so on. Changes are saved and applied immediately — no restart. If something required is missing (say an API key for the provider you picked), a notice tells you what.
|
|
39
|
+
|
|
40
|
+
```
|
|
41
|
+
-p, --port <n> Port (default $PORT or 3000)
|
|
42
|
+
--host <addr> Address to bind (default 127.0.0.1)
|
|
43
|
+
--settings <file> Settings file (default ~/.tz-voice-chat/settings.json, or $TZ_VOICE_CHAT_SETTINGS)
|
|
25
44
|
```
|
|
26
45
|
|
|
46
|
+
- **Export / Import** on the Settings page saves/loads every setting as a JSON file. The export **includes your API keys** — keep it private.
|
|
47
|
+
- The page never receives saved keys: a saved key shows as "Saved" and is replaced only when you type a new one.
|
|
48
|
+
- Environment variables (listed in the [settings reference](#settings-reference)) pre-seed the initial values; whatever you save in Settings wins.
|
|
49
|
+
- The server binds to loopback by default because the Settings endpoints can read and write API keys. Use `--host 0.0.0.0` only on a network you trust.
|
|
50
|
+
|
|
27
51
|
---
|
|
28
52
|
|
|
29
|
-
##
|
|
53
|
+
## Architecture overview
|
|
54
|
+
|
|
55
|
+
### The big picture
|
|
56
|
+
|
|
57
|
+
```
|
|
58
|
+
┌─ BROWSER (your page) ───────────────────────────────────────────────────────────┐
|
|
59
|
+
│ UI VoiceAssistant · SettingsPanel · AIAssistantButton │
|
|
60
|
+
│ │ useVoiceAssistant (config, backends, Settings) │
|
|
61
|
+
│ Pipeline TZVoiceChat: mic → VAD → STT → processInput() → TTS → speaker │
|
|
62
|
+
│ │
|
|
63
|
+
│ Runs locally Whisper (Web Worker) · Kokoro (WebGPU) · SmolLM2 · Web Speech API │
|
|
64
|
+
└──────────────────────────────────────────────────────────────────────────────────┘
|
|
65
|
+
│ same-origin HTTP: /api/* and /vendor/*
|
|
66
|
+
┌─ YOUR SERVER (tz-voice-chat/server, Express) ───────────────────────────────────┐
|
|
67
|
+
│ GET /config PUT /settings settings.json: API keys live HERE, not in the page│
|
|
68
|
+
│ POST /chat /stt /tts adapters: one request shape in, provider's out │
|
|
69
|
+
│ GET /models/* Hugging Face GET /vendor/* ONNX · VAD · transformers runtime │
|
|
70
|
+
└──────────────────────────────────────────────────────────────────────────────────┘
|
|
71
|
+
│ server-to-server — the keys are attached here
|
|
72
|
+
┌─ PROVIDERS ──────────────────────────────────────────────────────────────────────┐
|
|
73
|
+
│ Chat OpenAI · Anthropic · OpenRouter · Hugging Face · Ollama/LM Studio/vLLM │
|
|
74
|
+
│ STT OpenAI · ElevenLabs TTS OpenAI · ElevenLabs · Kokoro (server) │
|
|
75
|
+
│ Models huggingface.co (reached only through /models/*) │
|
|
76
|
+
└──────────────────────────────────────────────────────────────────────────────────┘
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Everything in the top box runs in the page. Anything that needs a secret, a vendor API, or a large file goes through the server in the middle.
|
|
80
|
+
|
|
81
|
+
### Why a server is required
|
|
82
|
+
|
|
83
|
+
The browser can do speech recognition, speech synthesis and even a small LLM by itself. A server is needed for everything else — and it is intentionally thin:
|
|
84
|
+
|
|
85
|
+
```
|
|
86
|
+
WITHOUT a server WITH tz-voice-chat/server
|
|
87
|
+
──────────────── ─────────────────────────
|
|
88
|
+
Browser ──(API key inside your JS)──▶ OpenAI Browser ──▶ /api/chat ──(key stays here)──▶ OpenAI
|
|
89
|
+
✗ anyone can read the key in DevTools ✓ the key never reaches the page
|
|
90
|
+
✗ many providers block or discourage direct ✓ same origin: no CORS problems
|
|
91
|
+
browser calls (CORS, keys in client code) ✓ one stream format for every provider
|
|
92
|
+
✗ every provider streams in a different format ✓ settings survive reloads and restarts
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
| Reason | What the server does |
|
|
96
|
+
|---|---|
|
|
97
|
+
| **Secrets** | API keys (OpenAI, Anthropic, ElevenLabs, OpenRouter, Hugging Face) are stored in `settings.json` on the server. `GET /settings` never returns them — only whether each one is set. |
|
|
98
|
+
| **CORS and browser limits** | Calls to provider APIs are made server-to-server, so they work regardless of what the vendor allows from a web page. This is also how a local model (Ollama, LM Studio) on the server's network becomes reachable. |
|
|
99
|
+
| **One streaming format** | Anthropic streams differently from OpenAI. The server converts every chat provider to the same OpenAI-style event stream, so the client has a single parser. |
|
|
100
|
+
| **Model files** | `GET /models/*` proxies Hugging Face downloads through your origin (cacheable, mirrorable, works behind a firewall). The browser never talks to huggingface.co directly. |
|
|
101
|
+
| **Runtime assets** | ONNX Runtime WASM files, the VAD model and the transformers/Kokoro bundles are loaded **by URL** at runtime, and must be same-origin. They ship inside the package (`vendor/`, about 62 MB — a ~16 MB download), and `createVendorRouter()` serves them at `/vendor/*`. Nothing is fetched from a CDN, and nothing native is installed. |
|
|
102
|
+
| **Server-side speech** | `server-kokoro` runs Kokoro in Node, so browsers without WebGPU still get good TTS. OpenAI/ElevenLabs STT and TTS are proxied here too. |
|
|
103
|
+
| **Persistent settings** | The Settings page saves to a file; the server applies changes live (and reloads server-side Kokoro when its parameters change). |
|
|
104
|
+
|
|
105
|
+
**When you don't need it:** if everything runs in the browser (Whisper + Web Speech or Kokoro on WebGPU + a `processInput` that calls your own backend) you only have to serve `/vendor/*` and the model downloads yourself. The moment you use any cloud provider, the server is what keeps the key safe.
|
|
106
|
+
|
|
107
|
+
### One conversation turn
|
|
108
|
+
|
|
109
|
+
```
|
|
110
|
+
you speak
|
|
111
|
+
│ VAD (voice-activity detection) finds the end of the utterance → 16 kHz audio
|
|
112
|
+
▼
|
|
113
|
+
SPEECH-TO-TEXT ── Whisper in a Web Worker ───────────────── or ── POST /api/stt ──▶ OpenAI / ElevenLabs
|
|
114
|
+
│ text (audio sent as a WAV file)
|
|
115
|
+
│ → timing "transcribe"
|
|
116
|
+
▼
|
|
117
|
+
processInput(text, history, signal) ◀── YOUR CODE, or POST /api/chat ──▶ the configured provider
|
|
118
|
+
│ an async generator: yields text chunks as they are produced
|
|
119
|
+
│ → timing "think" = time to the first chunk
|
|
120
|
+
▼
|
|
121
|
+
SENTENCE CHUNKER small first chunk (fast first audio), then whole sentences (natural prosody)
|
|
122
|
+
▼
|
|
123
|
+
TEXT-TO-SPEECH queue ── Kokoro (browser) ─ Web Speech ─ or ── POST /api/tts ──▶ server Kokoro / OpenAI / ElevenLabs
|
|
124
|
+
│ audio clips are trimmed of silence and played back to back
|
|
125
|
+
│ → timing "tts" = first sentence queued → audio starts
|
|
126
|
+
▼
|
|
127
|
+
speaker
|
|
128
|
+
|
|
129
|
+
BARGE-IN: if you start talking while it is speaking, playback stops and `signal` aborts the
|
|
130
|
+
in-flight request, so your processInput can cancel its LLM call.
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
### Status state machine
|
|
134
|
+
|
|
135
|
+
`status` (from `TZVoiceChat`) tells your UI what to show:
|
|
136
|
+
|
|
137
|
+
```
|
|
138
|
+
idle ──startListening()──▶ listening ──speech ends──▶ transcribing ──text──▶ thinking ──first chunk──▶ speaking
|
|
139
|
+
▲ ▲ │
|
|
140
|
+
└────stopListening()────────┴───── playback finished (back to listening while the mic is on) ◀────────┘
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
Typed messages (`submitText`) skip the first two steps and enter at `thinking`.
|
|
144
|
+
|
|
145
|
+
### Where settings come from
|
|
146
|
+
|
|
147
|
+
```
|
|
148
|
+
built-in defaults < environment variables < router `defaults` option < saved settings file
|
|
149
|
+
(shared/settingsSchema.js) (~/.tz-voice-chat/settings.json,
|
|
150
|
+
written by the Settings page)
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
One schema file, `shared/settingsSchema.js`, defines every setting (key, label, env variable, default, whether it is secret, when it is shown) and the "what is still missing" rules. The server validates with it and the Settings form is generated from it — so adding a setting means adding one entry.
|
|
154
|
+
|
|
155
|
+
---
|
|
156
|
+
|
|
157
|
+
## Components
|
|
158
|
+
|
|
159
|
+
```
|
|
160
|
+
tz-voice-chat
|
|
161
|
+
├── Client (import from 'tz-voice-chat')
|
|
162
|
+
│ ├── VoiceAssistant full UI: status, setup notice, info card, mic button, input, transcript, Settings
|
|
163
|
+
│ │ ├── SettingsPanel Settings page (form from the schema, save, import / export)
|
|
164
|
+
│ │ └── AIAssistantButton animated mic button with waveform and microphone picker
|
|
165
|
+
│ ├── useVoiceAssistant "batteries included" hook: loads /config, picks the chat backend, tracks what's missing
|
|
166
|
+
│ │ └── TZVoiceChat the pipeline hook: VAD → STT → processInput → TTS (+ transcript, status, timings)
|
|
167
|
+
│ │ └── modules/ vad · whisperWorker · chunker · ttsQueue · serverTtsQueue · webSpeechTts · wav
|
|
168
|
+
│ └── sendChatRequest / createLocalChatStream the two ready-made `processInput` backends
|
|
169
|
+
│
|
|
170
|
+
├── Server (import from 'tz-voice-chat/server')
|
|
171
|
+
│ ├── createVoiceAssistantRouter() Express router: /config /settings /stats /chat /stt /tts /models/*
|
|
172
|
+
│ │ ├── settings store defaults < env < options < saved file; secrets stay server-side
|
|
173
|
+
│ │ └── adapters chat (OpenAI-compatible · Anthropic) · stt (OpenAI · ElevenLabs) · tts (Kokoro · OpenAI · ElevenLabs)
|
|
174
|
+
│ └── createVendorRouter() /vendor/* — ONNX runtime, VAD, transformers, Kokoro (from node_modules)
|
|
175
|
+
│
|
|
176
|
+
└── CLI `tz-voice-chat` server + vendor assets + prebuilt web page, in one command
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
| Component | You'd use it to… |
|
|
180
|
+
|---|---|
|
|
181
|
+
| `VoiceAssistant` | drop in a finished UI (one line) |
|
|
182
|
+
| `useVoiceAssistant` | build your own UI but keep config, backends and Settings handled for you |
|
|
183
|
+
| `TZVoiceChat` | build your own UI **and** your own chat logic, with full control over every option |
|
|
184
|
+
| `AIAssistantButton` | reuse just the animated mic button |
|
|
185
|
+
| `SettingsPanel` | reuse just the Settings page |
|
|
186
|
+
| `createVoiceAssistantRouter` | get `/stt` `/tts` `/chat` `/models` `/settings` without writing them |
|
|
187
|
+
| `createVendorRouter` | serve the browser runtime assets without copying files |
|
|
188
|
+
|
|
189
|
+
### Choose your level
|
|
190
|
+
|
|
191
|
+
```
|
|
192
|
+
Level 1 CLI npx tz-voice-chat no code
|
|
193
|
+
Level 2 Drop-in UI <VoiceAssistant /> + router ~10 lines
|
|
194
|
+
Level 3 Your UI useVoiceAssistant + your JSX (+ SettingsPanel) your layout, our plumbing
|
|
195
|
+
Level 4 Your UI + your brain TZVoiceChat({ processInput }) + router for speech full control ◀── the tutorial below
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
---
|
|
199
|
+
|
|
200
|
+
## Build your own chat
|
|
201
|
+
|
|
202
|
+
This tutorial builds **Level 4**: your own React UI and your own chat logic (the "brain"), with tz-voice-chat doing the hard parts — microphone, voice detection, speech-to-text, sentence chunking, text-to-speech and interruptions. The brain here is a tiny echo so it runs without keys; in the last step you swap it for a real LLM, RAG, tools — anything that can produce text.
|
|
203
|
+
|
|
204
|
+
The project in steps 1–6, and the Level 3 shortcut after it, was built and run exactly as written (Node 20, Express 5, Vite). The Ollama snippet in step 7 is illustrative.
|
|
205
|
+
|
|
206
|
+
### 1. Project setup
|
|
207
|
+
|
|
208
|
+
```bash
|
|
209
|
+
mkdir my-voice-chat && cd my-voice-chat
|
|
210
|
+
npm init -y && npm pkg set type=module
|
|
211
|
+
npm install tz-voice-chat express react react-dom
|
|
212
|
+
npm install -D vite @vitejs/plugin-react
|
|
213
|
+
mkdir src
|
|
214
|
+
npm pkg set scripts.dev="vite" scripts.build="vite build" scripts.start="node server.js"
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
### 2. The server — `server.js`
|
|
218
|
+
|
|
219
|
+
The server does what the browser must not: model downloads, runtime files, keys and cloud calls. You mount the package router, then add **your** endpoint beside it.
|
|
220
|
+
|
|
221
|
+
```js
|
|
222
|
+
import express from 'express';
|
|
223
|
+
import path from 'node:path';
|
|
224
|
+
import { fileURLToPath } from 'node:url';
|
|
225
|
+
import { createVoiceAssistantRouter, createVendorRouter } from 'tz-voice-chat/server';
|
|
226
|
+
|
|
227
|
+
const app = express();
|
|
228
|
+
|
|
229
|
+
// Everything the browser must not do itself: model downloads, API keys, cloud STT/TTS, settings.
|
|
230
|
+
const { router, ready } = createVoiceAssistantRouter();
|
|
231
|
+
app.use('/api', router); // /api/config /api/stt /api/tts /api/models/* ...
|
|
232
|
+
app.use('/vendor', createVendorRouter()); // ONNX / VAD / transformers runtime files
|
|
233
|
+
|
|
234
|
+
// YOUR chat logic. Swap this echo for an LLM call, RAG, tool use, a database lookup...
|
|
235
|
+
app.post('/api/ask', express.json(), async (req, res) => {
|
|
236
|
+
const { messages } = req.body;
|
|
237
|
+
const last = messages.at(-1)?.content ?? '';
|
|
238
|
+
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
|
|
239
|
+
for (const word of `You said: ${last}`.split(' ')) {
|
|
240
|
+
res.write(word + ' '); // stream as you generate
|
|
241
|
+
await new Promise((r) => setTimeout(r, 60));
|
|
242
|
+
}
|
|
243
|
+
res.end();
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
const dist = path.resolve(path.dirname(fileURLToPath(import.meta.url)), 'dist');
|
|
247
|
+
app.use(express.static(dist));
|
|
248
|
+
app.use((req, res) => res.sendFile(path.join(dist, 'index.html'))); // SPA fallback (works in Express 4 and 5)
|
|
249
|
+
|
|
250
|
+
const port = process.env.PORT || 3000;
|
|
251
|
+
ready().then(() => app.listen(port, () => console.log(`http://localhost:${port}`)));
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
- `createVoiceAssistantRouter()` gives you `/api/config`, `/api/stt`, `/api/tts`, `/api/models/*`, `/api/chat`, `/api/settings` …
|
|
255
|
+
- `createVendorRouter()` serves the browser runtime files at `/vendor/*`.
|
|
256
|
+
- `/api/ask` is your brain. It receives the whole conversation and streams plain text back. (Express 4 or 5 both work.)
|
|
257
|
+
|
|
258
|
+
### 3. The page — `index.html`
|
|
259
|
+
|
|
260
|
+
Two things must exist before your app starts: an import map (Kokoro imports `@huggingface/transformers` by bare name) and the VAD scripts (a classic bundle that defines `window.vad`).
|
|
261
|
+
|
|
262
|
+
```html
|
|
263
|
+
<!doctype html>
|
|
264
|
+
<html lang="en">
|
|
265
|
+
<head>
|
|
266
|
+
<meta charset="UTF-8" />
|
|
267
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
268
|
+
<title>My voice chat</title>
|
|
269
|
+
<style>body { margin: 0; background: #0f172a; }</style>
|
|
270
|
+
<!-- kokoro-js imports @huggingface/transformers as a bare specifier at runtime. -->
|
|
271
|
+
<script type="importmap">
|
|
272
|
+
{ "imports": { "@huggingface/transformers": "/vendor/transformers/transformers.min.js" } }
|
|
273
|
+
</script>
|
|
274
|
+
<!-- The VAD bundle is a classic script that defines window.vad (and needs onnxruntime-web first). -->
|
|
275
|
+
<script src="/vendor/ort/ort.wasm.min.js"></script>
|
|
276
|
+
<script src="/vendor/vad/bundle.min.js"></script>
|
|
277
|
+
</head>
|
|
278
|
+
<body>
|
|
279
|
+
<div id="root"></div>
|
|
280
|
+
<script type="module" src="/src/main.jsx"></script>
|
|
281
|
+
</body>
|
|
282
|
+
</html>
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
### 4. Vite — `vite.config.js`
|
|
286
|
+
|
|
287
|
+
```js
|
|
288
|
+
import { defineConfig } from 'vite';
|
|
289
|
+
import react from '@vitejs/plugin-react';
|
|
290
|
+
|
|
291
|
+
// /vendor/* files are served by the Express server at runtime, never bundled.
|
|
292
|
+
const isVendor = (id) => id.startsWith('/vendor/');
|
|
293
|
+
|
|
294
|
+
export default defineConfig({
|
|
295
|
+
plugins: [
|
|
296
|
+
react(),
|
|
297
|
+
{ name: 'vendor-external', enforce: 'pre', resolveId: (id) => (isVendor(id) ? { id, external: true } : null) },
|
|
298
|
+
],
|
|
299
|
+
// Serve the package as-is in dev: pre-bundling would break its relative Web Worker URLs.
|
|
300
|
+
optimizeDeps: { exclude: ['tz-voice-chat'] },
|
|
301
|
+
server: { proxy: { '/api': 'http://localhost:3000', '/vendor': 'http://localhost:3000' } },
|
|
302
|
+
build: { rollupOptions: { external: isVendor } },
|
|
303
|
+
worker: { rollupOptions: { external: isVendor } },
|
|
304
|
+
});
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
- `/vendor/*` is never bundled — Express serves it at runtime.
|
|
308
|
+
- `optimizeDeps.exclude` is needed in dev because Vite's dependency pre-bundling breaks the package's Web Worker URLs.
|
|
309
|
+
- In dev the proxy sends `/api` and `/vendor` to Express, so run `npm start` (after one `npm run build`) in one terminal and `npm run dev` in another. Vite prints a harmless warning that the classic `<script>` tags "can't be bundled without type=module" — they are meant to stay as they are.
|
|
310
|
+
|
|
311
|
+
### 5. The app — `src/main.jsx` and `src/App.jsx`
|
|
30
312
|
|
|
31
313
|
```jsx
|
|
314
|
+
import { createRoot } from 'react-dom/client';
|
|
315
|
+
import App from './App.jsx';
|
|
316
|
+
|
|
317
|
+
createRoot(document.getElementById('root')).render(<App />);
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
This is the heart of it:
|
|
321
|
+
|
|
322
|
+
```jsx
|
|
323
|
+
import { useState } from 'react';
|
|
32
324
|
import { TZVoiceChat, AIAssistantButton } from 'tz-voice-chat';
|
|
33
325
|
import 'tz-voice-chat/style.css';
|
|
34
326
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
let buf = '';
|
|
65
|
-
while (true) {
|
|
66
|
-
const { value, done } = await reader.read();
|
|
67
|
-
if (done) break;
|
|
68
|
-
buf += dec.decode(value, { stream: true });
|
|
69
|
-
const lines = buf.split('\n');
|
|
70
|
-
buf = lines.pop();
|
|
71
|
-
for (const line of lines) {
|
|
72
|
-
const data = line.replace(/^data:\s*/, '');
|
|
73
|
-
if (data === '[DONE]') return;
|
|
74
|
-
try { const token = JSON.parse(data).choices?.[0]?.delta?.content; if (token) yield token; }
|
|
75
|
-
catch (_) {}
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
},
|
|
79
|
-
|
|
80
|
-
// ── Optional ─────────────────────────────────────────────────────────
|
|
81
|
-
ttsProvider: 'server-kokoro', // 'server-kokoro' | 'kokoro' | 'openai' | 'webspeech'
|
|
82
|
-
ttsVoice: 'af_bella',
|
|
83
|
-
ttsServerUrl: '/api/tts', // POST endpoint for server-side TTS
|
|
84
|
-
whisperModel: 'onnx-community/whisper-tiny.en',
|
|
85
|
-
whisperDtype: 'q8',
|
|
86
|
-
whisperDevice: 'cpu', // 'cpu' | 'webgpu'
|
|
87
|
-
modelProxyUrl: '/api/models/', // proxies HuggingFace model downloads
|
|
327
|
+
// Your "brain": an async generator. It receives what the user said, the whole conversation
|
|
328
|
+
// and an AbortSignal (fired when the user interrupts), and yields text as it is produced.
|
|
329
|
+
async function* ask(text, history, signal) {
|
|
330
|
+
const res = await fetch('/api/ask', {
|
|
331
|
+
method: 'POST',
|
|
332
|
+
headers: { 'Content-Type': 'application/json' },
|
|
333
|
+
body: JSON.stringify({ messages: history }),
|
|
334
|
+
signal,
|
|
335
|
+
});
|
|
336
|
+
if (!res.ok) throw new Error(await res.text());
|
|
337
|
+
const reader = res.body.getReader();
|
|
338
|
+
const decoder = new TextDecoder();
|
|
339
|
+
for (;;) {
|
|
340
|
+
const { value, done } = await reader.read();
|
|
341
|
+
if (done) return;
|
|
342
|
+
yield decoder.decode(value, { stream: true });
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
export default function App() {
|
|
347
|
+
const chat = TZVoiceChat({
|
|
348
|
+
processInput: ask,
|
|
349
|
+
systemPrompt: 'You are a concise voice assistant.',
|
|
350
|
+
// STT: Whisper runs in a Web Worker in the browser (downloaded once, ~40 MB for tiny).
|
|
351
|
+
whisperModel: 'onnx-community/whisper-tiny.en', whisperDtype: 'q8', whisperDevice: 'wasm',
|
|
352
|
+
// TTS: start with the browser's built-in voices — no download, works everywhere.
|
|
353
|
+
// Upgrade later: 'kokoro' (needs WebGPU), 'server-kokoro', 'openai' or 'elevenlabs'.
|
|
354
|
+
ttsProvider: 'webspeech',
|
|
355
|
+
modelProxyUrl: '/api/models/',
|
|
88
356
|
});
|
|
357
|
+
const [draft, setDraft] = useState('');
|
|
89
358
|
|
|
90
359
|
return (
|
|
91
|
-
<
|
|
92
|
-
<
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
360
|
+
<main style={{ maxWidth: 640, margin: '2rem auto', fontFamily: 'system-ui', color: '#e2e8f0' }}>
|
|
361
|
+
<h1>My voice chat <small>({chat.status})</small></h1>
|
|
362
|
+
|
|
363
|
+
<AIAssistantButton
|
|
364
|
+
status={chat.status}
|
|
365
|
+
active={chat.micEnabled}
|
|
366
|
+
loading={chat.loading}
|
|
367
|
+
analyser={chat.liveAnalyser}
|
|
368
|
+
onToggle={chat.micEnabled ? chat.stopListening : chat.startListening}
|
|
369
|
+
devices={chat.devices}
|
|
370
|
+
selectedMicId={chat.selectedMicId}
|
|
371
|
+
onDeviceChange={chat.setSelectedMicId}
|
|
372
|
+
/>
|
|
373
|
+
{chat.loading && <p>Loading models… whisper {Math.round(chat.progress.whisper * 100)}%, tts {Math.round(chat.progress.kokoro * 100)}%</p>}
|
|
374
|
+
|
|
375
|
+
<form onSubmit={(e) => { e.preventDefault(); if (draft.trim()) { chat.submitText(draft); setDraft(''); } }}>
|
|
376
|
+
<input value={draft} onChange={(e) => setDraft(e.target.value)} placeholder="…or type a message" disabled={chat.loading} />
|
|
377
|
+
</form>
|
|
378
|
+
|
|
379
|
+
{chat.transcript.map((m) => (
|
|
380
|
+
<p key={m.id}>
|
|
381
|
+
<b>{m.role}:</b> {m.content}{' '}
|
|
382
|
+
{m.timings && <small>{Object.entries(m.timings).map(([k, v]) => `${k.replace('Ms', '')} ${v} ms`).join(' · ')}</small>}
|
|
383
|
+
</p>
|
|
99
384
|
))}
|
|
100
|
-
|
|
385
|
+
{chat.streamingMessage !== null && <p><b>assistant:</b> {chat.streamingMessage}…</p>}
|
|
386
|
+
{chat.error && <p style={{ color: '#fca5a5' }}>Error: {chat.error}</p>}
|
|
387
|
+
</main>
|
|
101
388
|
);
|
|
102
389
|
}
|
|
103
390
|
```
|
|
104
391
|
|
|
105
|
-
|
|
392
|
+
What to notice:
|
|
106
393
|
|
|
107
|
-
|
|
394
|
+
- **`processInput` is the only thing you must supply.** It is an async generator `(text, history, signal)`. `history` is the full `[{ role, content }]` array (system prompt first). Yield text as you get it — the pipeline speaks sentence by sentence while you are still generating. Throw an error and it appears in `chat.error`.
|
|
395
|
+
- **`signal`** aborts when the user interrupts (barge-in) or stops listening. Pass it to `fetch` (or your LLM SDK) so the request is cancelled.
|
|
396
|
+
- **`chat.status`** drives your UI (`idle` → `listening` → `transcribing` → `thinking` → `speaking`).
|
|
397
|
+
- **`chat.transcript`** entries have `id`, `role`, `content` and `timings` (`transcribeMs` on your messages; `thinkMs` and `ttsMs` on the assistant's).
|
|
398
|
+
- **`submitText(text)`** feeds typed text through the same pipeline as speech.
|
|
399
|
+
- **Speech options:** this example uses Whisper (in a Web Worker, downloaded once) and the browser's built-in voices, so it needs no big download. The comment shows the upgrade path; the table in [TZVoiceChat options](#tzvoicechatoptions) lists everything.
|
|
108
400
|
|
|
109
|
-
###
|
|
401
|
+
### 6. Run it
|
|
110
402
|
|
|
111
|
-
|
|
403
|
+
```bash
|
|
404
|
+
npm run build
|
|
405
|
+
npm start # http://localhost:3000 (PORT=3001 npm start to change the port)
|
|
406
|
+
```
|
|
112
407
|
|
|
113
|
-
|
|
114
|
-
|---|---|---|
|
|
115
|
-
| `processInput` | `async function*(text, history, signal)` | Your AI processor. Called after each user utterance. `history` is the full `[{role,content}]` array. Yield response tokens. |
|
|
408
|
+
Open the page, wait for the models to load, then type a message or click the mic and talk. You should see your words, the streamed reply, and per-message timings. Click the mic button again to stop.
|
|
116
409
|
|
|
117
|
-
|
|
410
|
+
### 7. Swap in a real brain
|
|
118
411
|
|
|
119
|
-
|
|
120
|
-
|---|---|---|
|
|
121
|
-
| `systemPrompt` | friendly voice assistant prompt | System message prepended to all conversations |
|
|
122
|
-
| `ttsProvider` | `'server-kokoro'` | `'server-kokoro'` \| `'kokoro'` \| `'openai'` \| `'webspeech'` |
|
|
123
|
-
| `ttsVoice` | `'af_bella'` | Voice name for Kokoro / OpenAI TTS |
|
|
124
|
-
| `ttsServerUrl` | `'/api/tts'` | POST endpoint for server-side TTS (receives `{text, voice}`, returns audio) |
|
|
125
|
-
| `ttsSpeechRate` | `1` | WebSpeech rate |
|
|
126
|
-
| `ttsSpeechPitch` | `1` | WebSpeech pitch |
|
|
127
|
-
| `whisperModel` | `'onnx-community/whisper-tiny.en'` | HuggingFace model ID |
|
|
128
|
-
| `whisperDtype` | `'q8'` | `'q4'` \| `'q8'` \| `'fp32'` |
|
|
129
|
-
| `whisperDevice` | `'cpu'` | `'cpu'` \| `'webgpu'` |
|
|
130
|
-
| `kokoroDtype` | `'q8'` | Browser Kokoro dtype (when `ttsProvider: 'kokoro'`) |
|
|
131
|
-
| `kokoroBrowserDevice` | `'wasm'` | `'wasm'` \| `'webgpu'` |
|
|
132
|
-
| `modelProxyUrl` | `'/api/models/'` | Base URL for model downloads (proxies HuggingFace) |
|
|
412
|
+
Only `/api/ask` changes. Keep the same contract — receive `messages`, stream text back — and the browser code stays as is. For example, with any OpenAI-compatible server (Ollama shown):
|
|
133
413
|
|
|
134
|
-
|
|
414
|
+
```js
|
|
415
|
+
app.post('/api/ask', express.json(), async (req, res) => {
|
|
416
|
+
const upstream = await fetch('http://localhost:11434/v1/chat/completions', {
|
|
417
|
+
method: 'POST',
|
|
418
|
+
headers: { 'Content-Type': 'application/json' },
|
|
419
|
+
body: JSON.stringify({ model: 'llama3.2', messages: req.body.messages, stream: true }),
|
|
420
|
+
});
|
|
421
|
+
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
|
|
422
|
+
const decoder = new TextDecoder();
|
|
423
|
+
let buffer = '';
|
|
424
|
+
for await (const chunk of upstream.body) {
|
|
425
|
+
buffer += decoder.decode(chunk, { stream: true });
|
|
426
|
+
const lines = buffer.split('\n');
|
|
427
|
+
buffer = lines.pop();
|
|
428
|
+
for (const line of lines) {
|
|
429
|
+
if (!line.startsWith('data:') || line.includes('[DONE]')) continue;
|
|
430
|
+
const token = JSON.parse(line.slice(5)).choices?.[0]?.delta?.content;
|
|
431
|
+
if (token) res.write(token);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
res.end();
|
|
435
|
+
});
|
|
436
|
+
```
|
|
135
437
|
|
|
136
|
-
|
|
137
|
-
|---|---|---|
|
|
138
|
-
| `status` | `string` | `'idle'` \| `'listening'` \| `'transcribing'` \| `'thinking'` \| `'speaking'` |
|
|
139
|
-
| `loading` | `boolean` | `true` while Whisper + TTS are loading |
|
|
140
|
-
| `progress` | `{whisper:number, kokoro:number}` | Per-model load progress (0–1) |
|
|
141
|
-
| `error` | `string\|null` | Last error message |
|
|
142
|
-
| `transcript` | `{role,content,time}[]` | Completed conversation turns |
|
|
143
|
-
| `streamingMessage` | `string\|null` | Partial assistant response being streamed |
|
|
144
|
-
| `micEnabled` | `boolean` | Whether microphone is open |
|
|
145
|
-
| `startListening()` | `() => Promise<void>` | Open microphone and start pipeline |
|
|
146
|
-
| `stopListening()` | `() => void` | Close microphone and cancel in-progress pipeline |
|
|
147
|
-
| `speak(text)` | `(text:string) => void` | Synthesise and play text immediately |
|
|
148
|
-
| `liveAnalyser` | `AnalyserNode\|null` | Real-time frequency data for waveform UI |
|
|
149
|
-
| `devices` | `MediaDeviceInfo[]` | Available audio input devices |
|
|
150
|
-
| `selectedMicId` | `string` | Selected device ID (`''` = system default) |
|
|
151
|
-
| `setSelectedMicId` | `(id:string) => void` | Select an audio input device |
|
|
438
|
+
This is the place for retrieval over your documents, tool calls, a database lookup, or business rules — `history` has everything the user said so far. Or skip writing a brain at all and let the package do it:
|
|
152
439
|
|
|
153
|
-
|
|
440
|
+
### Shortcut: keep our chat backends, build only the UI (Level 3)
|
|
154
441
|
|
|
155
|
-
|
|
442
|
+
If you don't need custom logic, `useVoiceAssistant` loads the settings from the server, wires STT/TTS/chat accordingly, tracks what is missing, and handles `Esc`. You write only the layout:
|
|
156
443
|
|
|
157
|
-
|
|
444
|
+
```jsx
|
|
445
|
+
import { useState } from 'react';
|
|
446
|
+
import { useVoiceAssistant, AIAssistantButton, SettingsPanel } from 'tz-voice-chat';
|
|
447
|
+
import 'tz-voice-chat/style.css';
|
|
158
448
|
|
|
159
|
-
|
|
449
|
+
export default function App() {
|
|
450
|
+
// Reads /api/config, wires STT/TTS from the saved settings, picks the chat backend
|
|
451
|
+
// (server proxy or in-browser model), exposes what is still missing, and handles Esc.
|
|
452
|
+
const { chat, info, loading, missing, reload } = useVoiceAssistant();
|
|
453
|
+
const [showSettings, setShowSettings] = useState(false);
|
|
160
454
|
|
|
161
|
-
|
|
455
|
+
if (showSettings) {
|
|
456
|
+
return (
|
|
457
|
+
<div className="tz-va"> {/* the package's style scope */}
|
|
458
|
+
<SettingsPanel onSaved={reload} onClose={() => setShowSettings(false)} />
|
|
459
|
+
</div>
|
|
460
|
+
);
|
|
461
|
+
}
|
|
162
462
|
|
|
163
|
-
|
|
463
|
+
return (
|
|
464
|
+
<main style={{ maxWidth: 640, margin: '2rem auto', fontFamily: 'system-ui', color: '#e2e8f0' }}>
|
|
465
|
+
<h1>
|
|
466
|
+
My assistant <small>({chat.status})</small>{' '}
|
|
467
|
+
<button onClick={() => setShowSettings(true)}>Settings</button>
|
|
468
|
+
</h1>
|
|
469
|
+
|
|
470
|
+
{missing.length > 0 && <p style={{ color: '#fde68a' }}>Setup incomplete: {missing.map((m) => m.message).join(' ')}</p>}
|
|
471
|
+
{info && <p><small>Chat: {info.chatReady ? `${info.chatProvider} · ${info.chatModel}` : 'not configured'}</small></p>}
|
|
472
|
+
|
|
473
|
+
<AIAssistantButton
|
|
474
|
+
status={chat.status}
|
|
475
|
+
active={chat.micEnabled}
|
|
476
|
+
loading={loading}
|
|
477
|
+
analyser={chat.liveAnalyser}
|
|
478
|
+
onToggle={chat.micEnabled ? chat.stopListening : chat.startListening}
|
|
479
|
+
devices={chat.devices}
|
|
480
|
+
selectedMicId={chat.selectedMicId}
|
|
481
|
+
onDeviceChange={chat.setSelectedMicId}
|
|
482
|
+
/>
|
|
483
|
+
|
|
484
|
+
{chat.transcript.map((m) => <p key={m.id}><b>{m.role}:</b> {m.content}</p>)}
|
|
485
|
+
{chat.streamingMessage !== null && <p><b>assistant:</b> {chat.streamingMessage}…</p>}
|
|
486
|
+
{chat.error && <p style={{ color: '#fca5a5' }}>Error: {chat.error}</p>}
|
|
487
|
+
</main>
|
|
488
|
+
);
|
|
489
|
+
}
|
|
490
|
+
```
|
|
491
|
+
|
|
492
|
+
With this, the chat model (OpenAI, Claude, Ollama, in-browser…) and the speech providers are whatever the user picks on the Settings page. Wrapping `SettingsPanel` in `<div className="tz-va">` gives it the package's styles.
|
|
164
493
|
|
|
165
|
-
|
|
494
|
+
### Upgrading speech quality
|
|
495
|
+
|
|
496
|
+
Change only the speech options in `TZVoiceChat({...})` (or pick them in Settings when using `useVoiceAssistant`):
|
|
497
|
+
|
|
498
|
+
| Want | Use | Needs |
|
|
499
|
+
|---|---|---|
|
|
500
|
+
| Natural local voice | `ttsProvider: 'kokoro'`, `kokoroBrowserDevice: 'webgpu'`, `kokoroDtype: 'fp32'` | WebGPU browser; first load downloads 80–330 MB |
|
|
501
|
+
| Local voice, any browser | `ttsProvider: 'server-kokoro'` | runs in Node on your server (CPU) |
|
|
502
|
+
| Cloud voices | `ttsProvider: 'openai'` or `'elevenlabs'` | the key saved in Settings; `ttsServerUrl: '/api/tts'` |
|
|
503
|
+
| Cloud transcription | `sttProvider: 'server'` | `/api/stt` with OpenAI or ElevenLabs configured in Settings |
|
|
504
|
+
| More accurate local STT | `whisperModel: 'onnx-community/whisper-base.en'` or `small.en` | larger one-time download |
|
|
166
505
|
|
|
167
506
|
---
|
|
168
507
|
|
|
169
|
-
##
|
|
508
|
+
## Reference
|
|
170
509
|
|
|
171
|
-
|
|
172
|
-
TZVoiceChat hook
|
|
173
|
-
├── VAD (@ricky0123/vad-web, IIFE — loaded via <script> in index.html)
|
|
174
|
-
├── Whisper Worker (Web Worker — @huggingface/transformers, auto-speech-recognition)
|
|
175
|
-
├── TTS Queue (server-kokoro | kokoro | openai | webspeech)
|
|
176
|
-
└── processInput ← YOU provide this (async generator)
|
|
510
|
+
### `TZVoiceChat(options)`
|
|
177
511
|
|
|
178
|
-
|
|
179
|
-
└── 5-state animated button with waveform visualiser and mic selector
|
|
180
|
-
```
|
|
512
|
+
The pipeline hook. Returns the state and controls below. Option changes re-initialise the speech models.
|
|
181
513
|
|
|
182
|
-
|
|
514
|
+
#### TZVoiceChat options
|
|
183
515
|
|
|
184
|
-
|
|
516
|
+
| Option | Default | Description |
|
|
517
|
+
|---|---|---|
|
|
518
|
+
| `processInput` | — (**required**) | `async function*(text, history, signal)` yielding text chunks |
|
|
519
|
+
| `systemPrompt` | short spoken-style prompt | First message of every conversation |
|
|
520
|
+
| `sttProvider` | `'whisper'` | `'whisper'` (in the browser) or `'server'` (POST a WAV to `sttServerUrl`, expects `{ text }`) |
|
|
521
|
+
| `sttServerUrl` | `'/api/stt'` | Endpoint for `sttProvider: 'server'` |
|
|
522
|
+
| `whisperModel` | `'onnx-community/whisper-tiny.en'` | Hugging Face model id |
|
|
523
|
+
| `whisperDtype` | `'q8'` | `'q4'` · `'q8'` · `'fp16'` · `'fp32'` (q4/q8 are promoted to fp32 on WebGPU) |
|
|
524
|
+
| `whisperDevice` | `'wasm'` | `'wasm'` (CPU) or `'webgpu'` (`'cpu'` is accepted as an alias for `'wasm'`) |
|
|
525
|
+
| `ttsProvider` | `'server-kokoro'` | `'kokoro'` (browser) · `'server-kokoro'` · `'openai'` · `'elevenlabs'` · `'webspeech'`; every value except `kokoro` and `webspeech` posts to `ttsServerUrl` |
|
|
526
|
+
| `ttsVoice` | `'af_bella'` | Voice name / id for the provider |
|
|
527
|
+
| `ttsSpeed` | `1` | Kokoro speech-rate multiplier |
|
|
528
|
+
| `ttsServerUrl` | `'/api/tts'` | POST `{ text, voice }` → audio |
|
|
529
|
+
| `ttsSpeechRate` / `ttsSpeechPitch` | `1` / `1` | Web Speech |
|
|
530
|
+
| `kokoroDtype` | `'q8'` | Browser Kokoro precision |
|
|
531
|
+
| `kokoroBrowserDevice` | `'wasm'` | `'wasm'` or `'webgpu'` (see [Troubleshooting](#troubleshooting)) |
|
|
532
|
+
| `modelProxyUrl` | `'/api/models/'` | Base URL for model downloads |
|
|
185
533
|
|
|
186
|
-
|
|
534
|
+
#### Return value
|
|
187
535
|
|
|
188
|
-
|
|
536
|
+
| Field | Type | Description |
|
|
537
|
+
|---|---|---|
|
|
538
|
+
| `status` | `string` | `idle` · `listening` · `transcribing` · `thinking` · `speaking` |
|
|
539
|
+
| `loading` | `boolean` | Speech models still loading |
|
|
540
|
+
| `progress` | `{ whisper, kokoro }` | Load progress, 0–1 |
|
|
541
|
+
| `error` | `string \| null` | Last error (cleared by `startListening`) |
|
|
542
|
+
| `transcript` | `Array<{ id, role, content, time, timings? }>` | Completed turns. `timings`: `transcribeMs` (user), `thinkMs` and `ttsMs` (assistant) |
|
|
543
|
+
| `streamingMessage` | `string \| null` | The assistant reply while it streams |
|
|
544
|
+
| `micEnabled` | `boolean` | Microphone open |
|
|
545
|
+
| `startListening()` / `stopListening()` | `() => Promise \| void` | Open / close the mic and pipeline |
|
|
546
|
+
| `submitText(text)` | `(string) => void` | Send typed text through the pipeline |
|
|
547
|
+
| `speak(text)` | `(string) => void` | Speak text directly |
|
|
548
|
+
| `liveAnalyser` | `AnalyserNode \| null` | For waveform displays |
|
|
549
|
+
| `devices` · `selectedMicId` · `setSelectedMicId` | | Microphone list and selection |
|
|
550
|
+
|
|
551
|
+
### `useVoiceAssistant({ apiBase = '/api', systemPrompt })`
|
|
552
|
+
|
|
553
|
+
Returns `{ chat, info, config, memory, llmProgress, note, loading, missing, reload }`: `chat` is the full `TZVoiceChat` result; `info` the server's `/config`; `missing` the list of unmet required settings (`{ key, message, scope }`); `reload()` re-reads the config after settings change; `memory` is `{ browser, server }` bytes. It also stops listening on `Esc`.
|
|
554
|
+
|
|
555
|
+
### `<VoiceAssistant />`
|
|
556
|
+
|
|
557
|
+
Props: `apiBase` (`'/api'`), `title`, `showInfo` (`true`), `systemPrompt`, `className`.
|
|
558
|
+
|
|
559
|
+
### `<AIAssistantButton />`
|
|
560
|
+
|
|
561
|
+
Props: `status`, `active`, `loading`, `analyser`, `onToggle`, `devices`, `selectedMicId`, `onDeviceChange`, `inputData` / `sendData` (a send state for typed text), and theming: `accentColor`, `uiColor`, `size`, `barHue`, `barHueRange`, `barSat`, `barLit`, `barLitRange`.
|
|
562
|
+
|
|
563
|
+
### `<SettingsPanel apiBase onSaved onClose />`
|
|
564
|
+
|
|
565
|
+
The Settings page. `onSaved` receives the saved result (call `reload()` there); `onClose` shows a "Back" button.
|
|
566
|
+
|
|
567
|
+
### Server exports (`tz-voice-chat/server`)
|
|
568
|
+
|
|
569
|
+
| Export | Description |
|
|
570
|
+
|---|---|
|
|
571
|
+
| `createVoiceAssistantRouter({ settingsFile?, defaults? })` | Returns `{ router, ready, settings }`. `defaults` are initial setting values (the saved file still wins). `await ready()` pre-loads server Kokoro if selected. |
|
|
572
|
+
| `createVendorRouter()` | Express router for `/vendor/*` runtime assets (bundled in the package) |
|
|
573
|
+
| `loadKokoro()` / `generateWav(text, voice, speed)` | Server-side Kokoro |
|
|
574
|
+
|
|
575
|
+
#### HTTP endpoints (relative to where you mount the router)
|
|
576
|
+
|
|
577
|
+
| Endpoint | Description |
|
|
578
|
+
|---|---|
|
|
579
|
+
| `GET /config` | Public configuration for the client, plus `missing`, `chatReady` |
|
|
580
|
+
| `GET /settings` | Editable values; secrets are **never** returned — only `secretsSet` |
|
|
581
|
+
| `PUT /settings` | Save a partial update (or `{ settings: {...} }` from an export). Unknown or invalid keys are reported in `ignored`. `null` clears a saved value. |
|
|
582
|
+
| `GET /settings/export` | Every setting **including secrets**, as a download |
|
|
583
|
+
| `POST /chat` | Body `{ messages }` → OpenAI-style SSE stream for any configured chat provider |
|
|
584
|
+
| `POST /stt` | Body: a WAV file → `{ text }` (OpenAI or ElevenLabs) |
|
|
585
|
+
| `POST /tts` | Body `{ text, voice? }` → audio (Kokoro WAV, or MP3 from OpenAI/ElevenLabs) |
|
|
586
|
+
| `GET /models/*` | Hugging Face model-file proxy |
|
|
587
|
+
| `GET /stats` | Server memory (`rss`, `heapUsed`) |
|
|
588
|
+
|
|
589
|
+
Also: `OPENAI_BASE_URL`, `ANTHROPIC_BASE_URL`, `ELEVENLABS_BASE_URL` override the vendor endpoints (proxies, gateways, test doubles).
|
|
590
|
+
|
|
591
|
+
### Settings reference
|
|
592
|
+
|
|
593
|
+
Every setting can be set as an environment variable (initial value) or on the Settings page (saved to the settings file). Secrets are never sent to the browser.
|
|
594
|
+
|
|
595
|
+
**Chat model**
|
|
596
|
+
|
|
597
|
+
| Setting | Env variable | Default | Notes |
|
|
598
|
+
|---|---|---|---|
|
|
599
|
+
| `chatProvider` | `OPENAI_PROVIDER` | `local` | `(none)`, `local`, `openai-compatible`, `openrouter`, `openai`, `anthropic`, `huggingface` |
|
|
600
|
+
| `openrouterApiKey` | `OPENROUTER_API_KEY` | — | Secret. Get one at https://openrouter.ai/keys |
|
|
601
|
+
| `openrouterModel` | `OPENROUTER_MODEL` | `gpt-4o-mini` | e.g. openai/gpt-4o-mini, or a ":free" model |
|
|
602
|
+
| `openaiApiKey` | `OPENAI_API_KEY` | — | Secret. Used for OpenAI chat, transcription and/or TTS. Get one at https://platform.openai.com/api-keys |
|
|
603
|
+
| `openaiChatModel` | `OPENAI_CHAT_MODEL` | `gpt-4o-mini` | |
|
|
604
|
+
| `anthropicApiKey` | `ANTHROPIC_API_KEY` | — | Secret. Get one at https://console.anthropic.com/settings/keys |
|
|
605
|
+
| `anthropicModel` | `ANTHROPIC_MODEL` | `claude-haiku-5-5` | Haiku is the fastest — best for voice |
|
|
606
|
+
| `huggingfaceApiKey` | `HUGGINGFACE_API_KEY` | — | Secret. A token with read scope |
|
|
607
|
+
| `compatBaseUrl` | `OPENAI_COMPAT_BASE_URL` | `http://localhost:11434/v1` | Must serve /chat/completions. Ollama :11434, LM Studio :1234, vLLM :8000. From inside Docker use host.docker.internal instead of localhost. |
|
|
608
|
+
| `compatModel` | `OPENAI_COMPAT_MODEL` | — | Exactly as the server names it, e.g. llama3.2 or qwen2.5:7b-instruct |
|
|
609
|
+
| `compatApiKey` | `OPENAI_COMPAT_API_KEY` | — | Secret. Leave empty if the server needs no key (most local servers). |
|
|
610
|
+
| `systemPrompt` | — | — | Leave blank for the built-in short, spoken-style prompt. |
|
|
611
|
+
|
|
612
|
+
**Speech-to-text**
|
|
613
|
+
|
|
614
|
+
| Setting | Env variable | Default | Notes |
|
|
615
|
+
|---|---|---|---|
|
|
616
|
+
| `sttProvider` | `STT_PROVIDER` | `whisper` | `whisper`, `openai`, `elevenlabs` |
|
|
617
|
+
| `openaiSttModel` | `OPENAI_STT_MODEL` | `whisper-1` | Uses the OpenAI API key below |
|
|
618
|
+
| `openaiSttLanguage` | `OPENAI_STT_LANGUAGE` | — | ISO-639-1 code such as en; blank = detect automatically |
|
|
619
|
+
| `elevenlabsApiKey` | `ELEVENLABS_API_KEY` | — | Secret. Used for ElevenLabs speech-to-text and/or text-to-speech. Get one at https://elevenlabs.io/app/settings/api-keys |
|
|
620
|
+
| `elevenlabsSttModel` | `ELEVENLABS_STT_MODEL` | `scribe_v2` | |
|
|
621
|
+
| `elevenlabsLanguage` | `ELEVENLABS_STT_LANGUAGE` | — | ISO code such as en or de; blank = detect automatically |
|
|
622
|
+
| `whisperModel` | `WHISPER_MODEL` | `onnx-community/whisper-small.en` | `onnx-community/whisper-tiny.en`, `onnx-community/whisper-base.en`, `onnx-community/whisper-small.en` |
|
|
623
|
+
| `whisperDtype` | `WHISPER_DTYPE` | `fp32` | `q8`, `q4`, `fp16`, `fp32` |
|
|
624
|
+
| `whisperDevice` | `WHISPER_DEVICE` | `webgpu` | `wasm`, `webgpu` |
|
|
625
|
+
|
|
626
|
+
**Text-to-speech**
|
|
627
|
+
|
|
628
|
+
| Setting | Env variable | Default | Notes |
|
|
629
|
+
|---|---|---|---|
|
|
630
|
+
| `ttsProvider` | `TTS_PROVIDER` | `kokoro` | `kokoro`, `server-kokoro`, `webspeech`, `openai`, `elevenlabs` |
|
|
631
|
+
| `kokoroVoice` | `KOKORO_VOICE` | `af_bella` | e.g. af_bella, af_sarah, am_adam |
|
|
632
|
+
| `kokoroSpeed` | `KOKORO_SPEED` | `1` | 1 = normal; 1.1–1.2 often sounds more natural |
|
|
633
|
+
| `kokoroDtype` | `KOKORO_DTYPE` | `fp32` | `q8`, `q4`, `q4f16`, `fp16`, `fp32`. q4/q8 are promoted to fp32 on WebGPU |
|
|
634
|
+
| `kokoroBrowserDevice` | `KOKORO_BROWSER_DEVICE` | `webgpu` | `wasm`, `webgpu` |
|
|
635
|
+
| `kokoroDevice` | `KOKORO_DEVICE` | `cpu` | `cpu` |
|
|
636
|
+
| `openaiTtsModel` | `OPENAI_TTS_MODEL` | `tts-1` | |
|
|
637
|
+
| `openaiTtsVoice` | `OPENAI_TTS_VOICE` | `alloy` | |
|
|
638
|
+
| `elevenlabsVoiceId` | `ELEVENLABS_VOICE_ID` | `21m00Tcm4TlvDq8ikWAM` | Default is the premade "Rachel" voice. Copy another voice's ID from your ElevenLabs voice library. |
|
|
639
|
+
| `elevenlabsTtsModel` | `ELEVENLABS_TTS_MODEL` | `eleven_flash_v2_5` | Flash is the lowest latency — best for voice chat |
|
|
640
|
+
| `webSpeechVoice` | `WEBSPEECH_VOICE` | — | Exact voice name; blank = browser default |
|
|
641
|
+
| `webSpeechRate` | `WEBSPEECH_RATE` | `1` | 0.1 – 10 |
|
|
642
|
+
| `webSpeechPitch` | `WEBSPEECH_PITCH` | `1` | 0 – 2 |
|
|
189
643
|
|
|
190
|
-
|
|
191
|
-
import { VoiceAssistant } from 'tz-voice-chat';
|
|
192
|
-
import 'tz-voice-chat/style.css';
|
|
644
|
+
---
|
|
193
645
|
|
|
194
|
-
|
|
195
|
-
```
|
|
646
|
+
## Troubleshooting
|
|
196
647
|
|
|
197
|
-
|
|
648
|
+
| Symptom | Cause and fix |
|
|
649
|
+
|---|---|
|
|
650
|
+
| **Microphone never starts**, `window.vad` is undefined | Your page is missing the `ort` / VAD `<script>` tags or the import map ([step 3](#3-the-page--indexhtml)). Microphone access also needs `https://` or `localhost`. |
|
|
651
|
+
| **`Unsupported device: "cpu"`** | The browser build accepts only `wasm` or `webgpu`. Use `whisperDevice: 'wasm'` (`'cpu'` is auto-mapped by this package). |
|
|
652
|
+
| **Kokoro never finishes loading / is very slow** | The model is 80–330 MB depending on precision, and it downloads through your server — a slow link means a long first load. Browser Kokoro on `wasm` runs on the main thread and can be very slow; prefer `webgpu`, `server-kokoro`, or the Web Speech API. |
|
|
653
|
+
| **Chat says "not configured"** | Open Settings and pick a provider. If the provider needs a key, the notice names it. |
|
|
654
|
+
| **OpenAI-compatible server unreachable** | The *tz-voice-chat server* makes the request, so the URL must be reachable from there. Inside Docker, use `host.docker.internal` instead of `localhost`. |
|
|
655
|
+
| **`app.get('*')` throws in your own server** | You are on Express 5, which dropped bare `*` routes. Use a final `app.use(...)` fallback as in [step 2](#2-the-server--serverjs). The package's own router works with either version. |
|
|
656
|
+
| **Vite dev: "Model load failed"** | Add `optimizeDeps: { exclude: ['tz-voice-chat'] }` ([step 4](#4-vite--viteconfigjs)). In dev, a package linked with a symlink from outside the project root is also blocked by Vite — install a real copy (`npm pack` + install the tarball) to test. |
|
|
657
|
+
| **`ttsProvider: 'server-kokoro'` says it needs `kokoro-js`** | Server-side Kokoro is an optional extra, so installing tz-voice-chat stays light and free of native code: run `npm install kokoro-js`. Its dependency `onnxruntime-node` downloads binaries at install time; on Linux x64 use `ONNXRUNTIME_NODE_INSTALL_CUDA=skip npm install kokoro-js` (CPU inference is unaffected). Or use Kokoro in the browser, OpenAI, ElevenLabs or Web Speech. |
|
|
658
|
+
| **Settings file is lost in Docker** | It lives in the container's home directory. Mount a volume at `~/.tz-voice-chat`, or pass `settingsFile`. |
|
|
659
|
+
| **Port already in use** | `--port` (CLI) or `PORT` (your server). |
|
|
198
660
|
|
|
199
|
-
|
|
661
|
+
## Security notes
|
|
200
662
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
663
|
+
- Keep the server on loopback (the CLI default) or behind your own authentication: `/settings` can read and replace API keys, `/chat` spends your provider credits, and the OpenAI-compatible provider makes requests to a URL set in Settings.
|
|
664
|
+
- The settings file is written with owner-only permissions (`0600`).
|
|
665
|
+
- Exported settings contain secrets. Treat them like a password file.
|
|
204
666
|
|
|
205
|
-
|
|
206
|
-
const { router, ready } = createVoiceAssistantRouter(); // options default to env vars
|
|
207
|
-
app.use('/api', router); // /config /stats /chat /tts /models/*
|
|
208
|
-
ready().then(() => app.listen(3000));
|
|
209
|
-
```
|
|
667
|
+
## License
|
|
210
668
|
|
|
211
|
-
|
|
669
|
+
MIT
|