-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathworker.py
More file actions
1872 lines (1604 loc) · 77.6 KB
/
worker.py
File metadata and controls
1872 lines (1604 loc) · 77.6 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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""MiniCPMO45 推理 Worker
每个 Worker 占用一张 GPU,持有一个 UnifiedProcessor 实例,
提供 Chat (HTTP) / Streaming (WebSocket) / Duplex (WebSocket) 三种推理 API。
启动方式:
cd /user/sunweiyue/lib/swy-dev/minicpmo45_service
CUDA_VISIBLE_DEVICES=0 PYTHONPATH=. .venv/base/bin/python worker.py \\
--port 10031 \\
--model-path /path/to/base_model \\
--pt-path /path/to/custom.pt \\
--ref-audio-path /path/to/ref.wav
"""
import gc
import re
import json
import time
import uuid
import asyncio
import argparse
import logging
import base64
import threading
from enum import Enum
from typing import Optional, List, Dict, Any, Iterator
from datetime import datetime
import numpy as np
import torch
import uvicorn
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect
from fastapi.responses import StreamingResponse as FastAPIStreamingResponse
from pydantic import BaseModel, Field
from core.schemas.common import Message, Role, TextContent, AudioContent, ImageContent, VideoContent, ContentItem
from core.schemas.chat import ChatRequest, ChatResponse
from core.schemas.streaming import (
StreamingRequest, StreamingChunk, StreamingResponse, StreamingConfig,
)
from core.schemas.duplex import (
DuplexConfig, DuplexGenerateResult, DuplexPrefillRequest,
)
from session_recorder import DuplexSessionRecorder, TurnBasedSessionRecorder, generate_session_id
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
)
logger = logging.getLogger("worker")
# ============ Worker 状态 ============
class WorkerStatus(str, Enum):
"""Worker 状态"""
LOADING = "loading" # 正在加载模型
IDLE = "idle" # 空闲(可接受新请求)
BUSY_CHAT = "busy_chat" # 正在处理 Chat 请求
BUSY_HALF_DUPLEX = "busy_half_duplex" # 正在处理 Half-Duplex 请求
DUPLEX_ACTIVE = "duplex_active" # Duplex 活跃中
DUPLEX_PAUSED = "duplex_paused" # Duplex 暂停中
ERROR = "error" # 异常状态
class WorkerState(BaseModel):
"""Worker 运行时状态"""
status: WorkerStatus = WorkerStatus.LOADING
current_session_id: Optional[str] = None
duplex_pause_time: Optional[float] = None # Duplex 暂停的时间戳
total_requests: int = 0
total_inference_time_ms: float = 0.0
last_activity: Optional[str] = None
@property
def is_idle(self) -> bool:
return self.status == WorkerStatus.IDLE
@property
def is_busy(self) -> bool:
return self.status in (
WorkerStatus.BUSY_CHAT,
WorkerStatus.BUSY_HALF_DUPLEX,
WorkerStatus.DUPLEX_ACTIVE,
WorkerStatus.DUPLEX_PAUSED,
)
# ============ 请求/响应模型 ============
class WorkerHealthResponse(BaseModel):
"""健康检查响应"""
status: str
worker_status: WorkerStatus
gpu_id: int
model_loaded: bool
current_session_id: Optional[str] = None
total_requests: int = 0
avg_inference_time_ms: float = 0.0
kv_cache_length: int = 0 # 当前 LLM KV cache token 总数
class StreamingWsMessage(BaseModel):
"""Streaming WebSocket 消息(Client → Server)"""
type: str # "prefill" | "generate" | "complete_turn" | "close"
# prefill 参数
messages: Optional[List[Dict[str, Any]]] = None
session_id: Optional[str] = None
is_last_chunk: bool = True
# generate 参数
generate_audio: bool = True
max_new_tokens: int = 256
# complete_turn 参数
output_audio_path: Optional[str] = None
class DuplexWsMessage(BaseModel):
"""Duplex WebSocket 消息(Client → Server)"""
type: str # "prepare" | "audio_chunk" | "pause" | "resume" | "stop"
# prepare 参数
system_prompt: Optional[str] = None
ref_audio_path: Optional[str] = None
config: Optional[Dict[str, Any]] = None
# audio_chunk 参数
audio_base64: Optional[str] = None
frame_base64_list: Optional[List[str]] = None
force_listen: Optional[bool] = None # Force Listen 开关(per-chunk)
# ============ Worker 主类 ============
class MiniCPMOWorker:
"""MiniCPMO45 推理 Worker
持有一个 UnifiedProcessor 实例,提供三种推理模式。
"""
def __init__(
self,
model_path: str,
gpu_id: int,
pt_path: Optional[str] = None,
ref_audio_path: Optional[str] = None,
duplex_pause_timeout: float = 60.0,
compile: bool = False,
chat_vocoder: str = "token2wav",
attn_implementation: str = "auto",
):
self.model_path = model_path
self.gpu_id = gpu_id
self.pt_path = pt_path
self.ref_audio_path = ref_audio_path
self.duplex_pause_timeout = duplex_pause_timeout
self.compile = compile
self.chat_vocoder = chat_vocoder
self.attn_implementation = attn_implementation
self.state = WorkerState()
self.processor = None
# Duplex 暂停超时监控 task
self._duplex_timeout_task: Optional[asyncio.Task] = None
def load_model(self) -> None:
"""加载模型(同步,在启动时调用)"""
self.state.status = WorkerStatus.LOADING
logger.info(f"[GPU {self.gpu_id}] Loading model from {self.model_path}...")
from core.processors.unified import UnifiedProcessor
self.processor = UnifiedProcessor(
model_path=self.model_path,
pt_path=self.pt_path,
ref_audio_path=self.ref_audio_path,
compile=self.compile,
chat_vocoder=self.chat_vocoder,
attn_implementation=self.attn_implementation,
)
gc.collect()
torch.cuda.empty_cache()
self.state.status = WorkerStatus.IDLE
logger.info(f"[GPU {self.gpu_id}] Model loaded successfully")
# 检查模型各组件的 device 分布
self._log_device_map()
def _log_device_map(self) -> None:
"""打印模型各关键组件的 device,用于确认是否全部在 GPU 上"""
if self.processor is None:
return
model = self.processor.model
checks: list[tuple[str, str]] = []
# LLM
try:
p = next(model.llm.parameters())
checks.append(("LLM", str(p.device)))
except Exception:
checks.append(("LLM", "N/A"))
# Vision encoder
try:
p = next(model.vpm.parameters())
checks.append(("Vision (vpm)", str(p.device)))
except Exception:
checks.append(("Vision (vpm)", "N/A"))
# Whisper / audio encoder
for name in ("apm", "audio_encoder", "whisper"):
if hasattr(model, name):
try:
p = next(getattr(model, name).parameters())
checks.append((f"Audio ({name})", str(p.device)))
except Exception:
checks.append((f"Audio ({name})", "no params"))
break
# TTS 模块
if hasattr(model, "tts"):
tts = model.tts
# TTS 主体
try:
p = next(tts.parameters())
checks.append(("TTS (main)", str(p.device)))
except Exception:
checks.append(("TTS (main)", "N/A"))
# audio_tokenizer (Token2Wav 关键组件)
if hasattr(tts, "audio_tokenizer"):
tok = tts.audio_tokenizer
try:
p = next(tok.parameters())
checks.append(("TTS audio_tokenizer", str(p.device)))
except Exception:
checks.append(("TTS audio_tokenizer", "no params"))
# hift (vocoder in Token2Wav)
if hasattr(tok, "hift"):
try:
p = next(tok.hift.parameters())
checks.append(("TTS hift (vocoder)", str(p.device)))
except Exception:
checks.append(("TTS hift (vocoder)", "no params"))
# CosyVoice2 / flow model
for attr_name in ("cosyvoice", "cosyvoice2", "flow"):
if hasattr(tts, attr_name):
try:
p = next(getattr(tts, attr_name).parameters())
checks.append((f"TTS {attr_name}", str(p.device)))
except Exception:
checks.append((f"TTS {attr_name}", "no params"))
# Duplex decoder
if hasattr(model, "duplex") and model.duplex is not None:
try:
p = next(model.duplex.decoder.parameters())
checks.append(("Duplex decoder", str(p.device)))
except Exception:
checks.append(("Duplex decoder", "N/A"))
logger.info(f"[GPU {self.gpu_id}] === Device Map ===")
for name, device in checks:
on_gpu = "cuda" in device
marker = "✓" if on_gpu else "⚠ CPU!"
logger.info(f"[GPU {self.gpu_id}] {marker} {name}: {device}")
# ========== Chat ==========
def chat(self, request: ChatRequest) -> ChatResponse:
"""执行 Chat 推理(无状态)
Chat 模式下 cached_tokens 始终为 0(每次从头 prefill)。
token_stats 中的 input_tokens/generated_tokens 从模型输出精确获取:
- input_tokens: tokenizer 级别(含 audio/image 占位符,不含 embedding 展开)
- generated_tokens: LLM 实际生成的 token 数
"""
if not self.state.is_idle:
raise RuntimeError(f"Worker not idle, status: {self.state.status}")
self.state.status = WorkerStatus.BUSY_CHAT
self.state.last_activity = datetime.now().isoformat()
start_time = time.perf_counter()
try:
chat_view = self.processor.set_chat_mode()
response = chat_view.chat(
request,
max_new_tokens=request.generation.max_new_tokens,
do_sample=request.generation.do_sample,
generate_audio=request.tts.enabled if request.tts else False,
)
elapsed_ms = (time.perf_counter() - start_time) * 1000
self.state.total_requests += 1
self.state.total_inference_time_ms += elapsed_ms
# Chat token 统计已在 ChatView._chat_impl() 中从模型输出精确获取
# input_tokens: tokenizer 级别(含 audio/image 占位符)
# generated_tokens: LLM 实际生成的 token 数
ts = response.token_stats or {}
logger.info(
f"[GPU {self.gpu_id}] Chat completed: "
f"{len(response.text)} chars, {elapsed_ms:.0f}ms, "
f"tokens: in={ts.get('input_tokens', '?')} "
f"gen={ts.get('generated_tokens', '?')} "
f"total={ts.get('total_tokens', '?')}"
)
return response
finally:
# Chat 是无状态的,完成后清除 KV Cache 映射
self.state.status = WorkerStatus.IDLE
self.state.current_session_id = None
# ========== Chat prefill + generate(KV cache 模式) ==========
def chat_prefill(
self,
session_id: str,
msgs,
omni_mode: bool = False,
max_slice_nums=None,
use_tts_template: bool = False,
enable_thinking: bool = False,
) -> str:
"""Chat prefill:一次性 prefill 所有消息到 KV cache"""
chat_view = self.processor.set_chat_mode()
prompt = chat_view.prefill(
session_id=session_id,
msgs=msgs,
omni_mode=omni_mode,
max_slice_nums=max_slice_nums,
use_tts_template=use_tts_template,
enable_thinking=enable_thinking,
)
return prompt
def chat_non_streaming_generate(
self,
session_id: str,
max_new_tokens: int = 256,
do_sample: bool = True,
generate_audio: bool = False,
use_tts_template: bool = True,
enable_thinking: bool = False,
tts_ref_audio=None,
tts_sampling_params=None,
length_penalty: float = 1.1,
):
"""Chat 非流式 generate:基于 KV cache 做 HF generate + 可选 TTS"""
chat_view = self.processor.set_chat_mode()
result = chat_view.generate(
session_id=session_id,
max_new_tokens=max_new_tokens,
do_sample=do_sample,
generate_audio=generate_audio,
use_tts_template=use_tts_template,
enable_thinking=enable_thinking,
tts_ref_audio=tts_ref_audio,
tts_sampling_params=tts_sampling_params,
length_penalty=length_penalty,
)
return result
def chat_streaming_generate(
self,
session_id: str,
generate_audio: bool = True,
max_new_tokens: int = 256,
length_penalty: float = 1.1,
) -> "Iterator[StreamingChunk]":
"""Chat 流式 generate:基于 KV cache 做 streaming_generate"""
chat_view = self.processor.set_chat_mode()
yield from chat_view.streaming_generate(
session_id=session_id,
generate_audio=generate_audio,
max_new_tokens=max_new_tokens,
length_penalty=length_penalty,
)
# ========== Half-Duplex ==========
def half_duplex_prefill(self, request: StreamingRequest) -> str:
"""Half-Duplex 预填充"""
half_duplex_view = self.processor.set_half_duplex_mode()
prompt = half_duplex_view.prefill(request)
return prompt
def half_duplex_init_tts(self, ref_audio_data: Optional[np.ndarray] = None) -> None:
"""初始化 Half-Duplex TTS(在 generate 前调用,如需生成音频)
Args:
ref_audio_data: 前端上传的 ref audio ndarray (16kHz mono float32)。
若提供则使用此数据,否则使用 worker 默认的 ref_audio_path。
"""
half_duplex_view = self.processor.set_half_duplex_mode()
if ref_audio_data is not None:
half_duplex_view.init_ref_audio_from_data(ref_audio_data)
else:
half_duplex_view.init_ref_audio(self.ref_audio_path)
def half_duplex_generate(
self,
session_id: str,
generate_audio: bool = True,
max_new_tokens: int = 256,
length_penalty: float = 1.1,
) -> Iterator[StreamingChunk]:
"""Half-Duplex 生成(yield StreamingChunk)"""
half_duplex_view = self.processor.set_half_duplex_mode()
yield from half_duplex_view.generate(
session_id=session_id,
generate_audio=generate_audio,
max_new_tokens=max_new_tokens,
length_penalty=length_penalty,
)
def half_duplex_complete_turn(
self,
session_id: str,
messages: List[Message],
generate_audio: bool = True,
max_new_tokens: int = 256,
output_audio_path: Optional[str] = None,
length_penalty: float = 1.1,
) -> StreamingResponse:
"""Half-Duplex 完成一轮(便捷方法)"""
half_duplex_view = self.processor.set_half_duplex_mode()
return half_duplex_view.complete_turn(
session_id=session_id,
messages=messages,
generate_audio=generate_audio,
max_new_tokens=max_new_tokens,
output_audio_path=output_audio_path,
length_penalty=length_penalty,
)
def reset_half_duplex_session(self) -> None:
"""重置 Half-Duplex 模型 session(清除 KV cache)"""
half_duplex_view = self.processor.set_half_duplex_mode()
half_duplex_view._model.reset_session(reset_token2wav_cache=False)
logger.info(f"[GPU {self.gpu_id}] Half-Duplex model session reset (KV cache cleared)")
# ========== Duplex ==========
def duplex_prepare(
self,
system_prompt_text: Optional[str] = None,
ref_audio_path: Optional[str] = None,
prompt_wav_path: Optional[str] = None,
) -> str:
"""Duplex 准备
Args:
system_prompt_text: 系统提示文本
ref_audio_path: LLM 参考音频路径(嵌入 system prompt)
prompt_wav_path: TTS 参考音频路径(初始化 vocoder)。
若不提供则 fallback 到 ref_audio_path。
"""
duplex_view = self.processor.set_duplex_mode()
return duplex_view.prepare(
system_prompt_text=system_prompt_text,
ref_audio_path=ref_audio_path or self.ref_audio_path,
prompt_wav_path=prompt_wav_path,
)
def duplex_prefill(
self,
audio_waveform: Optional[np.ndarray] = None,
frame_list: Optional[list] = None,
max_slice_nums: int = 1,
) -> Dict[str, Any]:
"""Duplex 预填充"""
duplex_view = self.processor.set_duplex_mode()
return duplex_view.prefill(
audio_waveform=audio_waveform,
frame_list=frame_list,
max_slice_nums=max_slice_nums,
)
def duplex_generate(self, force_listen: bool = False) -> DuplexGenerateResult:
"""Duplex 生成
Args:
force_listen: 前端 Force Listen 开关,强制本次生成为 listen
"""
duplex_view = self.processor.set_duplex_mode()
return duplex_view.generate(force_listen=force_listen)
def duplex_finalize(self) -> None:
"""Duplex 延迟 finalize(feed 终止符 + 滑窗维护)
必须在 duplex_generate 之后、下一次 duplex_prefill 之前调用。
"""
duplex_view = self.processor.set_duplex_mode()
duplex_view.finalize()
def duplex_stop(self) -> None:
"""Duplex 停止"""
duplex_view = self.processor.set_duplex_mode()
duplex_view.stop()
def duplex_cleanup(self) -> None:
"""Duplex 会话结束后释放 GPU 资源,恢复到初始状态
调用 DuplexView.cleanup() 释放 KV cache、TTS caches 等,
然后触发 gc + empty_cache 确保显存真正归还。
诊断数据(40B 参数模型):
- stop 后泄漏: ~1,591 MB
- cleanup 后残留: ~48 MB(忽略不计)
- 释放量: ~1,543 MB
"""
if self.processor is None:
return
duplex_view = self.processor.set_duplex_mode()
duplex_view.cleanup()
gc.collect()
torch.cuda.empty_cache()
logger.info(f"[GPU {self.gpu_id}] Duplex cleanup done, GPU memory released")
# ============ FastAPI 应用 ============
worker: Optional[MiniCPMOWorker] = None
# 启动参数(通过 main() 传入)
WORKER_CONFIG: Dict[str, Any] = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
"""应用生命周期:启动时加载模型"""
global worker
config = WORKER_CONFIG
worker = MiniCPMOWorker(
model_path=config["model_path"],
gpu_id=config["gpu_id"],
pt_path=config.get("pt_path"),
ref_audio_path=config.get("ref_audio_path"),
duplex_pause_timeout=config.get("duplex_pause_timeout", 60.0),
compile=config.get("compile", False),
chat_vocoder=config.get("chat_vocoder", "token2wav"),
attn_implementation=config.get("attn_implementation", "auto"),
)
# 模型加载是同步操作(~15s),在线程中执行避免阻塞
await asyncio.to_thread(worker.load_model)
yield
logger.info("Worker shutting down")
app = FastAPI(title="MiniCPMO45 Worker", lifespan=lifespan)
# ========== 健康检查 ==========
@app.get("/health", response_model=WorkerHealthResponse)
async def health():
"""健康检查"""
if worker is None:
return WorkerHealthResponse(
status="initializing",
worker_status=WorkerStatus.LOADING,
gpu_id=0,
model_loaded=False,
)
avg_time = 0.0
if worker.state.total_requests > 0:
avg_time = worker.state.total_inference_time_ms / worker.state.total_requests
kv_len = worker.processor.kv_cache_length if worker.processor else 0
return WorkerHealthResponse(
status="healthy" if worker.processor is not None else "error",
worker_status=worker.state.status,
gpu_id=worker.gpu_id,
model_loaded=worker.processor is not None,
current_session_id=worker.state.current_session_id,
total_requests=worker.state.total_requests,
avg_inference_time_ms=avg_time,
kv_cache_length=kv_len,
)
# ========== Chat API ==========
@app.post("/chat", response_model=ChatResponse)
async def chat(request: ChatRequest):
"""Chat 推理(无状态)"""
if worker is None or worker.processor is None:
raise HTTPException(status_code=503, detail="Worker not ready")
if not worker.state.is_idle:
# Gateway 排队机制已保证并发安全,但 Worker 可能还在 cleanup 上一个任务
# (如 Duplex WS close 后 GPU 资源释放),短暂等待而非立即拒绝
for _ in range(10):
await asyncio.sleep(0.5)
if worker.state.is_idle:
break
else:
raise HTTPException(
status_code=429,
detail=f"Worker busy after waiting 5s, status: {worker.state.status.value}",
)
# 录制:创建 TurnBasedSessionRecorder
chat_recorder: Optional[TurnBasedSessionRecorder] = None
chat_session_id: Optional[str] = None
from config import get_config
chat_cfg = get_config()
if chat_cfg.recording.enabled:
chat_session_id = generate_session_id("chat")
sys_prompt = ""
for m in request.messages:
if m.role == "system":
c = m.content
sys_prompt = c if isinstance(c, str) else str(c)
break
chat_recorder = TurnBasedSessionRecorder(
session_id=chat_session_id,
app_type="chat",
worker_id=worker.gpu_id,
config_snapshot={
"system_prompt": sys_prompt,
"ref_audio": chat_cfg.ref_audio_path,
},
data_dir=chat_cfg.data_dir,
)
try:
response = await asyncio.to_thread(worker.chat, request)
# 录制:记录 chat turn
if chat_recorder and response.success:
input_summary: Dict[str, Any] = {}
for m in request.messages:
if m.role == "user":
c = m.content
if isinstance(c, str):
input_summary["text"] = c
elif isinstance(c, list):
texts = [it.text for it in c if hasattr(it, "text") and it.text]
if texts:
input_summary["text"] = " ".join(texts)
output_audio: Optional[np.ndarray] = None
if response.audio_data:
try:
audio_bytes = base64.b64decode(response.audio_data)
output_audio = np.frombuffer(audio_bytes, dtype=np.float32)
except Exception:
pass
chat_recorder.record_chat_turn(
turn_index=0,
request_ts_ms=0.0,
input_summary=input_summary,
output_text=response.text,
output_audio=output_audio,
timing={
"elapsed_ms": round(response.duration_ms, 1) if response.duration_ms else 0,
"tokens": response.tokens_generated or 0,
},
)
if chat_recorder:
chat_recorder.finalize()
if chat_session_id and response.success:
response.recording_session_id = chat_session_id
return response
except Exception as e:
if chat_recorder:
try:
chat_recorder.finalize()
except Exception:
pass
logger.error(f"Chat failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
# ========== Chat WebSocket(统一流式/非流式) ==========
def _parse_raw_messages(raw_messages: List[dict]) -> List[Message]:
"""将前端原始消息列表解析为 Schema Message 列表"""
messages: List[Message] = []
for m in raw_messages:
role = Role(m["role"])
content = m["content"]
if isinstance(content, list):
content_items: List[ContentItem] = []
for item in content:
if isinstance(item, dict):
if item.get("type") == "text" and item.get("text"):
content_items.append(TextContent(text=item["text"]))
elif item.get("type") == "audio" and item.get("data"):
content_items.append(AudioContent(data=item["data"]))
elif item.get("type") == "image" and item.get("data"):
content_items.append(ImageContent(data=item["data"]))
elif item.get("type") == "video" and item.get("data"):
content_items.append(VideoContent(
data=item["data"],
stack_frames=item.get("stack_frames", 1),
))
if content_items:
messages.append(Message(role=role, content=content_items))
else:
messages.append(Message(role=role, content=content))
return messages
def _convert_to_model_msgs(schema_messages: List[Message]) -> list:
"""将 Schema Message 列表转为模型格式 msgs"""
from core.processors.base import MiniCPMOProcessorMixin
_mixin = MiniCPMOProcessorMixin()
model_msgs = []
for m in schema_messages:
content = _mixin._convert_content_to_model_format(m.content)
if len(content) == 1 and isinstance(content[0], str):
content = content[0]
model_msgs.append({"role": m.role.value, "content": content})
return model_msgs
@app.websocket("/ws/chat")
async def chat_ws(ws: WebSocket):
"""Chat WebSocket — 统一流式/非流式
协议:
1. Client → JSON:
{
"messages": [...],
"streaming": true/false,
"generation": {"max_new_tokens": 256, "length_penalty": 1.1},
"image": {"max_slice_nums": null},
"tts": {"enabled": false, "ref_audio_data": "..."},
"use_tts_template": false,
"omni_mode": false,
}
2. Server → {"type": "prefill_done", "input_tokens": N}
3a. streaming=true:
Server → {"type": "chunk", "text_delta": "...", "audio_data": "..."} × N
Server → {"type": "done", "text": "...", "generated_tokens": N, "input_tokens": N}
3b. streaming=false:
Server → {"type": "done", "text": "...", "audio_data": "...", "generated_tokens": N, "input_tokens": N}
4. Error:
Server → {"type": "error", "error": "..."}
"""
if worker is None or worker.processor is None:
await ws.close(code=1013, reason="Worker not ready")
return
await ws.accept()
logger.info("Chat WebSocket connected")
try:
raw = await ws.receive_text()
msg = json.loads(raw)
# 等待 Worker 空闲
if not worker.state.is_idle:
for _ in range(10):
await asyncio.sleep(0.5)
if worker.state.is_idle:
break
else:
await ws.send_json({"type": "error", "error": "Worker busy"})
await ws.close()
return
session_id = "chat_ws_" + uuid.uuid4().hex[:8]
worker.state.status = WorkerStatus.BUSY_HALF_DUPLEX
worker.state.current_session_id = session_id
chat_ws_recorder: Optional[TurnBasedSessionRecorder] = None
chat_ws_session_id: Optional[str] = None
try:
# 1. 解析消息和参数
messages = _parse_raw_messages(msg.get("messages", []))
model_msgs = _convert_to_model_msgs(messages)
streaming = msg.get("streaming", True)
gen_cfg = msg.get("generation", {})
max_new_tokens = gen_cfg.get("max_new_tokens", 256)
length_penalty = gen_cfg.get("length_penalty", 1.1)
max_slice_nums = None
img_cfg = msg.get("image", {})
if img_cfg and img_cfg.get("max_slice_nums") is not None:
max_slice_nums = int(img_cfg["max_slice_nums"])
generate_audio = False
tts_ref_audio_ndarray = None
use_tts_template = msg.get("use_tts_template", False)
tts_cfg = msg.get("tts", {})
if tts_cfg and tts_cfg.get("enabled"):
generate_audio = True
use_tts_template = True
ref_b64 = tts_cfg.get("ref_audio_data")
if ref_b64:
tts_ref_bytes = base64.b64decode(ref_b64)
tts_ref_audio_ndarray = np.frombuffer(tts_ref_bytes, dtype=np.float32)
omni_mode = msg.get("omni_mode", False)
enable_thinking = msg.get("enable_thinking", False)
from config import get_config
_chat_ws_cfg = get_config()
if _chat_ws_cfg.recording.enabled:
chat_ws_session_id = generate_session_id("chat")
raw_messages = msg.get("messages", [])
sys_prompt = ""
for m in raw_messages:
if m.get("role") == "system":
c = m.get("content", "")
sys_prompt = c if isinstance(c, str) else str(c)
break
chat_ws_recorder = TurnBasedSessionRecorder(
session_id=chat_ws_session_id,
app_type="chat",
worker_id=worker.gpu_id,
config_snapshot={
"system_prompt": sys_prompt,
"streaming": streaming,
"ref_audio": _chat_ws_cfg.ref_audio_path,
},
data_dir=_chat_ws_cfg.data_dir,
)
# 2. Prefill
def _do_prefill():
return worker.chat_prefill(
session_id=session_id,
msgs=model_msgs,
omni_mode=omni_mode,
max_slice_nums=max_slice_nums,
use_tts_template=use_tts_template,
enable_thinking=enable_thinking,
)
await asyncio.to_thread(_do_prefill)
pre_kv = worker.processor.kv_cache_length
await ws.send_json({"type": "prefill_done", "input_tokens": pre_kv})
# 3. TTS init
if generate_audio:
def _init_tts():
if tts_ref_audio_ndarray is not None:
worker.processor.model.init_token2wav_cache(prompt_speech_16k=tts_ref_audio_ndarray)
elif worker.ref_audio_path:
import librosa
ref_audio, _ = librosa.load(worker.ref_audio_path, sr=16000, mono=True)
worker.processor.model.init_token2wav_cache(prompt_speech_16k=ref_audio)
await asyncio.to_thread(_init_tts)
# Build input summary for recording — save all content types
_chat_input_summary: Dict[str, Any] = {}
_chat_audio_idx = 0
_chat_video_idx = 0
for _rm in msg.get("messages", []):
if _rm.get("role") == "user":
c = _rm.get("content", "")
if isinstance(c, str):
_chat_input_summary["text"] = c
elif isinstance(c, list):
texts = [it["text"] for it in c if isinstance(it, dict) and it.get("type") == "text" and it.get("text")]
if texts:
_chat_input_summary["text"] = " ".join(texts)
if chat_ws_recorder:
saved_imgs = []
saved_videos = []
for it in c:
if not isinstance(it, dict):
continue
if it.get("type") == "image" and it.get("data"):
try:
img_data = base64.b64decode(it["data"])
idx = chat_ws_recorder.next_image_index()
rel = chat_ws_recorder.save_user_image(idx, img_data)
saved_imgs.append(rel)
except Exception:
pass
elif it.get("type") == "audio" and it.get("data"):
try:
audio_bytes = base64.b64decode(it["data"])
audio_np = np.frombuffer(audio_bytes, dtype=np.float32)
rel = chat_ws_recorder.save_user_audio(_chat_audio_idx, audio_np)
_chat_input_summary["audio"] = rel
_chat_audio_idx += 1
except Exception:
pass
elif it.get("type") == "video" and it.get("data"):
try:
video_bytes = base64.b64decode(it["data"])
rel = chat_ws_recorder.save_user_video(_chat_video_idx, video_bytes)
saved_videos.append(rel)
_chat_video_idx += 1
except Exception:
pass
if saved_imgs:
_chat_input_summary["images"] = saved_imgs
if saved_videos:
_chat_input_summary["videos"] = saved_videos
_gen_start = time.perf_counter()
# 4. Generate
if streaming:
if chat_ws_recorder:
chat_ws_recorder.start_turn(turn_index=0, request_ts_ms=0.0, input_summary=_chat_input_summary)
chunk_queue: asyncio.Queue = asyncio.Queue()
loop = asyncio.get_event_loop()
def _run_generate():
try:
for chunk in worker.chat_streaming_generate(
session_id=session_id,
generate_audio=generate_audio,
max_new_tokens=max_new_tokens,
length_penalty=length_penalty,
):
loop.call_soon_threadsafe(chunk_queue.put_nowait, ("chunk", chunk))
loop.call_soon_threadsafe(chunk_queue.put_nowait, ("done", None))
except Exception as e:
loop.call_soon_threadsafe(chunk_queue.put_nowait, ("error", e))
gen_task = loop.run_in_executor(None, _run_generate)
full_text = ""
chunk_count = 0
while True:
tag, payload = await chunk_queue.get()
if tag == "chunk":
chunk_data = {"type": "chunk"}
if payload.text_delta:
chunk_data["text_delta"] = payload.text_delta
full_text += payload.text_delta
if payload.audio_data:
chunk_data["audio_data"] = payload.audio_data
if len(chunk_data) > 1:
await ws.send_json(chunk_data)
if chat_ws_recorder:
chat_ws_recorder.add_streaming_chunk(
text_delta=payload.text_delta,
audio_base64=payload.audio_data,
)
chunk_count += 1
elif tag == "done":
_gen_ids = getattr(worker.processor.model, '_streaming_generated_token_ids', None)
generated_tokens = len(_gen_ids) if _gen_ids else chunk_count
_elapsed = round((time.perf_counter() - _gen_start) * 1000, 1)
if chat_ws_recorder:
chat_ws_recorder.end_turn(timing={
"elapsed_ms": _elapsed,
"tokens": generated_tokens,
"input_tokens": pre_kv,
})
await ws.send_json({
"type": "done",
"text": full_text,
"generated_tokens": generated_tokens,
"input_tokens": pre_kv,
**({"recording_session_id": chat_ws_session_id} if chat_ws_session_id else {}),
})
break
elif tag == "error":
await ws.send_json({"type": "error", "error": str(payload)})
break
try:
await asyncio.wait_for(gen_task, timeout=5.0)
except asyncio.TimeoutError:
pass
else:
def _run_non_streaming():
return worker.chat_non_streaming_generate(
session_id=session_id,
max_new_tokens=max_new_tokens,
generate_audio=generate_audio,
use_tts_template=use_tts_template,
enable_thinking=enable_thinking,
tts_ref_audio=tts_ref_audio_ndarray,
length_penalty=length_penalty,
)
result = await asyncio.to_thread(_run_non_streaming)
text = result
audio_data = None
output_audio_np = None