loader.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. return data.get("data", [])
  23. except Exception as e:
  24. logger.warning("增量获取文章失败: %s", e)
  25. return []
  26. def format_for_indexing(self, articles: list[dict]) -> list[dict]:
  27. """将文章格式化为可索引的文档"""
  28. docs = []
  29. for article in articles:
  30. content = f"{article.get('title', '')}\n\n{article.get('summary', '')}\n\n{article.get('content', '')}"
  31. docs.append({
  32. "id": f"article_{article['id']}",
  33. "content": content,
  34. "metadata": {
  35. "source": "article",
  36. "article_id": article["id"],
  37. "title": article.get("title", ""),
  38. "tags": article.get("tags", ""),
  39. "updated_at": article.get("updatedAt", ""),
  40. },
  41. })
  42. return docs