Spaces:
Runtime error
Runtime error
Download api/message.py from little666trader/backend-bxt: direct link, hf CLI and curl.
- Browser
- Download file 13.7 kB
-
https://huggingface.co/spaces/little666trader/backend-bxt/resolve/main/api/message.py
- Command line
-
hf download hf://spaces/little666trader/backend-bxt/api/message.py
-
curl -L -o message.py https://huggingface.co/spaces/little666trader/backend-bxt/resolve/main/api/message.py
13.7 kB
| """ | |
| @router /api/message | |
| @description 聊天消息路由模块 | |
| @author wjh | |
| @created at 2025-11-3 | |
| """ | |
| import os | |
| import jwt | |
| import json | |
| import asyncio | |
| from models.user_model import User | |
| from typing import Optional, List | |
| from service import chat_service | |
| from models.chat_session import ChatSession | |
| from models.message_model import Message, SenderType | |
| from service.chat_switcher import decide_provider, get_provider_bot, model_name_from_bot | |
| from service.history_aggregator import build_message_items, extract_key_fragments | |
| from service.providers.primary_client import complete_chat as deepseek_complete, translate_bridge_cn2en, stream_chat as deepseek_stream | |
| from service.providers.perplexity_client import complete_chat as pplx_complete, stream_chat as pplx_stream | |
| from fastapi import APIRouter, Depends, HTTPException, Query, WebSocket, WebSocketDisconnect | |
| from schemas.chat_message_schema import ChatMessage,ChatResponse,ChatHistoryResponse,MessageItem,ChatResponseEnvelope,ChatHistoryEnvelope | |
| from dependencies.auth import get_current_user | |
| from config.security import JWT_SECRET | |
| from config.prompt_loader import get as prompt_get | |
| router = APIRouter() | |
| # Provider 调用超时时间(秒),避免前端长时间等待无响应 (timeout for provider calls, to avoid long waiting in frontend) | |
| PROVIDER_TIMEOUT_SECONDS = int(os.getenv("CHAT_PROVIDER_TIMEOUT_SECONDS", "12")) | |
| # 聊天路由 (chat router) | |
| async def chat(data: ChatMessage, current_user: User = Depends(get_current_user)) -> ChatResponseEnvelope: | |
| # 基本校验:消息内容不能为空 | |
| if not data.message or not data.message.strip(): | |
| raise HTTPException(status_code=400, detail="消息内容不能为空") | |
| # 获取或创建会话 (get or create chat session) | |
| session: Optional[ChatSession] = None | |
| if data.session_id: | |
| session = await ChatSession.get_or_none(id=data.session_id, user_id=current_user.id) | |
| if not session: | |
| session = await ChatSession.create(user=current_user) | |
| # 交由服务层解析 @机器人、生成回复并完成持久化 (handle chat request and persist messages) | |
| reply_text, user_msg, bot_msg, used_bot, summary_text = await chat_service.handle_chat( | |
| session=session, | |
| raw_text=data.message.strip(), | |
| history=data.history or [] | |
| ) | |
| return { | |
| "success": True, | |
| "data": ChatResponse( | |
| reply=reply_text, | |
| session_id=session.id, | |
| message_id=bot_msg.id, | |
| created_at=bot_msg.created_at, | |
| summary=summary_text | |
| ) | |
| } | |
| # WebSocket 实时聊天路由(websocket chat router for mini program) | |
| async def chat_ws(websocket: WebSocket): | |
| """ | |
| WebSocket 聊天:客户端建立连接后发送一条 JSON: | |
| { message: string, session_id?: number, history?: [{id,role,content}] } | |
| 服务端按增量(delta)推送: | |
| - { is_final: false, content: string } | |
| - 最终:{ is_final: true, content, session_id, message_id, provider, model, citations } | |
| 鉴权:优先从 query 参数 `token` 获取;其次尝试 `Authorization: Bearer ...`。 | |
| """ | |
| # 解析令牌并完成鉴权 (parse token and authenticate) | |
| token = websocket.query_params.get("token") | |
| if not token: | |
| authz = websocket.headers.get("Authorization") | |
| if authz and authz.startswith("Bearer "): | |
| token = authz.split(" ", 1)[1] | |
| if not token: | |
| await websocket.close(code=4401, reason="未认证:缺少令牌") | |
| return | |
| try: | |
| payload = jwt.decode(token, JWT_SECRET, algorithms=["HS256"]) # type: ignore | |
| openid = payload.get("openid") | |
| if not openid: | |
| await websocket.close(code=4401, reason="令牌无效:缺少 openid") | |
| return | |
| current_user = await User.get_or_none(openid=openid) | |
| if not current_user: | |
| await websocket.close(code=4401, reason="用户不存在") | |
| return | |
| except jwt.PyJWTError: | |
| await websocket.close(code=4401, reason="令牌解析失败") | |
| return | |
| await websocket.accept() | |
| try: | |
| print(f"[WS] accepted /api/message/chat/ws openid={openid}") | |
| except Exception: | |
| pass | |
| try: | |
| # 接收首条请求载荷 (receive first request payload) | |
| first = await websocket.receive_text() | |
| data = json.loads(first or "{}") | |
| message_text = (data.get("message") or "").strip() | |
| if not message_text: | |
| await websocket.send_text(json.dumps({"is_final": True, "content": ""}, ensure_ascii=False)) | |
| await websocket.close(code=1000) | |
| return | |
| # 获取或创建会话 (get or create chat session) | |
| session: Optional[ChatSession] = None | |
| sid = data.get("session_id") | |
| if sid: | |
| session = await ChatSession.get_or_none(id=sid, user_id=current_user.id) | |
| if not session: | |
| session = await ChatSession.create(user=current_user) | |
| # 先持久化用户消息 (persist user message) | |
| try: | |
| _ = await chat_service.persist_user_message(session, message_text) | |
| if not session.title or not session.title.strip(): | |
| base = message_text.strip() | |
| if base: | |
| session.title = (base[:30] + ('...' if len(base) > 30 else '')) | |
| await session.save() | |
| except Exception: | |
| pass | |
| # 决策与模型 (decide provider and model) | |
| decision = await decide_provider(session) | |
| provider = decision.get("provider", "deepseek") | |
| reason = decision.get("reason", "") | |
| provider_bot = await get_provider_bot(provider) | |
| model_name = model_name_from_bot(provider_bot) | |
| # 历史聚合 (build message items) | |
| history_items = await build_message_items(session) | |
| # 先发送一个预热增量,提升交互感知 (send a warmup delta to improve interaction perception) | |
| try: | |
| await websocket.send_text(json.dumps({"is_final": False, "content": "正在生成,请稍候…"}, ensure_ascii=False)) | |
| except Exception: | |
| pass | |
| # 调用 Provider:实时流式转发增量数据 (call provider: stream forward delta data) | |
| citations: List[dict] = [] | |
| full_parts: List[str] = [] | |
| try: | |
| print(f"[WS] provider={provider} (stream) model={model_name} reason={reason}") | |
| if provider == "deepseek": | |
| system_prompt = prompt_get("primary", "deepseek_system", "你是一名越南律师,正在为中国客户提供法律咨询。根据用户输入与对话历史,产出问题清单,不直接给出法律结论。") | |
| messages = [{"role": "system", "content": system_prompt}] | |
| for it in history_items: | |
| role = it.role if it.role in ("user", "assistant", "system") else "user" | |
| messages.append({"role": role, "content": it.content}) | |
| messages.append({"role": "user", "content": message_text}) | |
| # 先推送前缀,统一体验 (send prefix to improve experience) | |
| prefix = prompt_get("primary", "deepseek_prefix", "[问题清单] ") | |
| await websocket.send_text(json.dumps({"is_final": False, "content": prefix}, ensure_ascii=False)) | |
| full_parts.append(prefix) | |
| async for evt in deepseek_stream(messages, model=model_name): | |
| if evt.get("type") == "delta": | |
| text = evt.get("content") or "" | |
| if text: | |
| full_parts.append(text) | |
| try: | |
| await websocket.send_text(json.dumps({"is_final": False, "content": text}, ensure_ascii=False)) | |
| except Exception: | |
| break | |
| elif evt.get("type") == "final": | |
| break | |
| else: | |
| fragments = extract_key_fragments(history_items, max_chars=512) | |
| bridge_input = f"用户补充:\n{message_text}\n\n历史关键片段:\n{fragments}" | |
| ds_bot = await get_provider_bot("deepseek") | |
| ds_model = model_name_from_bot(ds_bot) | |
| bridge_en = await asyncio.wait_for( | |
| translate_bridge_cn2en(bridge_input, model=ds_model), timeout=PROVIDER_TIMEOUT_SECONDS | |
| ) | |
| system_prompt_en = prompt_get("perplexity", "system", "You are a legal research assistant. Answer in Chinese. At the end, provide 3–5 references (title + URL + short note).") | |
| messages = [ | |
| {"role": "system", "content": system_prompt_en}, | |
| {"role": "user", "content": bridge_en}, | |
| ] | |
| prefix = prompt_get("perplexity", "prefix", "[咨询草案] ") | |
| await websocket.send_text(json.dumps({"is_final": False, "content": prefix}, ensure_ascii=False)) | |
| full_parts.append(prefix) | |
| async for evt in pplx_stream(messages, model=model_name): | |
| t = evt.get("type") | |
| if t == "delta": | |
| text = evt.get("content") or "" | |
| if text: | |
| full_parts.append(text) | |
| try: | |
| await websocket.send_text(json.dumps({"is_final": False, "content": text}, ensure_ascii=False)) | |
| except Exception: | |
| break | |
| elif t == "final": | |
| citations = evt.get("citations") or [] | |
| break | |
| except Exception: | |
| base_reply = await chat_service.generate_reply(message_text, history_items, model_name) | |
| if provider == "deepseek": | |
| fallback = f"[问题清单] {base_reply}" | |
| else: | |
| fallback = f"[咨询草案] {base_reply}" | |
| citations = [] | |
| full_parts = [] | |
| try: | |
| await websocket.send_text(json.dumps({"is_final": False, "content": fallback[:0]}, ensure_ascii=False)) | |
| except Exception: | |
| pass | |
| idx = 0 | |
| step = 96 | |
| while idx < len(fallback): | |
| chunk = fallback[idx:idx+step] | |
| full_parts.append(chunk) | |
| idx += step | |
| try: | |
| await websocket.send_text(json.dumps({"is_final": False, "content": chunk}, ensure_ascii=False)) | |
| except Exception: | |
| break | |
| # 最终消息持久化与发送 (persist and send final message) | |
| full_joined = "".join(full_parts).strip() | |
| bot_msg = await chat_service.persist_bot_message(session, full_joined, provider_bot) | |
| final_payload = { | |
| "is_final": True, | |
| "content": full_joined, | |
| "citations": [] if provider == "deepseek" else citations, | |
| "session_id": session.id, | |
| "message_id": bot_msg.id, | |
| "provider": provider, | |
| "model": model_name, | |
| "route_reason": reason, | |
| } | |
| try: | |
| await websocket.send_text(json.dumps(final_payload, ensure_ascii=False)) | |
| except Exception: | |
| pass | |
| try: | |
| print(f"[WS] final sent; total_len={len(full_joined)} session={session.id} msg_id={bot_msg.id}") | |
| except Exception: | |
| pass | |
| await websocket.close(code=1000) | |
| except WebSocketDisconnect: | |
| # 客户端断开连接 (client disconnect) | |
| try: | |
| await websocket.close(code=1000) | |
| except Exception: | |
| pass | |
| except Exception: | |
| # 未知错误:尽量告知客户端再关闭 (unknown error: try to notify client to close) | |
| try: | |
| await websocket.send_text(json.dumps({"is_final": True, "content": ""}, ensure_ascii=False)) | |
| except Exception: | |
| pass | |
| try: | |
| await websocket.close(code=1011, reason="服务器内部错误") | |
| except Exception: | |
| pass | |
| # 获取聊天历史记录路由 (get chat history router) | |
| async def history( | |
| session_id: int = Query(...), | |
| limit: int = Query(50, ge=1, le=200), | |
| offset: int = Query(0, ge=0), | |
| current_user: User = Depends(get_current_user) | |
| ) -> ChatHistoryEnvelope: | |
| session = await ChatSession.get_or_none(id=session_id, user_id=current_user.id) | |
| if not session: | |
| raise HTTPException(status_code=404, detail="会话不存在或无权访问") | |
| total = await Message.filter(session=session).count() | |
| msgs: List[Message] = await Message.filter(session=session).order_by("created_at").offset(offset).limit(limit) | |
| def to_role(sender_type: SenderType) -> str: | |
| if sender_type == SenderType.BOT: | |
| return "assistant" | |
| if sender_type == SenderType.USER: | |
| return "user" | |
| return "system" | |
| items = [ | |
| MessageItem( | |
| id=m.id, | |
| role=to_role(m.sender_type), | |
| content=m.content, | |
| timestamp=m.created_at | |
| ) | |
| for m in msgs | |
| ] | |
| has_more = offset + len(items) < total | |
| return { | |
| "success": True, | |
| "data": ChatHistoryResponse( | |
| messages=items, | |
| session_id=session.id, | |
| has_more=has_more, | |
| total=total | |
| ) | |
| } |