llm_classifier.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. from typing import List
  2. from applications.config import Chunk
  3. from applications.api import fetch_deepseek_completion
  4. class LLMClassifier:
  5. @staticmethod
  6. def generate_prompt(chunk_text: str) -> str:
  7. raw_prompt = """
  8. 你是一个文本分析助手。
  9. 我会给你一段文本,请你输出以下信息:
  10. 1. **主题标签 (topic)**:一句话概括文本主题
  11. 2. **关键词 (keywords)**:3-5 个,便于检索
  12. 3. **摘要 (summary)**:50字以内简要说明
  13. 4. **特征 (features)**:包含以下子字段
  14. - domain: 该文本所属领域(如:AI 技术、体育、金融)
  15. - task_type: 文本主要任务类型(如:解释、教学、动作描述、方法提出)
  16. - concepts: 涉及的核心知识点或概念
  17. - questions: 文本中隐含或显式的问题
  18. 请用 JSON 格式输出,例如:
  19. {
  20. "topic": "RAG 技术与分块策略",
  21. "summary": "介绍RAG技术并提出主题感知的分块方法。",
  22. "domain": "AI 技术",
  23. "task_type": "方法提出",
  24. "keywords": ["RAG", "检索增强", "文本分块", "知识图谱"],
  25. "concepts": ["RAG", "文本分块", "知识图谱"],
  26. "questions": ["如何提升RAG的检索效果?"]
  27. }
  28. 下面是文本:
  29. """
  30. return raw_prompt.strip() + chunk_text
  31. async def classify_chunk(self, chunk: Chunk) -> Chunk:
  32. text = chunk.text.strip()
  33. prompt = self.generate_prompt(text)
  34. response = await fetch_deepseek_completion(
  35. model="DeepSeek-V3", prompt=prompt, output_type="json"
  36. )
  37. return Chunk(
  38. chunk_id=chunk.chunk_id,
  39. doc_id=chunk.doc_id,
  40. text=text,
  41. tokens=chunk.tokens,
  42. topic_purity=chunk.topic_purity,
  43. summary=response["summary"],
  44. topic=response["topic"],
  45. domain=response["domain"],
  46. task_type=response["task_type"],
  47. concepts=response["concepts"],
  48. keywords=response["keywords"],
  49. questions=response["questions"],
  50. )
  51. async def classify_chunk_by_topic(self, chunk_list: List[Chunk]) -> List[Chunk]:
  52. return [await self.classify_chunk(chunk) for chunk in chunk_list]