.cursorrules 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. # Tolan AI 英语语音助手 - 开发规则
  2. ## 项目概述
  3. - **后端**: FastAPI + Python 3.11+ + WebSocket
  4. - **前端**: React 18 + TypeScript + Vite + Ant Design
  5. - **AI服务**: 阿里云 DashScope (STT/LLM/TTS)
  6. - **架构**: 实时语音对话流水线 (STT → LLM → TTS)
  7. ---
  8. ## 代码生成原则
  9. ### 文档规则
  10. - ❌ 避免生成冗长的 Markdown 文档
  11. - ✅ 代码优先,注释简洁
  12. - ✅ 必要文档:配置说明、API定义(列表形式)
  13. - ✅ 文档格式:表格 > 列表 > 段落
  14. - ✅ **文档生成路径规则**:
  15. - 项目文档 → `项目文档/` 目录
  16. - 后端文档 → `backend/文档/` 目录
  17. - 前端文档 → `frontend/docs/` 目录(如需要)
  18. - 配置文档 → 对应模块根目录(如 `backend/ENV_CONFIG.md`)
  19. ### 代码风格
  20. - **Python**: 类型提示、async/await、异常处理必需
  21. - **TypeScript**: 严格类型、接口定义、错误边界
  22. - **命名**: 英文、语义化、统一风格(snake_case/camelCase)
  23. - **注释**: 仅对复杂逻辑、性能优化、临时方案添加
  24. ---
  25. ## 后端开发规则
  26. ### FastAPI 结构
  27. ```python
  28. # 路由定义
  29. @app.websocket("/ws")
  30. async def endpoint(websocket: WebSocket): ...
  31. # 类型定义(必需)
  32. from pydantic import BaseModel
  33. class Message(BaseModel):
  34. type: str
  35. data: dict
  36. ```
  37. ### 异步编程
  38. - 所有 I/O 操作使用 `async/await`
  39. - 使用 `asyncio.to_thread()` 包装同步库
  40. - WebSocket 消息处理异步化
  41. ### 配置管理
  42. - 所有配置从 `.env` 读取
  43. - 使用 `pydantic-settings` 管理
  44. - 必需项无默认值,可选项提供默认值
  45. ### AI 服务集成
  46. ```python
  47. # DashScope API 调用模式
  48. import dashscope
  49. dashscope.api_key = settings.DASHSCOPE_API_KEY
  50. # 流式处理
  51. async for chunk in ai_service.generate_stream(text):
  52. await websocket.send_json(chunk)
  53. ```
  54. ### 错误处理
  55. ```python
  56. try:
  57. result = await api_call()
  58. except Exception as e:
  59. logger.error(f"Error: {e}")
  60. await send_error(request_id, str(e))
  61. ```
  62. ---
  63. ## 前端开发规则
  64. ### React + TypeScript
  65. ```typescript
  66. // 类型定义(必需)
  67. interface Message {
  68. type: string;
  69. requestId: string;
  70. data: unknown;
  71. }
  72. // 组件定义
  73. export const Component: React.FC<Props> = ({ ... }) => {
  74. // Hooks
  75. const [state, setState] = useState<Type>(initial);
  76. // 处理函数
  77. const handleEvent = useCallback(() => { ... }, [deps]);
  78. return <UI />;
  79. };
  80. ```
  81. ### WebSocket 通信
  82. ```typescript
  83. // 发送消息
  84. ws.send(JSON.stringify({ type, requestId, data }));
  85. // 接收消息
  86. ws.onmessage = (event) => {
  87. const message: Message = JSON.parse(event.data);
  88. handleMessage(message);
  89. };
  90. ```
  91. ### 状态管理 (Zustand)
  92. ```typescript
  93. export const useStore = create<State>((set) => ({
  94. value: initial,
  95. update: (newValue) => set({ value: newValue }),
  96. }));
  97. ```
  98. ### 音频处理
  99. ```typescript
  100. // 录音
  101. const recorder = new Recorder({ sampleRate: 16000 });
  102. recorder.start();
  103. // Base64 编码
  104. const base64 = btoa(String.fromCharCode(...audioData));
  105. ```
  106. ---
  107. ## API 集成规则
  108. ### DashScope STT
  109. - 模型: `qwen3-asr-flash-realtime`
  110. - 格式: PCM 16kHz mono
  111. - 流式识别: WebSocket API
  112. ### DashScope LLM
  113. - 模型: `qwen-turbo/qwen-plus`
  114. - 模式: 流式输出 (stream=True)
  115. - 提示词: 简化版优先
  116. ### DashScope TTS
  117. - 模型: `qwen3-tts-flash`
  118. - 音色: `Cherry` (女声)
  119. - 输出: PCM 24kHz
  120. - 速率控制: `TTS_MIN_INTERVAL` 避免限流
  121. ---
  122. ## WebSocket 消息协议
  123. ### 客户端 → 服务端
  124. ```typescript
  125. { type: "audio_chunk", requestId, data: base64, chunkIndex, sampleRate }
  126. { type: "audio_end", requestId, totalChunks }
  127. { type: "cancel", requestId }
  128. ```
  129. ### 服务端 → 客户端
  130. ```typescript
  131. { type: "text_result", requestId, text, isFinal }
  132. { type: "emotion", requestId, emotion }
  133. { type: "audio_response", requestId, data: base64, chunkIndex, isLast }
  134. { type: "error", requestId, code, message }
  135. ```
  136. ---
  137. ## 性能优化规则
  138. ### 后端优化
  139. - TTS 连接预热(启动时)
  140. - HTTP/2 连接池(httpx)
  141. - 流式处理(LLM+TTS 并行)
  142. - 动态超时(根据 STT 更新时间)
  143. ### 前端优化
  144. - 音频流式播放(边接收边播放)
  145. - WebSocket 断线重连
  146. - 组件懒加载 (React.lazy)
  147. - 防抖/节流(用户交互)
  148. ---
  149. ## 文档生成规范
  150. ### 文档类型与路径
  151. | 文档类型 | 生成路径 | 示例 |
  152. |---------|---------|------|
  153. | 项目架构/设计文档 | `项目文档/` | `项目文档/系统架构设计.md` |
  154. | API 文档 | `项目文档/` | `项目文档/前后端交互API文档.md` |
  155. | 需求文档 | `需求/` | `需求/用户需求.md` |
  156. | 后端技术文档 | `backend/文档/` | `backend/文档/数据库设计.md` |
  157. | 后端配置说明 | `backend/` | `backend/ENV_CONFIG.md` |
  158. | 前端技术文档 | `frontend/docs/` | `frontend/docs/组件设计.md` |
  159. | 部署运维文档 | `项目文档/` | `项目文档/部署指南.md` |
  160. ### 文档命名规则
  161. - 使用中文文件名(项目主要使用中文)
  162. - 描述清晰、简洁
  163. - 格式:`功能描述.md`
  164. ---
  165. ## 常见任务模板
  166. ### 添加新的 WebSocket 消息类型
  167. 1. `backend/models.py`: 定义 Pydantic 模型
  168. 2. `backend/websocket_handler.py`: 添加处理函数
  169. 3. `frontend/src/types/index.ts`: 定义 TypeScript 类型
  170. 4. `frontend/src/utils/websocket.ts`: 添加发送/接收逻辑
  171. ### 添加新的环境变量
  172. 1. `backend/.env`: 添加配置项
  173. 2. `backend/config.py`: 定义 Settings 字段
  174. 3. `backend/ENV_CONFIG.md`: 更新文档(仅列表)
  175. ### 添加新的 UI 页面
  176. 1. `frontend/src/pages/`: 创建页面组件
  177. 2. `frontend/src/router/`: 添加路由
  178. 3. 使用 Ant Design 组件,保持风格统一
  179. ### 生成技术文档
  180. 1. 确定文档类型(架构/API/配置/需求等)
  181. 2. 根据上表选择正确的生成路径
  182. 3. 使用表格格式(优先)
  183. 4. 内容控制在 100 行以内
  184. ---
  185. ## 禁止事项
  186. - ❌ 生成超过 100 行的 Markdown 文档
  187. - ❌ 在代码中使用 `any` 类型(TypeScript)
  188. - ❌ 同步阻塞 I/O 操作(后端)
  189. - ❌ 硬编码 API 密钥或敏感信息
  190. - ❌ 未处理的 Promise rejection
  191. - ❌ 未添加类型提示的函数(Python/TS)
  192. ---
  193. ## 调试技巧
  194. ```python
  195. # 后端日志
  196. print(f"[{request_id}] 🔍 Debug: {variable}")
  197. # 性能测试
  198. import time
  199. start = time.time()
  200. # ... code ...
  201. print(f"⏱️ Duration: {(time.time() - start)*1000:.1f}ms")
  202. ```
  203. ```typescript
  204. // 前端日志
  205. console.log('[WebSocket] Received:', message.type);
  206. console.time('Processing');
  207. // ... code ...
  208. console.timeEnd('Processing');
  209. ```