java_client.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. import httpx
  2. from typing import Optional
  3. from app.config import settings
  4. import logging
  5. logger = logging.getLogger(__name__)
  6. class JavaClient:
  7. """Java 后端 HTTP 客户端 (单例, 复用连接池)"""
  8. _instance: Optional["JavaClient"] = None
  9. def __new__(cls):
  10. if cls._instance is None:
  11. cls._instance = super().__new__(cls)
  12. cls._instance._client = None
  13. cls._instance._base_url = settings.java_base_url
  14. return cls._instance
  15. async def _get_client(self) -> httpx.AsyncClient:
  16. if self._client is None:
  17. limits = httpx.Limits(
  18. max_connections=10,
  19. max_keepalive_connections=5,
  20. keepalive_expiry=30,
  21. )
  22. self._client = httpx.AsyncClient(
  23. base_url=self._base_url,
  24. timeout=httpx.Timeout(120.0, connect=3.0),
  25. limits=limits,
  26. )
  27. return self._client
  28. async def close(self):
  29. if self._client:
  30. await self._client.aclose()
  31. self._client = None
  32. JavaClient._instance = None
  33. async def get_published_articles(self) -> list[dict]:
  34. """拉取已发布知识库文章(分页 + records 解析,避免单次响应过大 / 返回 dict 结构)"""
  35. client = await self._get_client()
  36. page = 1
  37. size = 50
  38. records = []
  39. while True:
  40. resp = await client.post("/api/article/list", json={"status": "published", "page": page, "size": size})
  41. data = resp.json()
  42. if data.get("code") != 200:
  43. break
  44. body = data.get("data", {}) or {}
  45. items = body.get("records", []) or []
  46. records.extend(items)
  47. total = body.get("total", 0)
  48. if page * size >= int(total or 0) or not items:
  49. break
  50. page += 1
  51. return records
  52. async def search_products(self, keyword: str, limit: int = 5) -> list[dict]:
  53. client = await self._get_client()
  54. resp = await client.post("/api/product/search", json={
  55. "keyword": keyword, "status": "上架", "limit": limit
  56. })
  57. data = resp.json()
  58. if data.get("code") == 200:
  59. return data.get("data", [])
  60. return []
  61. async def search_activities(self, keyword: str, limit: int = 5) -> list[dict]:
  62. client = await self._get_client()
  63. resp = await client.post("/api/activity/search", json={
  64. "keyword": keyword, "status": "published", "limit": limit
  65. })
  66. data = resp.json()
  67. if data.get("code") == 200:
  68. return data.get("data", [])
  69. return []
  70. async def search_articles(self, keyword: str, limit: int = 5) -> list[dict]:
  71. client = await self._get_client()
  72. resp = await client.post("/api/article/search", json={
  73. "keyword": keyword, "status": "published", "limit": limit
  74. })
  75. data = resp.json()
  76. if data.get("code") == 200:
  77. return data.get("data", [])
  78. return []
  79. async def get_user_context(self, user_id: int, params: Optional[dict] = None) -> dict:
  80. client = await self._get_client()
  81. resp = await client.post(settings.effective_java_context_url, json={
  82. "user_id": str(user_id),
  83. "params": params or {},
  84. })
  85. data = resp.json()
  86. if data.get("code") == 200:
  87. return data.get("data", {})
  88. return {}
  89. async def get_microbiome_articles(self) -> list[dict]:
  90. """拉取菌群知识库文章(分页,避免单次响应过大导致 Broken pipe)"""
  91. client = await self._get_client()
  92. page = 1
  93. size = 50
  94. records = []
  95. while True:
  96. resp = await client.post("/api/microbiome/article/list",
  97. json={"page": page, "size": size, "keyword": "", "category": ""})
  98. data = resp.json()
  99. if data.get("code") != 200:
  100. break
  101. body = data.get("data", {}) or {}
  102. items = body.get("records", []) or []
  103. records.extend(items)
  104. total = body.get("total", 0)
  105. if page * size >= int(total or 0) or not items:
  106. break
  107. page += 1
  108. return records
  109. async def get_dan_knowledge_base(self) -> list[dict]:
  110. """拉取知识库内容(dan_knowledge_base 表,仅启用 status=1)"""
  111. client = await self._get_client()
  112. page = 1
  113. size = 1000
  114. records = []
  115. while True:
  116. resp = await client.post("/api/admin/knowledge-base/list", json={"page": page, "size": size, "status": 1})
  117. data = resp.json()
  118. if data.get("code") != 200:
  119. break
  120. body = data.get("data", {}) or {}
  121. items = body.get("records", []) or []
  122. records.extend(items)
  123. total = body.get("total", 0)
  124. if page * size >= int(total or 0) or not items:
  125. break
  126. page += 1
  127. return records
  128. async def get_member_reports(self, member_id: int) -> list[dict]:
  129. """获取某个家庭成员的健康报告列表"""
  130. client = await self._get_client()
  131. resp = await client.post("/api/health/report/list", json={"memberId": member_id})
  132. data = resp.json()
  133. if data.get("code") == 200:
  134. return data.get("data", [])
  135. return []
  136. async def get_report_indicators(self, report_id: int) -> list[dict]:
  137. """获取健康报告的所有指标明细"""
  138. client = await self._get_client()
  139. resp = await client.post("/api/health/report/indicator/list", json={"reportId": report_id})
  140. data = resp.json()
  141. if data.get("code") == 200:
  142. return data.get("data", [])
  143. return []
  144. async def query_health_knowledge(self, item_type: str, item_name: str) -> dict | None:
  145. """查询健康知识库中某个指标/菌属/营养素的定义"""
  146. client = await self._get_client()
  147. resp = await client.post("/api/health/knowledge/query", json={
  148. "itemType": item_type, "itemName": item_name,
  149. })
  150. data = resp.json()
  151. if data.get("code") == 200 and data.get("data"):
  152. return data["data"]
  153. return None
  154. async def batch_query_health_knowledge(self, queries: list[dict]) -> list[dict]:
  155. """批量查询健康知识库"""
  156. client = await self._get_client()
  157. resp = await client.post("/api/health/knowledge/batch-query", json={"queries": queries})
  158. data = resp.json()
  159. if data.get("code") == 200:
  160. return data.get("data", [])
  161. return []
  162. async def get_family_context(self, user_id: int, intent_type: str = "child_info", params: dict | None = None) -> dict:
  163. """获取家庭上下文数据(通过公开的 /api/ai/context 端点)"""
  164. client = await self._get_client()
  165. body = {"user_id": str(user_id), "intent_type": intent_type}
  166. if params:
  167. body["params"] = params
  168. resp = await client.post("/api/ai/context", json=body)
  169. data = resp.json()
  170. if data.get("code") == 200:
  171. return data.get("data", {})
  172. return {}
  173. async def get_member_profile(self, member_id: int) -> dict:
  174. """获取家庭成员画像快照"""
  175. client = await self._get_client()
  176. resp = await client.post("/api/profile/my", json={"memberId": member_id})
  177. data = resp.json()
  178. if data.get("code") == 200 and data.get("data"):
  179. return data["data"]
  180. return {}