content_completion.py 19 KB

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