llm_classifier.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. **领域 (domain)**:该文本所属领域(如:AI 技术、体育、金融)
  14. 5. **任务类型 (task_type)**:文本主要任务类型(如:解释、教学、动作描述、方法提出)
  15. 6. **核心知识点 (concepts)**:涉及的核心知识点或概念
  16. 7. **显示/隐式问题 (questions)**:文本中隐含或显式的问题
  17. 请用 JSON 格式输出,例如:
  18. {
  19. "topic": "RAG 技术与分块策略",
  20. "summary": "介绍RAG技术并提出主题感知的分块方法。",
  21. "domain": "AI 技术",
  22. "task_type": "方法提出",
  23. "keywords": ["RAG", "检索增强", "文本分块", "知识图谱"],
  24. "concepts": ["RAG", "文本分块", "知识图谱"],
  25. "questions": ["如何提升RAG的检索效果?"]
  26. }
  27. 下面是文本:
  28. """
  29. return raw_prompt.strip() + chunk_text
  30. async def classify_chunk(self, chunk: Chunk) -> Chunk:
  31. text = chunk.text.strip()
  32. prompt = self.generate_prompt(text)
  33. response = await fetch_deepseek_completion(
  34. model="DeepSeek-V3", prompt=prompt, output_type="json"
  35. )
  36. return Chunk(
  37. chunk_id=chunk.chunk_id,
  38. doc_id=chunk.doc_id,
  39. text=text,
  40. tokens=chunk.tokens,
  41. topic_purity=chunk.topic_purity,
  42. summary=response.get("summary"),
  43. topic=response.get("topic"),
  44. domain=response.get("domain"),
  45. task_type=response.get("task_type"),
  46. concepts=response.get("concepts", []),
  47. keywords=response.get("keywords", []),
  48. questions=response.get("questions", []),
  49. )
  50. async def classify_chunk_by_topic(self, chunk_list: List[Chunk]) -> List[Chunk]:
  51. return [await self.classify_chunk(chunk) for chunk in chunk_list]