loader.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. from app.tools.java_client import JavaClient
  2. from typing import Optional
  3. import logging
  4. logger = logging.getLogger(__name__)
  5. class KnowledgeLoader:
  6. """知识库加载器: 从 Java 侧拉取文章并格式化"""
  7. def __init__(self):
  8. self.java = JavaClient()
  9. async def load_all_articles(self) -> list[dict]:
  10. """获取所有已发布文章"""
  11. return await self.java.get_published_articles()
  12. async def load_updated_since(self, since: str) -> list[dict]:
  13. """增量获取: 获取某个时间后更新的文章"""
  14. try:
  15. client = await self.java._get_client()
  16. resp = await client.post("/api/article/updated-since", json={
  17. "since": since,
  18. "status": "published",
  19. })
  20. data = resp.json()
  21. if data.get("code") == 200:
  22. body = data.get("data", [])
  23. # 兼容两种响应:直接 list 或 {records:[...]} 分页结构
  24. if isinstance(body, dict):
  25. body = body.get("records", []) or []
  26. return body
  27. except Exception as e:
  28. logger.warning("增量获取文章失败: %s", e)
  29. return []
  30. def format_for_indexing(self, articles: list[dict]) -> list[dict]:
  31. """将文章格式化为可索引的文档"""
  32. docs = []
  33. for article in articles:
  34. content = f"{article.get('title', '')}\n\n{article.get('summary', '')}\n\n{article.get('content', '')}"
  35. docs.append({
  36. "id": f"article_{article['id']}",
  37. "content": content,
  38. "metadata": {
  39. "source": "article",
  40. "article_id": article["id"],
  41. "title": article.get("title", ""),
  42. "tags": article.get("tags", ""),
  43. "updated_at": article.get("updatedAt", ""),
  44. },
  45. })
  46. return docs