ai_service.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  1. """
  2. AI服务:集成STT、LLM、TTS模型
  3. """
  4. import base64
  5. import json
  6. import asyncio
  7. import tempfile
  8. import os
  9. import logging
  10. import traceback
  11. from typing import AsyncGenerator, Optional
  12. import dashscope
  13. from openai import OpenAI
  14. from config import settings, get_dashscope_http_base_url, get_dashscope_domain
  15. from models import EmotionType
  16. logger = logging.getLogger(__name__)
  17. # 🔥 TTS API选择
  18. # 注意: SpeechSynthesizer (tts_v2) 使用callback模式,不适合我们的generator流式场景
  19. # MultiModalConversation 已经是最适合流式语音合成的API
  20. USE_NEW_TTS_API = False # 保持使用 MultiModalConversation
  21. # 设置API Key和endpoint(根据国际版/国内版自动选择)
  22. dashscope.api_key = settings.active_dashscope_api_key
  23. # 配置国际版endpoint(如果需要)
  24. if settings.use_dashscope_intl:
  25. dashscope_domain = get_dashscope_domain()
  26. dashscope.base_http_api_url = f"https://{dashscope_domain}/api/v1"
  27. dashscope.base_websocket_api_url = f"wss://{dashscope_domain}/api-ws/v1"
  28. class AIService:
  29. """AI服务管理器"""
  30. # 类级别的预热标记(避免多次实例化时重复预热)
  31. _tts_warmed_up = False
  32. _warmup_lock = None
  33. _tts_call_lock = None # TTS调用锁(防止SDK内部冲突)
  34. _last_tts_call_time = 0.0 # 上次TTS调用时间(用于速率控制)
  35. def __init__(self):
  36. import httpx
  37. import os
  38. # 临时清除代理环境变量(只在这个进程中)
  39. env_backup = {}
  40. proxy_vars = ['HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy', 'ALL_PROXY', 'all_proxy']
  41. for var in proxy_vars:
  42. if var in os.environ:
  43. env_backup[var] = os.environ[var]
  44. del os.environ[var]
  45. # 🔥 优化:创建高性能 HTTP 客户端 - 连接池配置
  46. # 注意:连接池不会阻塞新请求,每次 API 调用都是独立的 HTTP 请求
  47. # 连接池只是复用 TCP 连接,提高性能,不会影响随时建立新请求的能力
  48. http_client = httpx.Client(
  49. proxy=None, # 禁用代理
  50. timeout=60.0,
  51. trust_env=False, # 不信任环境变量中的代理设置
  52. # 连接池优化:复用 TCP 连接,但每次 API 调用都是独立请求
  53. limits=httpx.Limits(
  54. max_keepalive_connections=settings.HTTPX_MAX_KEEPALIVE_CONNECTIONS, # 从配置读取
  55. max_connections=settings.HTTPX_MAX_CONNECTIONS, # 从配置读取
  56. keepalive_expiry=settings.HTTPX_KEEPALIVE_EXPIRY, # 从配置读取
  57. ),
  58. # HTTP/2支持 - 多路复用,减少连接开销,支持并发请求
  59. http2=True,
  60. )
  61. self.openai_client = OpenAI(
  62. api_key=settings.active_dashscope_api_key,
  63. base_url=get_dashscope_http_base_url(),
  64. http_client=http_client, # 使用自定义 HTTP 客户端
  65. )
  66. # 🔥 连接健康检查标记
  67. self._last_llm_healthcheck: float = 0.0
  68. self._llm_healthcheck_interval = settings.LLM_HEALTHCHECK_INTERVAL # 从配置读取
  69. # 🔥 TTS优化:预热TTS连接(后台执行,不阻塞启动)
  70. import threading
  71. # 初始化锁
  72. if AIService._warmup_lock is None:
  73. AIService._warmup_lock = threading.Lock()
  74. AIService._tts_call_lock = threading.Lock() # 初始化TTS调用锁
  75. # 只预热一次(避免多次实例化时重复)
  76. if not AIService._tts_warmed_up:
  77. threading.Thread(target=self._warmup_tts_sync, daemon=True).start()
  78. # 恢复环境变量(避免影响其他模块)
  79. for var, value in env_backup.items():
  80. os.environ[var] = value
  81. def _warmup_tts_sync(self):
  82. """同步方式预热TTS连接(在后台线程执行)"""
  83. import time
  84. # 使用锁确保只预热一次
  85. with AIService._warmup_lock:
  86. if AIService._tts_warmed_up:
  87. return # 已经预热过了
  88. time.sleep(2) # 等待2秒确保服务启动完成
  89. try:
  90. start_time = time.time()
  91. response = dashscope.MultiModalConversation.call(
  92. model=settings.tts_model,
  93. text="Hi", # 极短的测试文本
  94. voice=settings.tts_voice,
  95. stream=True,
  96. )
  97. # 只接收首块即停止
  98. for _ in response:
  99. break
  100. AIService._tts_warmed_up = True # 标记为已预热
  101. except Exception as e:
  102. logger.error(
  103. f"[TTS异常] 错误类型=TTS预热失败, "
  104. f"异常类型={type(e).__name__}, "
  105. f"错误消息={str(e)}, "
  106. f"模型={settings.tts_model}, "
  107. f"音色={settings.tts_voice}, "
  108. f"堆栈跟踪:\n{traceback.format_exc()}"
  109. )
  110. # STT现在使用流式识别,在websocket_handler中直接处理
  111. async def generate_response_stream(
  112. self, user_text: str
  113. ) -> AsyncGenerator[tuple[str, EmotionType], None]:
  114. """
  115. 生成对话回复(流式)
  116. Args:
  117. user_text: 用户输入文本
  118. Yields:
  119. (sentence, emotion): 句子片段和情感
  120. """
  121. try:
  122. # 构建System Prompt
  123. system_prompt = self._build_system_prompt()
  124. # 调用LLM流式API
  125. import time
  126. llm_api_start = time.time()
  127. # 🔥 连接健康检查(长时间未使用时)
  128. await self._ensure_llm_connection()
  129. try:
  130. response = self.openai_client.chat.completions.create(
  131. model=settings.llm_model,
  132. messages=[
  133. {"role": "system", "content": system_prompt},
  134. {"role": "user", "content": user_text},
  135. ],
  136. temperature=0.7,
  137. max_tokens=500,
  138. stream=True, # 启用流式
  139. )
  140. except Exception as api_error:
  141. logger.error(
  142. f"[LLM异常] 错误类型=LLM API调用失败, "
  143. f"异常类型={type(api_error).__name__}, "
  144. f"错误消息={str(api_error)}, "
  145. f"模型={settings.llm_model}, "
  146. f"用户输入长度={len(user_text)}, "
  147. f"System Prompt长度={len(system_prompt)}, "
  148. f"API Key={settings.active_dashscope_api_key[:10]}... (已脱敏), "
  149. f"使用国际版={settings.use_dashscope_intl}, "
  150. f"堆栈跟踪:\n{traceback.format_exc()}"
  151. )
  152. raise
  153. buffer = ""
  154. full_response = ""
  155. sentence_count = 0
  156. detected_emotion: EmotionType = "neutral" # 存储检测到的情感
  157. emotion_yielded = False # 标记是否已发送情感
  158. chunk_count = 0 # 计数chunk
  159. for chunk in response:
  160. chunk_count += 1
  161. if chunk.choices[0].delta.content:
  162. content = chunk.choices[0].delta.content
  163. buffer += content
  164. full_response += content
  165. # 🎯 优先检测情感标记(如果还没检测到)
  166. if detected_emotion == "neutral" and "[EMOTION:" in full_response:
  167. emotion_start = full_response.find("[EMOTION:")
  168. emotion_end = full_response.find("]", emotion_start)
  169. if emotion_end > emotion_start:
  170. emotion_str = full_response[emotion_start + 9:emotion_end].strip().lower()
  171. valid_emotions = ["neutral", "happy", "sad", "excited", "angry", "surprised", "thoughtful", "encouraging", "confused", "worried", "satisfied", "friendly", "sorry"]
  172. if emotion_str in valid_emotions:
  173. detected_emotion = emotion_str
  174. # 🚀 立即 yield 空句子传递情感(减少延迟)
  175. if not emotion_yielded:
  176. yield ("", detected_emotion) # 空句子,仅传递情感
  177. emotion_yielded = True
  178. # 🧹 从 buffer 中移除情感标记(避免重复处理)
  179. buffer = buffer.replace(f"[EMOTION:{emotion_str.upper()}]", "").strip()
  180. # 检测句子边界(完整的句子)
  181. if self._is_complete_sentence(buffer):
  182. sentence = buffer.strip()
  183. sentence_count += 1
  184. # 使用已检测到的情感
  185. yield (sentence, detected_emotion)
  186. buffer = ""
  187. # 处理剩余内容(使用已检测到的情感)
  188. # 从完整响应中移除情感标签部分(用于日志输出)
  189. clean_response = full_response
  190. if "[EMOTION:" in full_response:
  191. emotion_start = full_response.find("[EMOTION:")
  192. clean_response = full_response[:emotion_start].strip()
  193. # 处理buffer中的剩余内容(已输出句子之后的部分)
  194. remaining = buffer.strip()
  195. if remaining and not remaining.startswith("[EMOTION"):
  196. sentence_count += 1
  197. yield (remaining, detected_emotion)
  198. elif not remaining and sentence_count == 0:
  199. # 如果一个句子都没输出,输出完整内容
  200. if clean_response:
  201. yield (clean_response, detected_emotion)
  202. else:
  203. # 🔥 兜底逻辑:LLM没有返回任何文本(只返回了情感标记)
  204. default_response = "I understand. Could you tell me more?"
  205. yield (default_response, detected_emotion)
  206. except Exception as e:
  207. logger.error(
  208. f"[LLM异常] 错误类型=LLM流式生成失败, "
  209. f"异常类型={type(e).__name__}, "
  210. f"错误消息={str(e)}, "
  211. f"模型={settings.llm_model}, "
  212. f"用户输入={user_text[:100]}... (前100字符), "
  213. f"堆栈跟踪:\n{traceback.format_exc()}"
  214. )
  215. yield ("I'm sorry, I'm having trouble understanding. Could you please repeat that?", "neutral")
  216. def _is_complete_sentence(self, text: str) -> bool:
  217. """检测是否完整句子"""
  218. text = text.strip()
  219. # 必须以句子结束符结尾
  220. if not text.endswith(('.', '!', '?', '。', '!', '?')):
  221. return False
  222. # 排除常见缩写(避免误判)
  223. words = text.split()
  224. if words:
  225. last_word = words[-1]
  226. # 常见英文缩写
  227. common_abbrev = ['Mr.', 'Mrs.', 'Ms.', 'Dr.', 'Prof.', 'Sr.', 'Jr.', 'etc.', 'e.g.', 'i.e.', 'vs.']
  228. if last_word in common_abbrev:
  229. return False
  230. # 🔥 优化:减少最小字符限制从5到3,让短句更快发送
  231. # 例如"Hi!" "OK!" "Yes!" 这种短句也能快速返回
  232. if len(text) < 3:
  233. return False
  234. return True
  235. async def generate_response(
  236. self, user_text: str
  237. ) -> tuple[str, EmotionType]:
  238. """
  239. 生成对话回复
  240. Args:
  241. user_text: 用户输入文本
  242. Returns:
  243. (response_text, emotion): 回复文本和情感
  244. """
  245. try:
  246. # 构建System Prompt
  247. system_prompt = self._build_system_prompt()
  248. # 🔥 连接健康检查(长时间未使用时)
  249. await self._ensure_llm_connection()
  250. # 调用LLM
  251. response = self.openai_client.chat.completions.create(
  252. model=settings.llm_model,
  253. messages=[
  254. {"role": "system", "content": system_prompt},
  255. {"role": "user", "content": user_text},
  256. ],
  257. temperature=0.7,
  258. max_tokens=500,
  259. )
  260. full_response = response.choices[0].message.content or ""
  261. # 提取情感标签
  262. emotion: EmotionType = "neutral"
  263. response_text = full_response
  264. # 查找情感标签
  265. if "[EMOTION:" in full_response:
  266. emotion_start = full_response.find("[EMOTION:")
  267. emotion_end = full_response.find("]", emotion_start)
  268. if emotion_end > emotion_start:
  269. emotion_str = full_response[emotion_start + 9:emotion_end].strip().lower()
  270. # 验证情感类型
  271. valid_emotions = ["neutral", "happy", "sad", "excited", "angry", "surprised", "thoughtful", "encouraging", "confused", "worried", "satisfied", "friendly", "sorry"]
  272. if emotion_str in valid_emotions:
  273. emotion = emotion_str
  274. # 移除情感标签(不发送给TTS)
  275. response_text = full_response[:emotion_start].strip()
  276. # 如果没有文本内容,使用默认回复
  277. if not response_text:
  278. response_text = "I understand. Please tell me more!"
  279. emotion = "neutral"
  280. return (response_text, emotion)
  281. except Exception as e:
  282. logger.error(
  283. f"[LLM异常] 错误类型=LLM生成失败, "
  284. f"异常类型={type(e).__name__}, "
  285. f"错误消息={str(e)}, "
  286. f"模型={settings.llm_model}, "
  287. f"用户输入={user_text[:100]}... (前100字符), "
  288. f"堆栈跟踪:\n{traceback.format_exc()}"
  289. )
  290. return ("I'm sorry, I'm having trouble understanding. Could you please repeat that?", "neutral")
  291. async def text_to_speech_stream(
  292. self, text: str, emotion: EmotionType = "neutral"
  293. ) -> AsyncGenerator[bytes, None]:
  294. """
  295. 文本转语音(流式 - 实时返回音频块),带重试机制和速率控制
  296. Args:
  297. text: 要合成的文本
  298. emotion: 情感类型
  299. Yields:
  300. audio_data: PCM 音频数据块(Base64 解码后的原始数据)
  301. """
  302. import time
  303. # 🚦 速率控制:确保两次TTS调用之间有最小间隔
  304. min_interval = settings.TTS_MIN_INTERVAL
  305. time_since_last_call = time.time() - AIService._last_tts_call_time
  306. if time_since_last_call < min_interval:
  307. wait_time = min_interval - time_since_last_call
  308. await asyncio.sleep(wait_time)
  309. # 更新最后调用时间
  310. AIService._last_tts_call_time = time.time()
  311. max_retries = settings.TTS_MAX_RETRIES
  312. retry_delay = settings.TTS_RETRY_DELAY
  313. backoff = settings.TTS_RETRY_BACKOFF
  314. for attempt in range(max_retries + 1):
  315. try:
  316. async for audio_chunk in self._text_to_speech_stream_internal(text, emotion):
  317. yield audio_chunk
  318. # 成功则退出
  319. return
  320. except Exception as e:
  321. # 检查是否为速率限制错误(429、Throttling、rate limit)
  322. error_str = str(e)
  323. is_rate_limit = (
  324. 'rate limit' in error_str.lower() or
  325. 'throttling' in error_str.lower() or
  326. '429' in error_str or
  327. 'RateQuota' in error_str
  328. )
  329. logger.error(
  330. f"[TTS异常] 错误类型=TTS流式生成失败, "
  331. f"异常类型={type(e).__name__}, "
  332. f"错误消息={str(e)}, "
  333. f"是否为速率限制={is_rate_limit}, "
  334. f"重试次数={attempt}/{max_retries}, "
  335. f"模型={settings.tts_model}, "
  336. f"音色={self._get_voice_for_emotion(emotion)}, "
  337. f"文本长度={len(text)}, "
  338. f"文本内容={text[:100]}... (前100字符), "
  339. f"堆栈跟踪:\n{traceback.format_exc()}"
  340. )
  341. if is_rate_limit and attempt < max_retries:
  342. wait_time = retry_delay * (backoff ** attempt)
  343. logger.warning(
  344. f"[TTS警告] 速率限制,等待{wait_time:.2f}秒后重试 "
  345. f"(第{attempt+1}/{max_retries}次重试)"
  346. )
  347. await asyncio.sleep(wait_time)
  348. continue
  349. else:
  350. # 非速率限制错误或已达最大重试次数
  351. raise
  352. async def _text_to_speech_stream_internal(
  353. self, text: str, emotion: EmotionType = "neutral"
  354. ) -> AsyncGenerator[bytes, None]:
  355. """
  356. TTS流式调用的内部实现(不含重试逻辑)
  357. Args:
  358. text: 要合成的文本
  359. emotion: 情感类型
  360. Yields:
  361. audio_data: PCM 音频数据块(Base64 解码后的原始数据)
  362. """
  363. try:
  364. import time
  365. tts_start = time.time()
  366. # 根据情感选择音色
  367. voice = self._get_voice_for_emotion(emotion)
  368. def sync_streaming_tts():
  369. return dashscope.MultiModalConversation.call(
  370. model=settings.tts_model,
  371. text=text,
  372. voice=voice,
  373. speech_rate=settings.tts_speech_rate, # 语速调整
  374. stream=True, # 流式输出
  375. # 注意: incremental_output 参数在此API中可能不生效
  376. )
  377. # 🔥 修复:使用队列在线程和异步之间传递数据
  378. import queue
  379. import threading
  380. audio_queue = queue.Queue()
  381. error_holder = [None] # 用列表包装以便在线程间共享
  382. def stream_producer():
  383. """在独立线程中执行同步流式API调用"""
  384. nonlocal chunk_count, first_chunk_time, total_audio_size
  385. try:
  386. # 🔥 关键修复:在锁内完成整个API调用和迭代
  387. # 原因:DashScope SDK内部可能有全局状态,并发迭代会冲突
  388. with AIService._tts_call_lock:
  389. response = sync_streaming_tts()
  390. chunk_index = 0
  391. for chunk in response:
  392. chunk_index += 1
  393. # 🔥 检查API错误(特别是速率限制)
  394. if hasattr(chunk, 'status_code') and chunk.status_code != 200:
  395. error_code = getattr(chunk, 'code', 'Unknown')
  396. error_msg = getattr(chunk, 'message', 'No error message')
  397. # 详细记录TTS API错误
  398. logger.error(
  399. f"[TTS异常] 错误类型=TTS API响应错误, "
  400. f"HTTP状态码={chunk.status_code}, "
  401. f"错误码={error_code}, "
  402. f"错误消息={error_msg}, "
  403. f"模型={settings.tts_model}, "
  404. f"音色={voice}, "
  405. f"文本长度={len(text)}, "
  406. f"chunk索引={chunk_index}, "
  407. f"完整chunk对象={chunk}"
  408. )
  409. # 构造友好的错误信息
  410. if chunk.status_code == 429 or 'Throttling' in error_code:
  411. raise Exception(f"TTS API速率限制: {error_msg} (code: {error_code})")
  412. else:
  413. raise Exception(f"TTS API错误 (status={chunk.status_code}): {error_msg} (code: {error_code})")
  414. if hasattr(chunk, 'output') and hasattr(chunk.output, 'audio'):
  415. audio = chunk.output.audio
  416. # 接收到音频数据块
  417. if audio.data is not None:
  418. # 记录首字节时间
  419. if first_chunk_time is None:
  420. first_chunk_time = time.time()
  421. # Base64 解码 PCM 数据
  422. pcm_bytes = base64.b64decode(audio.data)
  423. chunk_count += 1
  424. total_audio_size += len(pcm_bytes)
  425. # 放入队列
  426. audio_queue.put(('data', pcm_bytes))
  427. # 检查是否结束
  428. if hasattr(chunk.output, 'finish_reason') and chunk.output.finish_reason == "stop":
  429. tts_end = time.time()
  430. total_duration = (tts_end - tts_start) * 1000
  431. break
  432. # 标记完成
  433. audio_queue.put(('done', None))
  434. except Exception as e:
  435. logger.error(
  436. f"[TTS异常] 错误类型=TTS流式生成线程异常, "
  437. f"异常类型={type(e).__name__}, "
  438. f"错误消息={str(e)}, "
  439. f"模型={settings.tts_model}, "
  440. f"音色={voice}, "
  441. f"文本长度={len(text)}, "
  442. f"已接收chunk数={chunk_index}, "
  443. f"堆栈跟踪:\n{traceback.format_exc()}"
  444. )
  445. error_holder[0] = e
  446. audio_queue.put(('error', e))
  447. # 启动生产者线程
  448. chunk_count = 0
  449. first_chunk_time = None
  450. total_audio_size = 0
  451. received_data = False # 标记是否收到过数据
  452. producer_thread = threading.Thread(target=stream_producer, daemon=True)
  453. producer_thread.start()
  454. # 异步消费队列数据
  455. while True:
  456. # 非阻塞获取(避免阻塞事件循环)
  457. try:
  458. msg_type, data = await asyncio.to_thread(audio_queue.get, timeout=30)
  459. if msg_type == 'data':
  460. received_data = True
  461. yield data
  462. await asyncio.sleep(0) # 让出控制权
  463. elif msg_type == 'done':
  464. break
  465. elif msg_type == 'error':
  466. raise data
  467. except queue.Empty:
  468. error_msg = "TTS API 超时(30秒无响应)"
  469. logger.error(
  470. f"[TTS异常] 错误类型=TTS API超时, "
  471. f"错误消息={error_msg}, "
  472. f"模型={settings.tts_model}, "
  473. f"音色={self._get_voice_for_emotion(emotion)}, "
  474. f"文本长度={len(text)}, "
  475. f"已接收数据={received_data}, "
  476. f"chunk计数={chunk_count}"
  477. )
  478. raise Exception(error_msg)
  479. # 检查是否收到过数据(避免竞态条件)
  480. if not received_data:
  481. error_msg = f"TTS API 未返回任何音频数据 (text='{text}', emotion={emotion}, voice={voice})"
  482. if error_holder[0]:
  483. error_msg += f"\n生产者线程错误: {error_holder[0]}"
  484. logger.error(
  485. f"[TTS异常] 错误类型=TTS API无数据返回, "
  486. f"错误消息={error_msg}, "
  487. f"模型={settings.tts_model}, "
  488. f"音色={voice}, "
  489. f"文本长度={len(text)}, "
  490. f"文本内容={text[:100]}... (前100字符), "
  491. f"chunk计数={chunk_count}, "
  492. f"总音频大小={total_audio_size} bytes"
  493. )
  494. raise Exception(error_msg)
  495. except Exception as e:
  496. logger.error(
  497. f"[TTS异常] 错误类型=TTS流式生成内部异常, "
  498. f"异常类型={type(e).__name__}, "
  499. f"错误消息={str(e)}, "
  500. f"模型={settings.tts_model}, "
  501. f"音色={self._get_voice_for_emotion(emotion)}, "
  502. f"文本长度={len(text)}, "
  503. f"堆栈跟踪:\n{traceback.format_exc()}"
  504. )
  505. raise
  506. async def _ensure_llm_connection(self):
  507. """确保LLM连接可用(长时间未使用时进行健康检查)"""
  508. import time
  509. now = time.time()
  510. # 如果距离上次检查超过间隔,执行健康检查
  511. if now - self._last_llm_healthcheck < self._llm_healthcheck_interval:
  512. return
  513. try:
  514. # 🔥 执行简单的健康检查:发送一个极短的测试请求
  515. # 注意:使用asyncio.to_thread包装同步调用,避免阻塞事件循环
  516. def health_check():
  517. return self.openai_client.chat.completions.create(
  518. model=settings.llm_model,
  519. messages=[{"role": "user", "content": "Hi"}],
  520. max_tokens=1,
  521. timeout=5.0, # 5秒超时
  522. )
  523. test_response = await asyncio.to_thread(health_check)
  524. self._last_llm_healthcheck = now
  525. logger.debug("✅ LLM连接健康检查成功")
  526. except Exception as e:
  527. # 健康检查失败,重建HTTP客户端
  528. logger.warning(f"⚠️ LLM连接健康检查失败,重建连接: {e}")
  529. self._recreate_http_client()
  530. self._last_llm_healthcheck = now
  531. def _recreate_http_client(self):
  532. """重建HTTP客户端(连接失效时)"""
  533. import httpx
  534. try:
  535. # 关闭旧客户端
  536. if hasattr(self, 'openai_client') and self.openai_client:
  537. if hasattr(self.openai_client, '_client') and self.openai_client._client:
  538. self.openai_client._client.close()
  539. except:
  540. pass
  541. # 创建新客户端(使用配置值)
  542. http_client = httpx.Client(
  543. proxy=None,
  544. timeout=60.0,
  545. trust_env=False,
  546. limits=httpx.Limits(
  547. max_keepalive_connections=settings.HTTPX_MAX_KEEPALIVE_CONNECTIONS,
  548. max_connections=settings.HTTPX_MAX_CONNECTIONS,
  549. keepalive_expiry=settings.HTTPX_KEEPALIVE_EXPIRY,
  550. ),
  551. http2=True,
  552. )
  553. self.openai_client = OpenAI(
  554. api_key=settings.active_dashscope_api_key,
  555. base_url=get_dashscope_http_base_url(),
  556. http_client=http_client,
  557. )
  558. logger.info("✅ HTTP客户端已重建")
  559. def _get_voice_for_emotion(self, emotion: EmotionType) -> str:
  560. """根据情感选择音色"""
  561. # 所有情感统一使用配置文件中的音色
  562. return settings.tts_voice
  563. def _build_system_prompt(self) -> str:
  564. """构建System Prompt"""
  565. learner_proficiency = settings.LEARNER_PROFICIENCY
  566. age_tag = settings.AGE_TAG
  567. topic_tag = settings.TOPIC_TAG
  568. experiment_tag = settings.EXPERIMENT_TAG
  569. # 🔥 如果启用简化提示词(优化延迟)
  570. if settings.USE_SIMPLIFIED_PROMPT:
  571. return self._build_simplified_prompt(learner_proficiency, age_tag, topic_tag, experiment_tag)
  572. # 基础提示词
  573. prompt = f"""**[Role]**
  574. You are **KELLY**, a friendly and supportive English conversation partner based in London.
  575. **[Objective]**
  576. Help Chinese EFL learners practice **spoken English**.
  577. **[Target Audience]**
  578. - Language Level: **{learner_proficiency}**
  579. - Age Group: **{age_tag}**
  580. - Conversation Topic: **{topic_tag}**
  581. **[Response Guidelines]**
  582. 1. **Lead the Conversation**: Don't just follow the learner's questions—take initiative. Gently guide the conversation forward by introducing related ideas, asking engaging questions, or adding playful input.
  583. 2. **Stay Focused**: Keep the conversation on the topic {topic_tag}, and make it suitable for {age_tag} learners.
  584. 3. **Be Concise**: Respond in 2–3 short, natural sentences—like small talk with a friend.
  585. 4. **Use Simple Language**: Stick to A1-A2 level (very easy) vocabulary and grammar. No idioms, no complex tenses. Use high-frequency, easy words.
  586. 5. **Adapt to Learner**: If learners give very short or confused answers, simplify even more: use shorter, clearer sentences.
  587. 6. **Spark Real Conversation**: Ask easy follow-up questions that feel personal, imaginative, or reflective (e.g., "What if you could go anywhere?", "How do you feel when...?", "Why do you like it?"). Let the conversation feel playful, personal, and curious.
  588. 7. **Transition Smoothly**: If the topic feels finished or the learner seems less engaged, gently move to a related or new topic in a natural way. avoid overly specific or unusual questions (e.g., "What type of fish do you like?" or "What shape is your favorite lamp?"), as these can feel awkward or hard to answer. Instead, use broader, everyday topics that are easier to talk about, like: "That reminds me — do you usually cook at home or eat out?", "Speaking of weekends, do you like relaxing or doing something active?"
  589. 8. **Being Empathetic**: Acknowledge the learner's feelings and experiences, but avoid overdoing it.
  590. 9. **Seek Clarification**: When meaning is unclear, use context and ask the learner to clarify. After requesting clarification, pause and wait for their response before continuing the conversation.
  591. 10. **Handle Misunderstandings**:
  592. - If the learner says "Sorry?" → Rephrase your last sentence in simpler English.
  593. - If they ask "Do you mean…?" → Confirm their guess and briefly explain in basic terms.
  594. """
  595. # 如果是实验组,添加纠错反馈策略
  596. if experiment_tag == "experiment":
  597. correction_rule = """
  598. **[Corrective Feedback Strategy]**
  599. Goal:
  600. Prioritising conversation flow while helping learners notice and improve their grammar.
  601. Tone & Guidelines:
  602. (1) Use a kind and supportive tone: correct gently, and always reinforce progress;
  603. (2) Focus ONLY on grammar errors, ignore vocabulary issues;
  604. (3) Correct ONLY ONE error at a time;
  605. (4) Praise self-corrections (e.g. "I do… I did it last time") — encourage the effort, don't go back to correct the earlier mistake.
  606. (5) Reinforcement: Praise learners' correct usage to build their confidence. Examples: "That's right!", "Good job with the past tense!"
  607. (6) Avoid disrupting the conversation flow — don't say things like 'let's fix it', 'it should be...', 'you made a mistake', or 'you should say...'
  608. Correction Strategy:
  609. - For **grammar errors** (e.g., tense, agreement): Use **recasts** as the default - restate with correct form naturally; If meaning is unclear: use a clarification check; If repeated 2+ times: use explicit correction in simple and friendly English.
  610. - For **vocabulary errors** (e.g., inappropriate word choice): ONLY use recasts; NEVER explain or point out!
  611. Correction Techniques:
  612. - **Recast** (PREFERRED): For minor grammar mistakes, restate the learner's sentence naturally with the correct form — without pointing out the error or saying "like you said, but…". Example: Learner: "Yesterday I go to restaurant.", You: "Yesterday you **went** to the restaurant? That's great!"
  613. - **Clarification Check**: Ask a confirming question when meaning is unclear. After asking the question, DO NOT continue asking other follow-up questions; instead, wait for the student's clarification. Example: "Do you mean 'you **went** to the restaurant'?"
  614. - **Explicit Correction**: Only when a grammar mistake repeats many times, you explain the correct form clearly in basic English. After providing an Explicit Correction, DO NOT continue asking the follow-up question; instead, wait for the student's self-correction. If they try to self-correct, respond ONLY to the grammar part and don't focus on vocabulary. Example: "We say 'went' because it's past tense. So it's: 'I went to the restaurant.' Can you try it again?"
  615. """
  616. prompt += correction_rule
  617. # 添加情感标签要求(前置到开头)
  618. prompt += """
  619. **[Emotion Tag - IMPORTANT]**
  620. At the BEGINNING of your response, on the FIRST line, add the emotion tag in this exact format:
  621. [EMOTION:emotion_name]
  622. Then ALWAYS continue with your spoken response (2-3 sentences).
  623. Available emotions: neutral, happy, sad, excited, angry, surprised, thoughtful, encouraging, confused, worried, satisfied, friendly, sorry
  624. **How to choose emotion:**
  625. 1. **Respond to the learner's emotion**: If they express sadness/difficulty → use "sorry" or "encouraging"; if they're happy/excited → use "happy" or "excited"
  626. 2. **Match your response tone**: The emotion should reflect YOUR response style (empathetic, supportive, cheerful, etc.)
  627. 3. **Examples**:
  628. - Learner says "I'm sad today" → [EMOTION:sorry] "I'm sorry to hear that. What happened?"
  629. - Learner says "I passed my exam!" → [EMOTION:excited] "That's amazing! Congratulations!"
  630. - Learner asks a normal question → [EMOTION:friendly] or [EMOTION:neutral]
  631. Example response:
  632. [EMOTION:happy]
  633. That sounds like fun! What did you do there?
  634. CRITICAL:
  635. - NEVER return ONLY the emotion tag without spoken text
  636. - ALWAYS include 2-3 sentences of actual spoken response after the emotion tag
  637. - The emotion tag MUST be the FIRST line, before any other content
  638. - DO NOT use parentheses () or brackets [] in your spoken response (they will be removed during speech synthesis)
  639. - Keep your response natural and conversational, avoid meta-commentary or clarifications in parentheses"""
  640. return prompt
  641. def _build_simplified_prompt(self, learner_proficiency: str, age_tag: str, topic_tag: str, experiment_tag: str) -> str:
  642. """构建简化版System Prompt(优化延迟,减少token)"""
  643. prompt = f"""You are KELLY, a friendly English tutor in London.
  644. **Target**: {learner_proficiency} level, {age_tag}, {topic_tag}
  645. **Guidelines**:
  646. 1. Lead conversation actively, 2-3 short simple sentences
  647. 2. Use A1-A2 level vocabulary only
  648. 3. Ask easy, personal follow-up questions
  649. 4. If unclear, ask for clarification then wait
  650. 5. Transition smoothly between topics
  651. 6. Be empathetic but natural
  652. """
  653. # 实验组:简化的纠错规则
  654. if experiment_tag == "experiment":
  655. prompt += """
  656. **Feedback**:
  657. - Recast grammar errors naturally (one at a time)
  658. - Supportive tone, praise progress
  659. - Never say "you made a mistake"
  660. """
  661. # 情感标签(必需)
  662. prompt += """
  663. **Emotion Tag - REQUIRED**:
  664. Add [EMOTION:name] at the FIRST line, then ALWAYS follow with 2-3 sentences of spoken response.
  665. Emotions: neutral, happy, sad, excited, angry, surprised, thoughtful, encouraging, confused, worried, satisfied, friendly, sorry
  666. **Choose based on**:
  667. - Learner's emotion (sad→sorry/encouraging, happy→excited)
  668. - Your response tone (empathetic, supportive, cheerful)
  669. Example:
  670. [EMOTION:sorry]
  671. I'm sorry to hear that. What happened?
  672. Critical:
  673. - NEVER return ONLY the emotion tag
  674. - ALWAYS include actual spoken text after the tag
  675. - NO parentheses () or brackets [] in spoken text
  676. """
  677. return prompt
  678. async def generate_summary(self, prompt: str) -> str:
  679. """
  680. 生成对话总结(非流式)
  681. Args:
  682. prompt: 总结提示词
  683. Returns:
  684. 总结文本
  685. """
  686. try:
  687. # 🔥 连接健康检查(长时间未使用时)
  688. await self._ensure_llm_connection()
  689. response = self.openai_client.chat.completions.create(
  690. model=settings.llm_model,
  691. messages=[
  692. {"role": "system", "content": "你是一位专业的英语学习助手,擅长总结学习对话的关键信息。"},
  693. {"role": "user", "content": prompt},
  694. ],
  695. temperature=0.5,
  696. max_tokens=300,
  697. )
  698. summary = response.choices[0].message.content or ""
  699. return summary.strip()
  700. except Exception as e:
  701. logger.error(
  702. f"[LLM异常] 错误类型=生成总结失败, "
  703. f"异常类型={type(e).__name__}, "
  704. f"错误消息={str(e)}, "
  705. f"模型={settings.llm_model}, "
  706. f"提示词长度={len(prompt)}, "
  707. f"提示词内容={prompt[:200]}... (前200字符), "
  708. f"堆栈跟踪:\n{traceback.format_exc()}"
  709. )
  710. return ""
  711. # 全局AI服务实例
  712. ai_service = AIService()