deepseek_service.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. """
  2. DeepSeek API 服务(阿里云百炼平台)
  3. 用于调用 DeepSeek 模型进行 NER 提取
  4. """
  5. import json
  6. import re
  7. import uuid
  8. import httpx
  9. from typing import List, Optional, Dict, Any
  10. from loguru import logger
  11. from ..config import settings
  12. from ..models import EntityInfo, PositionInfo
  13. class DeepSeekService:
  14. """DeepSeek API 服务"""
  15. def __init__(self):
  16. self.api_key = settings.deepseek_api_key
  17. self.base_url = settings.deepseek_base_url
  18. self.model = settings.deepseek_model
  19. self.timeout = settings.deepseek_timeout
  20. self.temperature = settings.deepseek_temperature
  21. self.max_tokens = settings.deepseek_max_tokens
  22. self.max_retries = settings.deepseek_max_retries
  23. self.chunk_size = settings.chunk_size
  24. self.chunk_overlap = settings.chunk_overlap
  25. logger.info(f"初始化 DeepSeek 服务: model={self.model}, base_url={self.base_url}")
  26. def _split_text(self, text: str) -> List[Dict[str, Any]]:
  27. """
  28. 将长文本分割成多个块
  29. """
  30. if len(text) <= self.chunk_size:
  31. return [{"text": text, "start_pos": 0, "end_pos": len(text)}]
  32. chunks = []
  33. start = 0
  34. while start < len(text):
  35. end = min(start + self.chunk_size, len(text))
  36. # 尝试在句号、换行处分割
  37. if end < len(text):
  38. for sep in ['\n\n', '\n', '。', ';', '!', '?', '.']:
  39. sep_pos = text.rfind(sep, start + self.chunk_size // 2, end)
  40. if sep_pos > start:
  41. end = sep_pos + len(sep)
  42. break
  43. chunk_text = text[start:end]
  44. chunks.append({
  45. "text": chunk_text,
  46. "start_pos": start,
  47. "end_pos": end
  48. })
  49. start = end - self.chunk_overlap if end < len(text) else end
  50. logger.info(f"文本分割完成: 总长度={len(text)}, 分块数={len(chunks)}")
  51. return chunks
  52. def _build_ner_prompt(self, text: str, entity_types: Optional[List[str]] = None) -> str:
  53. """
  54. 构建 NER 提取的 Prompt
  55. """
  56. types = entity_types or settings.entity_types
  57. prompt = f"""你是专业的命名实体识别(NER)专家。请从以下文本中提取有意义的命名实体。
  58. ## 实体类型定义
  59. 1. **PERSON** - 人名
  60. - 包括:姓名、职务+姓名(如"张总"、"李工程师")
  61. - 不包括:职位本身(如"经理"、"主任")
  62. 2. **ORG** - 机构/组织
  63. - 包括:公司、政府机关、协会、院校等完整名称
  64. - 例如:"中国电建集团成都勘测设计研究院有限公司"、"国家能源局"
  65. - 不包括:简称(如"公司"、"集团"),除非是特定缩写(如"成都院")
  66. 3. **LOC** - 地点/位置
  67. - 包括:省市区县、具体地址、工程位置
  68. - 例如:"四川省成都市"、"龙滩水电站"
  69. 4. **DATE** - 日期/时间
  70. - 包括:具体日期、时间段、年份
  71. - 例如:"2024年7月13日"、"2019年版"
  72. - 不包括:单独的年份数字
  73. 5. **NUMBER** - 有意义的数值
  74. - 包括:带单位的数量、金额、评分、比例
  75. - 例如:"93.33分"、"7000名"、"70多年"、"5个"
  76. - **不包括**:章节编号(如"1.1"、"第3章")、纯序号(如"16"、"17")、表格序号
  77. 6. **PROJECT** - 项目/工程名称
  78. - 包括:具体项目名称、工程名称
  79. - 例如:"白鹤滩水电站工程"、"安全生产标准化建设项目"
  80. - **不包括**:文件编号(如"AY-BZ-0092-2024")、标准编号
  81. 7. **METHOD** - 方法/标准/规范
  82. - 包括:技术标准、管理办法、评价标准的完整名称
  83. - 例如:"电力建设企业安全生产标准化评价标准"、"安全生产风险抵押金管理办法"
  84. - **不包括**:编号(如"SQE.01C0213"、"中电建协〔2014〕24号文")
  85. 8. **DEVICE** - 设备/系统
  86. - 包括:设备名称、信息系统名称
  87. - 例如:"OA系统"、"QHSE系统"、"造槽机"
  88. ## 重要规则
  89. 1. **只提取有实际意义的实体**,忽略:
  90. - 章节编号(如"1"、"1.1"、"第一章")
  91. - 表格序号
  92. - 单独的数字(如"16"、"17")
  93. - 文件编号和标准编号(归类为无意义数据,不要提取)
  94. 2. **实体边界要准确**,提取完整的名称而非片段
  95. 3. **去除重复实体**,相同的实体只返回一次
  96. 4. **charStart和charEnd必须准确**,对应实体在原文中的字符位置(从0开始)
  97. ## 输出格式
  98. 直接输出JSON,格式如下:
  99. {{"entities": [{{"name": "实体名称", "type": "实体类型", "charStart": 起始位置, "charEnd": 结束位置}}]}}
  100. ## 待处理文本
  101. {text}
  102. 请直接输出JSON:"""
  103. return prompt
  104. async def _call_api(self, prompt: str) -> Optional[str]:
  105. """
  106. 调用 DeepSeek API(OpenAI 兼容格式)
  107. """
  108. url = f"{self.base_url}/v1/chat/completions"
  109. headers = {
  110. "Authorization": f"Bearer {self.api_key}",
  111. "Content-Type": "application/json"
  112. }
  113. payload = {
  114. "model": self.model,
  115. "messages": [
  116. {
  117. "role": "user",
  118. "content": prompt
  119. }
  120. ],
  121. "temperature": self.temperature,
  122. "max_tokens": self.max_tokens,
  123. }
  124. for attempt in range(self.max_retries):
  125. try:
  126. async with httpx.AsyncClient(timeout=self.timeout) as client:
  127. response = await client.post(url, headers=headers, json=payload)
  128. response.raise_for_status()
  129. result = response.json()
  130. # OpenAI 格式响应
  131. choices = result.get("choices", [])
  132. if choices:
  133. message = choices[0].get("message", {})
  134. return message.get("content", "")
  135. return None
  136. except httpx.TimeoutException:
  137. logger.warning(f"DeepSeek API 请求超时 (尝试 {attempt + 1}/{self.max_retries})")
  138. if attempt == self.max_retries - 1:
  139. logger.error(f"DeepSeek API 请求超时: timeout={self.timeout}s")
  140. return None
  141. except httpx.HTTPStatusError as e:
  142. logger.error(f"DeepSeek API HTTP 错误: {e.response.status_code} - {e.response.text}")
  143. return None
  144. except Exception as e:
  145. logger.error(f"DeepSeek API 请求失败: {e}")
  146. if attempt == self.max_retries - 1:
  147. return None
  148. return None
  149. def _parse_response(self, response: str, chunk_start_pos: int = 0) -> List[EntityInfo]:
  150. """
  151. 解析 API 返回的 JSON 结果
  152. """
  153. entities = []
  154. try:
  155. # 移除 markdown code block 标记
  156. response = re.sub(r'```json\s*', '', response)
  157. response = re.sub(r'```\s*', '', response)
  158. response = response.strip()
  159. # 方法1:直接解析
  160. data = None
  161. try:
  162. data = json.loads(response)
  163. except json.JSONDecodeError:
  164. pass
  165. # 方法2:查找 JSON 对象
  166. if not data or "entities" not in data:
  167. json_match = re.search(r'\{\s*"entities"\s*:\s*\[[\s\S]*\]\s*\}', response)
  168. if json_match:
  169. try:
  170. data = json.loads(json_match.group())
  171. except json.JSONDecodeError:
  172. pass
  173. if not data or "entities" not in data:
  174. logger.warning(f"未找到有效的 entities JSON, response={response[:300]}...")
  175. return entities
  176. entity_list = data.get("entities", [])
  177. for item in entity_list:
  178. name = item.get("name", "").strip()
  179. entity_type = item.get("type", "").upper()
  180. char_start = item.get("charStart", 0)
  181. char_end = item.get("charEnd", 0)
  182. if not name or len(name) < 2:
  183. continue
  184. # 校正位置
  185. adjusted_start = char_start + chunk_start_pos
  186. adjusted_end = char_end + chunk_start_pos
  187. entity = EntityInfo(
  188. name=name,
  189. type=entity_type,
  190. value=name,
  191. position=PositionInfo(
  192. char_start=adjusted_start,
  193. char_end=adjusted_end,
  194. line=1
  195. ),
  196. confidence=0.95, # DeepSeek 置信度较高
  197. temp_id=str(uuid.uuid4())[:8]
  198. )
  199. entities.append(entity)
  200. except Exception as e:
  201. logger.error(f"解析响应失败: {e}")
  202. return entities
  203. async def extract_entities(
  204. self,
  205. text: str,
  206. entity_types: Optional[List[str]] = None
  207. ) -> List[EntityInfo]:
  208. """
  209. 使用 DeepSeek API 提取实体
  210. """
  211. if not text or not text.strip():
  212. return []
  213. # 分割长文本
  214. chunks = self._split_text(text)
  215. all_entities = []
  216. seen_entities = set()
  217. for i, chunk in enumerate(chunks):
  218. logger.info(f"处理分块 {i+1}/{len(chunks)}: 长度={len(chunk['text'])}")
  219. prompt = self._build_ner_prompt(chunk["text"], entity_types)
  220. response = await self._call_api(prompt)
  221. if not response:
  222. logger.warning(f"分块 {i+1} API 返回为空")
  223. continue
  224. logger.debug(f"分块 {i+1} API 响应: {response[:500]}...")
  225. entities = self._parse_response(response, chunk["start_pos"])
  226. # 去重
  227. for entity in entities:
  228. entity_key = f"{entity.type}:{entity.name}"
  229. if entity_key not in seen_entities:
  230. seen_entities.add(entity_key)
  231. all_entities.append(entity)
  232. logger.info(f"分块 {i+1} 提取实体: {len(entities)} 个")
  233. logger.info(f"DeepSeek NER 提取完成: 总实体数={len(all_entities)}")
  234. return all_entities
  235. async def extract_entities_with_progress(
  236. self,
  237. text: str,
  238. entity_types: Optional[List[str]] = None
  239. ):
  240. """
  241. 使用 DeepSeek API 提取实体(带进度生成器)
  242. Yields:
  243. SSE 事件字符串
  244. """
  245. import json
  246. async def sse_event(event: str, data: dict):
  247. return f"event: {event}\ndata: {json.dumps(data, ensure_ascii=False)}\n\n"
  248. if not text or not text.strip():
  249. yield await sse_event("complete", {"entities": [], "total_entities": 0})
  250. return
  251. # 分割长文本
  252. chunks = self._split_text(text)
  253. total_chunks = len(chunks)
  254. all_entities = []
  255. seen_entities = set()
  256. for i, chunk in enumerate(chunks):
  257. chunk_index = i + 1
  258. logger.info(f"处理分块 {chunk_index}/{total_chunks}: 长度={len(chunk['text'])}")
  259. # 发送进度事件
  260. yield await sse_event("progress", {
  261. "chunk_index": chunk_index,
  262. "total_chunks": total_chunks,
  263. "chunk_length": len(chunk['text']),
  264. "total_entities": len(all_entities),
  265. "progress_percent": int((chunk_index - 1) / total_chunks * 100),
  266. "message": f"正在处理第 {chunk_index}/{total_chunks} 个文本块..."
  267. })
  268. prompt = self._build_ner_prompt(chunk["text"], entity_types)
  269. response = await self._call_api(prompt)
  270. if not response:
  271. logger.warning(f"分块 {chunk_index} API 返回为空")
  272. continue
  273. logger.debug(f"分块 {chunk_index} API 响应: {response[:500]}...")
  274. entities = self._parse_response(response, chunk["start_pos"])
  275. # 去重并收集新实体
  276. new_entities = []
  277. for entity in entities:
  278. entity_key = f"{entity.type}:{entity.name}"
  279. if entity_key not in seen_entities:
  280. seen_entities.add(entity_key)
  281. all_entities.append(entity)
  282. new_entities.append(entity)
  283. logger.info(f"分块 {chunk_index} 提取实体: {len(entities)} 个, 新增: {len(new_entities)} 个")
  284. # 发送分块完成事件
  285. yield await sse_event("chunk_complete", {
  286. "chunk_index": chunk_index,
  287. "total_chunks": total_chunks,
  288. "chunk_entities": len(entities),
  289. "new_entities": len(new_entities),
  290. "total_entities": len(all_entities),
  291. "progress_percent": int(chunk_index / total_chunks * 100)
  292. })
  293. logger.info(f"DeepSeek NER 提取完成: 总实体数={len(all_entities)}")
  294. # 发送实体数据事件(供调用方获取实体列表)
  295. yield await sse_event("entities_data", {
  296. "entities": [entity.model_dump(by_alias=True) for entity in all_entities],
  297. "total_entities": len(all_entities)
  298. })
  299. async def check_health(self) -> bool:
  300. """
  301. 检查 DeepSeek API 是否可用
  302. """
  303. try:
  304. url = f"{self.base_url}/v1/models"
  305. headers = {
  306. "Authorization": f"Bearer {self.api_key}"
  307. }
  308. async with httpx.AsyncClient(timeout=10) as client:
  309. response = await client.get(url, headers=headers)
  310. return response.status_code == 200
  311. except Exception:
  312. return False
  313. # 创建单例
  314. deepseek_service = DeepSeekService()