Repository navigation
Expand file tree
/
Copy pathstart.ps1
More file actions
350 lines (306 loc) · 13 KB
/
Copy pathstart.ps1
File metadata and controls
350 lines (306 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# KNIGHTBOT - CANONICAL STARTUP SCRIPT (Windows / PowerShell)
# Notes:
# - Uses `docker compose` when available (Docker Desktop), falls back to legacy `docker-compose`.
# - If ffmpeg is missing, STT + Pipecat are skipped (chat + TTS still work).
$ErrorActionPreference = "Stop"
$K = "F:\KnightBot"
$VenvActivate = "$K\venv\Scripts\Activate.ps1"
$PythonExe = "$K\venv\Scripts\python.exe"
function Invoke-DockerCompose {
param(
[Parameter(Mandatory = $true)][string[]]$Args
)
# Prefer plugin: `docker compose ...`
try {
$null = docker compose version 2>$null
& docker compose @Args
return $LASTEXITCODE
}
catch {
# Fall back to legacy binary: `docker-compose ...`
& docker-compose @Args
return $LASTEXITCODE
}
}
function Test-PortInUse {
param([int]$Port)
try {
$conn = Get-NetTCPConnection -State Listen -LocalPort $Port -ErrorAction SilentlyContinue
return $null -ne $conn
}
catch {
return $false
}
}
function Start-KnightService {
param(
[string]$Name,
[string]$Command,
[int]$DelaySeconds = 2
)
Write-Host ("Starting " + $Name + "...") -ForegroundColor Yellow
$wrappedCommand = '$ErrorActionPreference="Stop"; $env:PYTHONIOENCODING="utf-8"; $env:PYTHONUTF8="1"; ' + $Command
$proc = Start-Process powershell -ArgumentList "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", $wrappedCommand -WindowStyle Hidden -PassThru
Start-Sleep -Seconds $DelaySeconds
Write-Host (" OK: " + $Name + " launch command issued (PID " + $proc.Id + ")") -ForegroundColor Green
}
function Get-DotEnvValue {
param(
[Parameter(Mandatory = $true)][string]$Path,
[Parameter(Mandatory = $true)][string]$Key,
[Parameter(Mandatory = $true)][string]$Default
)
if (-not (Test-Path $Path)) { return $Default }
try {
$line = Get-Content $Path -ErrorAction Stop |
Where-Object { $_ -match ("^\s*" + [regex]::Escape($Key) + "\s*=") } |
Select-Object -Last 1
if (-not $line) { return $Default }
$value = ($line -split "=", 2)[1].Trim()
if (($value.StartsWith("'") -and $value.EndsWith("'")) -or ($value.StartsWith('"') -and $value.EndsWith('"'))) {
$value = $value.Substring(1, $value.Length - 2)
}
if ([string]::IsNullOrWhiteSpace($value)) { return $Default }
return $value
}
catch {
return $Default
}
}
function Stop-KnightCoreProcesses {
param([switch]$Quiet)
try {
$targets = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Where-Object {
$_.Name -match '^python(w)?\.exe$' -and
$_.CommandLine -and
$_.CommandLine -match 'scripts[\\/]knight_core\.py'
}
}
catch {
$targets = @()
}
if (-not $targets -or $targets.Count -eq 0) {
if (-not $Quiet) {
Write-Host "No existing Knight Core python processes found." -ForegroundColor DarkGray
}
return 0
}
$stopped = 0
foreach ($t in $targets) {
try {
Stop-Process -Id $t.ProcessId -Force -ErrorAction Stop
$stopped++
Write-Host (" OK: stopped stale Knight Core PID " + $t.ProcessId) -ForegroundColor DarkGray
}
catch {
Write-Host (" WARN: failed to stop stale Knight Core PID " + $t.ProcessId + ": " + $_.Exception.Message) -ForegroundColor Yellow
}
}
Start-Sleep -Milliseconds 800
return $stopped
}
try {
if ($Host -and $Host.UI -and $Host.UI.RawUI) {
Clear-Host
}
}
catch {
# Non-interactive shells can throw on RawUI operations.
}
Write-Host ""
Write-Host "KnightBot startup (canonical)" -ForegroundColor Cyan
Write-Host ""
if (-not (Test-Path $PythonExe)) {
Write-Host ("ERROR: Python venv not found at " + $PythonExe) -ForegroundColor Red
Write-Host "Run: .\install.ps1" -ForegroundColor Yellow
exit 1
}
# Ensure we run from the repo root regardless of where the script was invoked from.
Set-Location $K
$dotEnvPath = Join-Path $K ".env"
$lmReqTimeout = Get-DotEnvValue -Path $dotEnvPath -Key "LM_REQUEST_TIMEOUT_S" -Default "180"
$lmFallbackModel = Get-DotEnvValue -Path $dotEnvPath -Key "LM_FALLBACK_MODEL_ID" -Default "phi-4-14b-instruct-sft"
$lmForceNonStream = Get-DotEnvValue -Path $dotEnvPath -Key "LM_FORCE_NONSTREAM_MODELS" -Default "qwen3-vl-32b-instruct-heretic-v2-i1,qwen3-vl-32b-thinking-heretic-v2-i1"
Write-Host ("LLM Runtime: timeout=" + $lmReqTimeout + "s") -ForegroundColor Cyan
Write-Host ("LLM Runtime: fallback model=" + $lmFallbackModel) -ForegroundColor Cyan
Write-Host ("LLM Runtime: forced non-stream models=" + $lmForceNonStream) -ForegroundColor Cyan
# Stage LiveKit config to a C: path for Docker Desktop mounts.
# Some Docker Desktop setups cannot bind-mount directly from external drives.
$dockerConfigRoot = Join-Path $env:USERPROFILE ".knightbot\config"
$dockerLiveKitConfig = Join-Path $dockerConfigRoot "livekit.yaml"
New-Item -ItemType Directory -Path $dockerConfigRoot -Force | Out-Null
Copy-Item -Path (Join-Path $K "config\livekit.yaml") -Destination $dockerLiveKitConfig -Force
$env:LIVEKIT_CONFIG_PATH = ($dockerLiveKitConfig -replace "\\", "/")
$skipSTT = $false
$skipSTTReason = ""
$ffmpeg = Get-Command ffmpeg -ErrorAction SilentlyContinue
if (-not $ffmpeg) {
$skipSTT = $true
$skipSTTReason = "ffmpeg"
Write-Host "WARNING: ffmpeg not found in PATH. STT will be skipped (voice input disabled)." -ForegroundColor Yellow
Write-Host " Install ffmpeg, then restart KnightBot to enable STT." -ForegroundColor DarkGray
}
function Test-PythonModule {
param([Parameter(Mandatory = $true)][string]$Module)
try {
& $PythonExe -c "import importlib; importlib.import_module('$Module')" 2>$null
return $LASTEXITCODE -eq 0
}
catch {
return $false
}
}
# Dependency checks: if modules are missing, the STT/TTS services will crash immediately.
$skipTTS = $false
$sttMissing = @()
$ttsMissing = @()
if (-not (Test-PythonModule -Module "torch")) {
$sttMissing += "torch"
$ttsMissing += "torch"
}
if (-not (Test-PythonModule -Module "torchaudio")) {
$ttsMissing += "torchaudio"
}
if (-not (Test-PythonModule -Module "soundfile")) {
$ttsMissing += "soundfile"
}
# NOTE: Importing `nemo.collections.asr` can pull in optional dependency chains (metrics/diarization/etc.)
# and is heavier than what we actually need for Parakeet.
#
# To avoid false negatives from import-time side effects, prefer a file-existence check for NeMo ASR.
$asrModelFile = Join-Path $K "venv\Lib\site-packages\nemo\collections\asr\models\asr_model.py"
$sttOk = (Test-Path $asrModelFile)
if (-not $sttOk) {
# Fallback to an actual import check.
$sttOk = (Test-PythonModule -Module "nemo.collections.asr.models.asr_model")
}
if (-not $sttOk) {
$sttMissing += "nemo-toolkit (NeMo ASR not found)"
}
if (-not (Test-PythonModule -Module "pydub")) {
# Not strictly required for basic synthesis, but used by voice upload processing.
$ttsMissing += "pydub"
}
if (-not (Test-PythonModule -Module "PIL")) {
$ttsMissing += "Pillow (PIL)"
}
if (-not (Test-PythonModule -Module "transformers")) {
$ttsMissing += "transformers"
}
if ($sttMissing.Count -gt 0) {
$skipSTT = $true
if (-not $skipSTTReason) { $skipSTTReason = "deps" }
Write-Host ("WARNING: STT dependencies missing: " + ($sttMissing -join ", ") + ". STT will be skipped.") -ForegroundColor Yellow
Write-Host " Fix by running .\install.ps1 (or pip install -r requirements.txt)" -ForegroundColor DarkGray
}
if ($ttsMissing.Count -gt 0) {
$skipTTS = $true
Write-Host ("WARNING: TTS dependencies missing: " + ($ttsMissing -join ", ") + ". TTS will be skipped.") -ForegroundColor Yellow
Write-Host " Fix by running .\install.ps1 (or pip install -r requirements.txt)" -ForegroundColor DarkGray
}
# Ports we require to be free before launching
# STT: 8071 = Faster Whisper (preferred), 8070 = Parakeet (fallback)
$requiredPorts = @(3000, 8050, 8100, 7880, 6333)
if (-not $skipTTS) { $requiredPorts += 8060 }
if (-not $skipSTT) { $requiredPorts += @(8070, 8071) }
# Enforce a single Knight Core owner before port checks.
$stoppedKnightCore = Stop-KnightCoreProcesses -Quiet
if ($stoppedKnightCore -gt 0) {
Write-Host ("Stopped " + $stoppedKnightCore + " existing Knight Core process(es) before launch.") -ForegroundColor Cyan
}
$occupied = @($requiredPorts | Where-Object { Test-PortInUse -Port $_ })
if ($occupied.Count -gt 0) {
Write-Host ("ERROR: Required ports already in use: " + ($occupied -join ", ")) -ForegroundColor Red
Write-Host "Run: .\stop.ps1, then retry." -ForegroundColor Yellow
exit 1
}
try {
docker info | Out-Null
}
catch {
Write-Host "ERROR: Docker is not running. Start Docker Desktop and retry." -ForegroundColor Red
exit 1
}
Write-Host "Starting Docker services (LiveKit, Qdrant, Mem0)..." -ForegroundColor Yellow
Invoke-DockerCompose -Args @("up", "-d", "--remove-orphans") | Out-Null
if ($LASTEXITCODE -ne 0) {
Write-Host "ERROR: Docker compose startup failed." -ForegroundColor Red
exit 1
}
Start-Sleep -Seconds 6
Write-Host "OK: Docker services started" -ForegroundColor Green
# Check LM Studio (non-fatal)
$lmStudioUrl = if ($env:LM_STUDIO_URL -and $env:LM_STUDIO_URL.Trim()) {
$env:LM_STUDIO_URL.Trim().TrimEnd("/")
} else {
"http://192.168.68.111:1234/v1"
}
if (-not $env:LM_STUDIO_URL) {
$env:LM_STUDIO_URL = $lmStudioUrl
}
$lmStudioModelsUrl = "$lmStudioUrl/models"
try {
$null = Invoke-RestMethod -Uri $lmStudioModelsUrl -Method Get -TimeoutSec 3
Write-Host ("OK: LM Studio API reachable at " + $lmStudioModelsUrl) -ForegroundColor Green
}
catch {
Write-Host ("WARNING: LM Studio not reachable at " + $lmStudioModelsUrl + ". Chat will fail until model server is running.") -ForegroundColor Yellow
}
# Start services
Start-KnightService -Name "Knight Core (8100)" -Command "& '$VenvActivate'; Set-Location '$K'; & '$PythonExe' '$K\scripts\knight_core.py'" -DelaySeconds 3
# Check for Faster Whisper (preferred) vs Parakeet (fallback)
$skipFasterWhisper = $false
if (-not (Test-PythonModule -Module "faster_whisper")) {
Write-Host "NOTE: Faster Whisper not found - will use Parakeet fallback" -ForegroundColor Cyan
$skipFasterWhisper = $true
}
if (-not $skipSTT) {
# Start Faster Whisper (port 8071) - preferred STT
if (-not $skipFasterWhisper) {
Start-KnightService -Name "Faster Whisper STT (8071)" -Command "& '$VenvActivate'; Set-Location '$K'; $env:KB_FASTER_WHISPER_DEVICE='cuda'; $env:KB_FASTER_WHISPER_COMPUTE='float16'; & '$PythonExe' '$K\\faster_whisper\\server.py'" -DelaySeconds 3
}
# Start Parakeet (port 8070) - fallback STT
Start-KnightService -Name "Parakeet STT (8070)" -Command "& '$VenvActivate'; Set-Location '$K'; & '$PythonExe' '$K\\parakeet\\server.py'" -DelaySeconds 3
} else {
Write-Host "Skipping STT (disabled)" -ForegroundColor DarkGray
}
if (-not $skipTTS) {
Start-KnightService -Name "Chatterbox TTS (8060)" -Command "& '$VenvActivate'; Set-Location '$K'; $env:KB_CHATTERBOX_ATTN_IMPL='sdpa'; $env:KB_TTS_MAX_NEW_TOKENS='520'; $env:KB_TTS_MIN_NEW_TOKENS='180'; $env:KB_TTS_BASE_NEW_TOKENS='120'; $env:KB_TTS_TOKENS_PER_CHAR='0.45'; $env:KB_TTS_SDP_FLASH='1'; $env:KB_TTS_SDP_MEM_EFFICIENT='1'; $env:KB_TTS_SDP_MATH='1'; $env:KB_TTS_FORCE_ALIGNMENT_ATTN='0'; & '$PythonExe' '$K\\chatterbox\\server.py'" -DelaySeconds 3
} else {
Write-Host "Skipping TTS (missing python deps)" -ForegroundColor DarkGray
}
if (-not $skipSTT) {
Start-KnightService -Name "Pipecat (LiveKit pipeline)" -Command "& '$VenvActivate'; Set-Location '$K'; & '$PythonExe' '$K\pipecat\pipeline.py'" -DelaySeconds 2
} else {
Write-Host "Skipping Pipecat (depends on STT)" -ForegroundColor DarkGray
}
Start-KnightService -Name "Frontend (3000)" -Command "Set-Location '$K\frontend'; npm run dev" -DelaySeconds 2
Write-Host ""
Write-Host "KnightBot launch sequence complete" -ForegroundColor Green
Write-Host "Frontend: http://localhost:3000" -ForegroundColor White
Write-Host "Knight API: http://localhost:8100" -ForegroundColor White
if (-not $skipSTT) {
if (-not $skipFasterWhisper) {
Write-Host "STT: Faster Whisper (8071) + Parakeet (8070)" -ForegroundColor White
} else {
Write-Host "STT: Parakeet (8070)" -ForegroundColor White
}
} else {
if ($skipSTTReason -eq "ffmpeg") {
Write-Host "STT: disabled (install ffmpeg)" -ForegroundColor DarkGray
} else {
Write-Host "STT: disabled (missing python deps)" -ForegroundColor DarkGray
}
}
if (-not $skipTTS) {
Write-Host "TTS: Chatterbox Turbo (8060)" -ForegroundColor White
} else {
Write-Host "TTS: disabled (missing python deps)" -ForegroundColor DarkGray
}
Write-Host "LiveKit: ws://localhost:7880" -ForegroundColor White
try {
Start-Process "http://localhost:3000" | Out-Null
}
catch {
Write-Host "NOTE: Could not auto-open browser. Frontend is still at http://localhost:3000" -ForegroundColor DarkGray
}