content_completion.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. # -*- coding: utf-8 -*-
  2. """
  3. 上下文生成接口 - 极速版 (DashScope Aliyun Optimized)
  4. 目标平台:阿里云 DashScope (兼容模式)
  5. API URL: https://dashscope.aliyuncs.com/compatible-mode/v1
  6. 模型:qwen3-30b-a3b-instruct-2507
  7. """
  8. import uuid
  9. import json
  10. import time
  11. import asyncio
  12. import aiohttp
  13. from typing import Optional, List, Dict, Any, AsyncGenerator
  14. from pydantic import BaseModel, Field
  15. from fastapi import APIRouter, HTTPException
  16. from fastapi.responses import StreamingResponse
  17. from foundation.observability.logger.loggering import write_logger as logger
  18. from foundation.infrastructure.tracing import TraceContext, auto_trace
  19. from foundation.infrastructure.config.config import config_handler
  20. from core.base.workflow_manager import WorkflowManager
  21. from redis.asyncio import Redis as AsyncRedis
  22. # ==================== 1. 配置与路径初始化 ====================
  23. content_completion_router = APIRouter(prefix="/sgbx", tags=["施工方案编写"])
  24. workflow_manager = WorkflowManager(max_concurrent_docs=3, max_concurrent_reviews=5)
  25. # ==================== 2. 全局资源池 (速度优化核心) ====================
  26. GLOBAL_HTTP_SESSION: Optional[aiohttp.ClientSession] = None
  27. GLOBAL_REDIS_CLIENT: Optional[AsyncRedis] = None
  28. async def init_global_resources():
  29. """初始化全局连接池"""
  30. global GLOBAL_HTTP_SESSION, GLOBAL_REDIS_CLIENT
  31. if GLOBAL_HTTP_SESSION is None or GLOBAL_HTTP_SESSION.closed:
  32. # 增加 DNS 缓存和连接复用,针对阿里云域名优化
  33. connector = aiohttp.TCPConnector(limit=100, limit_per_host=20, ttl_dns_cache=300, force_close=False)
  34. GLOBAL_HTTP_SESSION = aiohttp.ClientSession(
  35. timeout=aiohttp.ClientTimeout(total=120, connect=10, sock_read=10), # 连接超时稍长以防网络波动
  36. connector=connector,
  37. headers={"User-Agent": "FastAPI-DashScope-Optimized/2.0"}
  38. )
  39. logger.info("✅ 全局 HTTP 连接池已初始化 (DashScope Ready)")
  40. if GLOBAL_REDIS_CLIENT is None:
  41. try:
  42. GLOBAL_REDIS_CLIENT = AsyncRedis(
  43. host='127.0.0.1', port=6379, password='123456', db=0,
  44. decode_responses=True, socket_connect_timeout=1,
  45. socket_keepalive=True, max_connections=50
  46. )
  47. asyncio.create_task(_background_ping())
  48. logger.info("✅ 全局 Redis 连接池已初始化")
  49. except Exception as e:
  50. logger.warning(f"⚠️ Redis 初始化失败: {e}")
  51. GLOBAL_REDIS_CLIENT = None
  52. async def _background_ping():
  53. if GLOBAL_REDIS_CLIENT:
  54. try: await GLOBAL_REDIS_CLIENT.ping()
  55. except: pass
  56. async def get_http_session():
  57. if GLOBAL_HTTP_SESSION is None or GLOBAL_HTTP_SESSION.closed:
  58. await init_global_resources()
  59. return GLOBAL_HTTP_SESSION
  60. async def get_redis_client():
  61. if GLOBAL_REDIS_CLIENT is None:
  62. await init_global_resources()
  63. return GLOBAL_REDIS_CLIENT
  64. # ==================== 3. 文件操作工具 ====================
  65. # ==================== 4. 自定义 API 配置 (阿里云 DashScope) ====================
  66. class CustomAPIConfig:
  67. # 【关键修改】阿里云 DashScope 兼容模式地址
  68. # 注意:必须包含 /chat/completions 后缀
  69. DASHSCOPE_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
  70. DASHSCOPE_CHAT_URL = f"{DASHSCOPE_BASE_URL}/chat/completions"
  71. # 【关键修改】您的 API Key
  72. DASHSCOPE_API_KEY = "sk-ae805c991b6a4a8da3a09351c34963a5"
  73. # 【关键修改】目标模型
  74. DEFAULT_MODEL_NAME = "qwen3-30b-a3b-instruct-2507"
  75. @staticmethod
  76. def get_api_url() -> str:
  77. # 优先使用硬编码的阿里云地址
  78. return CustomAPIConfig.DASHSCOPE_CHAT_URL
  79. @staticmethod
  80. def get_api_key() -> str:
  81. return CustomAPIConfig.DASHSCOPE_API_KEY
  82. @staticmethod
  83. def get_model_name() -> str:
  84. # 允许配置覆盖,否则使用默认
  85. configured_model = config_handler.get("custom_api", "MODEL_NAME", "")
  86. return configured_model if configured_model else CustomAPIConfig.DEFAULT_MODEL_NAME
  87. @staticmethod
  88. def is_enabled() -> bool:
  89. # 只要 Key 不为空即启用
  90. return bool(CustomAPIConfig.get_api_key()) and bool(CustomAPIConfig.get_api_url())
  91. # ==================== 5. 极速流式调用 (核心优化) ====================
  92. async def call_custom_api_stream(
  93. prompt: str, system_prompt: str = "", max_tokens: int = 2000,
  94. temperature: float = 0.7, trace_id: str = ""
  95. ) -> AsyncGenerator[tuple[str, Optional[float]], None]:
  96. api_url = CustomAPIConfig.get_api_url()
  97. model_name = CustomAPIConfig.get_model_name()
  98. api_key = CustomAPIConfig.get_api_key()
  99. logger.debug(f"[{trace_id}] 正在调用阿里云 DashScope: {model_name} @ {api_url}")
  100. # 截断过长的 Prompt (阿里云对输入长度有限制,且为了速度)
  101. max_prompt_len = 10000
  102. if len(prompt) > max_prompt_len:
  103. prompt = prompt[-max_prompt_len:]
  104. logger.debug(f"[{trace_id}] Prompt 已截断至 {max_prompt_len} 字符")
  105. payload = {
  106. "model": model_name,
  107. "messages": [
  108. {"role": "system", "content": system_prompt},
  109. {"role": "user", "content": prompt}
  110. ],
  111. "max_tokens": max_tokens,
  112. "temperature": temperature,
  113. "stream": True,
  114. "incremental_output": True # 阿里云兼容模式可能支持此参数,优化流式体验
  115. }
  116. headers = {
  117. "Content-Type": "application/json",
  118. "Authorization": f"Bearer {api_key}"
  119. }
  120. start_time = time.time()
  121. first_token_time: Optional[float] = None
  122. buffer = ""
  123. session = await get_http_session()
  124. try:
  125. # 阿里云 HTTPS 连接,保持 read_bufsize=1 以获取最快首字
  126. async with session.post(api_url, json=payload, headers=headers, read_bufsize=1) as response:
  127. if response.status != 200:
  128. error_text = await response.text()
  129. logger.error(f"[{trace_id}] API 错误 {response.status}: {error_text}")
  130. raise Exception(f"API 错误 {response.status}: {error_text}")
  131. async for chunk in response.content.iter_any():
  132. if not chunk: continue
  133. try:
  134. text = chunk.decode('utf-8', errors='ignore')
  135. if not text: continue
  136. buffer += text
  137. while '\n' in buffer:
  138. line, buffer = buffer.split('\n', 1)
  139. line = line.strip()
  140. if line.startswith('data: '):
  141. data = line[6:]
  142. if data == '[DONE]':
  143. return
  144. try:
  145. event_data = json.loads(data)
  146. # 处理阿里云可能的错误格式
  147. if "error" in event_data:
  148. err_msg = event_data["error"].get("message", "Unknown Error")
  149. logger.error(f"[{trace_id}] 流式数据中包含错误: {err_msg}")
  150. continue
  151. choices = event_data.get("choices", [])
  152. if choices:
  153. delta = choices[0].get("delta", {})
  154. content = delta.get("content", "")
  155. if content:
  156. if first_token_time is None:
  157. first_token_time = time.time() - start_time
  158. yield (content, first_token_time)
  159. except json.JSONDecodeError:
  160. continue
  161. except UnicodeDecodeError:
  162. continue
  163. except Exception as e:
  164. logger.error(f"[{trace_id}] API 流式请求异常: {e}")
  165. raise
  166. # ==================== 6. 数据模型 ====================
  167. class CompletionConfig(BaseModel):
  168. section_path: str = Field(..., description="章节路径")
  169. current_content: str = Field(default="", description="当前已有内容")
  170. context_window: int = Field(default=2000, ge=500, le=5000)
  171. completion_mode: str = Field(default="continue", description="模式")
  172. target_length: int = Field(default=1000, ge=100, le=5000)
  173. include_references: bool = Field(default=True)
  174. style_match: bool = Field(default=True)
  175. hint_keywords: Optional[List[str]] = Field(default=None)
  176. class ProjectInfoSimple(BaseModel):
  177. project_name: str = Field(default="施工方案")
  178. construct_location: Optional[str] = Field(default=None)
  179. engineering_type: Optional[str] = Field(default=None)
  180. class ContentCompletionRequest(BaseModel):
  181. task_id: Optional[str] = Field(default=None)
  182. user_id: str = Field(...)
  183. project_info: Optional[ProjectInfoSimple] = Field(default=None)
  184. completion_config: CompletionConfig = Field(...)
  185. model_name: Optional[str] = Field(default=None)
  186. class Config: extra = "forbid"
  187. class ContentCompletionResponse(BaseModel):
  188. code: int
  189. message: str
  190. data: Optional[Dict[str, Any]] = None
  191. # ==================== 7. 业务逻辑辅助 ====================
  192. CONTENT_COMPLETION_SYSTEM_PROMPT = "你是一位专业的施工方案编写专家。请直接输出生成的内容文本,不要添加任何解释、标注或格式标记。要求生成的内容不超过100字。"
  193. def build_content_completion_prompt(project_info, section_path, section_title, current_content, completion_mode, target_length, include_references, style_match, hint_keywords, context_before="", context_after=""):
  194. parts = []
  195. parts.append(f"【项目】{project_info.get('project_name', '未知')}")
  196. parts.append(f"【章节】{section_title} ({section_path})")
  197. parts.append(f"【模式】{completion_mode} (目标:{target_length})")
  198. if context_before: parts.append(f"【前文】...{context_before[-500:]}")
  199. if current_content: parts.append(f"【当前】{current_content}")
  200. if context_after: parts.append(f"【后文】{context_after[:500]}...")
  201. parts.append("【指令】请根据上述信息继续生成专业内容,直接输出正文:")
  202. return "\n".join(parts)
  203. def extract_chunk_content(chunk: Any) -> str:
  204. if isinstance(chunk, str): return chunk
  205. if hasattr(chunk, 'content'): return str(chunk.content) if chunk.content else ""
  206. if isinstance(chunk, dict): return str(chunk.get('content', ''))
  207. return str(chunk)
  208. def validate_user_id(user_id: str):
  209. supported_users = {'user-001', 'user-002', 'user-003'}
  210. if user_id not in supported_users:
  211. raise HTTPException(status_code=403, detail={"code": "INVALID_USER", "message": "用户标识无效"})
  212. def validate_completion_config(config: CompletionConfig):
  213. if not config.section_path or not all(p.isdigit() for p in config.section_path.split(".")):
  214. raise HTTPException(status_code=400, detail={"code": "INVALID_PATH", "message": "章节路径格式错误"})
  215. def validate_request(request: ContentCompletionRequest):
  216. if not request.task_id and not request.project_info:
  217. raise HTTPException(status_code=400, detail={"code": "MISSING_INFO", "message": "缺少任务 ID 或项目信息"})
  218. def format_sse_event(event_type: str, data: str) -> str:
  219. return f"event: {event_type}\ndata: {data}\n\n"
  220. # ==================== 8. 核心流式生成逻辑 ====================
  221. async def generate_content_stream(callback_task_id, source_task_id, user_id, request, redis_client):
  222. async def is_cancelled() -> bool:
  223. if not redis_client: return False
  224. try: return await redis_client.exists(f"terminate:{callback_task_id}") > 0
  225. except: return False
  226. stream_start_time = time.time()
  227. first_token_latency: Optional[float] = None
  228. full_content_parts: List[str] = []
  229. chunk_count = 0
  230. try:
  231. yield format_sse_event("connected", json.dumps({
  232. "callback_task_id": callback_task_id, "status": "connected", "timestamp": int(time.time())
  233. }, ensure_ascii=False))
  234. project_info = request.project_info.dict() if request.project_info else {}
  235. section_title = f"章节 {request.completion_config.section_path}"
  236. user_prompt = build_content_completion_prompt(
  237. project_info=project_info,
  238. section_path=request.completion_config.section_path,
  239. section_title=section_title,
  240. current_content=request.completion_config.current_content,
  241. completion_mode=request.completion_config.completion_mode,
  242. target_length=request.completion_config.target_length,
  243. include_references=request.completion_config.include_references,
  244. style_match=request.completion_config.style_match,
  245. hint_keywords=request.completion_config.hint_keywords
  246. )
  247. yield format_sse_event("generating", json.dumps({
  248. "status": "generating",
  249. "message": f"正在调用阿里云 Qwen3 ({CustomAPIConfig.get_model_name()})...",
  250. "timestamp": int(time.time())
  251. }, ensure_ascii=False))
  252. # 执行生成
  253. if CustomAPIConfig.is_enabled():
  254. logger.info(f"[{callback_task_id}] 使用阿里云 DashScope API (模型:{CustomAPIConfig.get_model_name()})")
  255. async for content, ftl in call_custom_api_stream(
  256. prompt=user_prompt,
  257. system_prompt=CONTENT_COMPLETION_SYSTEM_PROMPT,
  258. max_tokens=min(request.completion_config.target_length, 4000),
  259. temperature=0.7,
  260. trace_id=callback_task_id
  261. ):
  262. if await is_cancelled():
  263. yield format_sse_event("cancelled", json.dumps({"status": "cancelled"}, ensure_ascii=False))
  264. return
  265. if content:
  266. full_content_parts.append(content)
  267. chunk_count += 1
  268. if first_token_latency is None:
  269. first_token_latency = ftl if ftl is not None else (time.time() - stream_start_time)
  270. logger.info(f"[{callback_task_id}] ⚡ 首字延迟: {first_token_latency:.3f}s (Model: {CustomAPIConfig.get_model_name()})")
  271. yield format_sse_event("chunk", json.dumps({
  272. "chunk": content,
  273. "first_token_latency": round(first_token_latency, 3),
  274. "timestamp": int(time.time())
  275. }, ensure_ascii=False))
  276. else:
  277. # 备用逻辑 (理论上不会触发,因为 Key 已硬编码)
  278. logger.warning(f"[{callback_task_id}] API 配置失效,回退到默认模型 (不应发生)")
  279. raise Exception("API 配置未生效,请检查 CustomAPIConfig")
  280. # 完成统计
  281. total_duration = time.time() - stream_start_time
  282. full_content = "".join(full_content_parts)
  283. logger.info(f"[{callback_task_id}] ✅ 完成 | 首字: {first_token_latency:.3f}s | 总耗时: {total_duration:.3f}s | 字数: {len(full_content)}")
  284. yield format_sse_event("completed", json.dumps({
  285. "callback_task_id": callback_task_id,
  286. "status": "completed",
  287. "metrics": {
  288. "first_token_latency": round(first_token_latency, 3) if first_token_latency else 0.0,
  289. "total_duration": round(total_duration, 3),
  290. "char_count": len(full_content),
  291. "chunk_count": chunk_count,
  292. "model_used": CustomAPIConfig.get_model_name()
  293. },
  294. "full_content": full_content,
  295. "timestamp": int(time.time())
  296. }, ensure_ascii=False))
  297. except Exception as e:
  298. logger.error(f"[{callback_task_id}] ❌ 异常: {str(e)}", exc_info=True)
  299. yield format_sse_event("error", json.dumps({"status": "error", "message": str(e)}, ensure_ascii=False))
  300. # ==================== 9. API 路由 ====================
  301. @content_completion_router.post("/content_completion")
  302. @auto_trace(generate_if_missing=True)
  303. async def content_completion(request: ContentCompletionRequest):
  304. callback_task_id = f"ctx_{uuid.uuid4().hex[:12]}"
  305. TraceContext.set_trace_id(callback_task_id)
  306. receive_time = time.time()
  307. try:
  308. validate_user_id(request.user_id)
  309. validate_completion_config(request.completion_config)
  310. validate_request(request)
  311. redis_client = await get_redis_client()
  312. logger.info(f"[{callback_task_id}] 请求接收 (预处理耗时: {(time.time()-receive_time)*1000:.1f}ms)")
  313. return StreamingResponse(
  314. generate_content_stream(callback_task_id, request.task_id, request.user_id, request, redis_client),
  315. media_type="text/event-stream",
  316. headers={
  317. "Cache-Control": "no-cache, no-store, must-revalidate",
  318. "Pragma": "no-cache",
  319. "Expires": "0",
  320. "Connection": "keep-alive",
  321. "X-Accel-Buffering": "no",
  322. "Content-Type": "text/event-stream; charset=utf-8",
  323. "Access-Control-Allow-Origin": "*"
  324. }
  325. )
  326. except HTTPException:
  327. raise
  328. except Exception as e:
  329. logger.error(f"[{callback_task_id}] 全局异常: {str(e)}")
  330. raise HTTPException(status_code=500, detail=str(e))
  331. @content_completion_router.get("/content_completion_health")
  332. async def health_check():
  333. return {
  334. "status": "healthy",
  335. "provider": "Aliyun DashScope",
  336. "current_model": CustomAPIConfig.get_model_name(),
  337. "api_url_prefix": "https://dashscope.aliyuncs.com/compatible-mode/v1"
  338. }
  339. @content_completion_router.get("/content_completion_modes", response_model=ContentCompletionResponse)
  340. async def get_modes():
  341. modes = [
  342. {"mode": "continue", "name": "续写"}, {"mode": "expand", "name": "扩写"},
  343. {"mode": "polish", "name": "润色"}, {"mode": "complete", "name": "补全"}
  344. ]
  345. return ContentCompletionResponse(code=200, message="success", data={"modes": modes})
  346. @content_completion_router.get("/content_completion_api_status", response_model=ContentCompletionResponse)
  347. async def get_api_status():
  348. enabled = CustomAPIConfig.is_enabled()
  349. return ContentCompletionResponse(
  350. code=200, message="success",
  351. data={
  352. "enabled": enabled,
  353. "provider": "Aliyun DashScope",
  354. "model": CustomAPIConfig.get_model_name()
  355. }
  356. )