bisheng.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. import json
  2. from datetime import datetime
  3. import httpx
  4. from app.config.config import settings
  5. from app.utils.rsa_crypto import BishengCrypto
  6. class BishengService:
  7. def __init__(self, base_url: str):
  8. self.base_url = base_url
  9. def _check_response(self, response: httpx.Response):
  10. if response.status_code not in [200, 201]:
  11. raise Exception(f"Failed to fetch data from Bisheng API: {response.text}")
  12. response_data = response.json()
  13. status_code = response_data.get("status_code", 0)
  14. if status_code != 200:
  15. raise Exception(f"Failed to fetch data from Bisheng API: {response.text}")
  16. # 检查返回的数据类型
  17. if isinstance(response_data.get("data"), dict):
  18. return response_data.get("data", {})
  19. elif isinstance(response_data.get("data"), list):
  20. return response_data.get("data", [])
  21. else:
  22. return {}
  23. async def register(self, username: str, password: str):
  24. public_key = await self.get_public_key_api()
  25. password = BishengCrypto(public_key, settings.PRIVATE_KEY).encrypt(password)
  26. async with httpx.AsyncClient() as client:
  27. response = await client.post(
  28. f"{self.base_url}/api/v1/user/regist",
  29. json={"user_name": username, "password": password},
  30. headers={'Content-Type': 'application/json'}
  31. )
  32. return self._check_response(response)
  33. async def login(self, username: str, password: str) -> str:
  34. public_key = await self.get_public_key_api()
  35. password = BishengCrypto(public_key, settings.PRIVATE_KEY).encrypt(password)
  36. async with httpx.AsyncClient() as client:
  37. response = await client.post(
  38. f"{self.base_url}/api/v1/user/login",
  39. json={"user_name": username, "password": password},
  40. headers={'Content-Type': 'application/json'}
  41. )
  42. data = self._check_response(response)
  43. return data.get('access_token')
  44. async def get_public_key_api(self) -> dict:
  45. async with httpx.AsyncClient() as client:
  46. response = await client.get(
  47. f"{self.base_url}/api/v1/user/public_key",
  48. headers={'Content-Type': 'application/json'}
  49. )
  50. data = self._check_response(response)
  51. return data.get('public_key')
  52. async def get_chat_sessions(self, token: str, page: int = 1, limit: int=100) -> list:
  53. url = f"{self.base_url}/api/v1/chat/list?page={page}&limit={limit}"
  54. headers = {'cookie': f"access_token_cookie={token};"}
  55. async with httpx.AsyncClient() as client:
  56. response = await client.get(url, headers=headers)
  57. data = self._check_response(response)
  58. result = [
  59. {
  60. "id": item["chat_id"],
  61. "name": item["latest_message"]["message"],
  62. "updated_time": int(datetime.strptime(item["update_time"], "%Y-%m-%dT%H:%M:%S").timestamp() * 1000),
  63. "update_date": item["update_time"]
  64. }
  65. for item in data
  66. if "latest_message" in item and "message" in item["latest_message"] and item["latest_message"]["message"]
  67. ]
  68. def process_name(item):
  69. message = item.get("latest_message", {}).get("message", "")
  70. name = message
  71. try:
  72. message_json = json.loads(message)
  73. if 'question' in message_json:
  74. name = message_json['question']
  75. elif 'query' in message_json:
  76. name = message_json['query']
  77. elif 'report_name' in message_json:
  78. name = message_json['report_name']
  79. except json.JSONDecodeError:
  80. pass
  81. return name
  82. result = [
  83. {
  84. "id": item["chat_id"],
  85. "name": process_name(item),
  86. "update_date": item["update_time"].replace("T", " "),
  87. "updated_time": int(datetime.strptime(item["update_time"], "%Y-%m-%dT%H:%M:%S").timestamp() * 1000)
  88. }
  89. for item in data
  90. if "latest_message" in item and "message" in item["latest_message"] and item["latest_message"]["message"]
  91. ]
  92. return result
  93. async def get_session_log(self, token: str, agent_id: str, conversation_id: str):
  94. url = (
  95. f"{self.base_url}/api/v1/chat/history?"
  96. f"flow_id={agent_id}&"
  97. f"chat_id={conversation_id}&page_size=30&id="
  98. )
  99. headers = {'cookie': f"access_token_cookie={token};"}
  100. async with httpx.AsyncClient() as client:
  101. response = await client.get(url, headers=headers)
  102. response.raise_for_status()
  103. data = self._check_response(response)
  104. session_log = [
  105. {
  106. "message": message.get("message"),
  107. "role": message.get("category"),
  108. "ts": message.get("create_time")
  109. }
  110. for message in data
  111. ]
  112. # 把session_log 按ts 升序排序
  113. session_log.sort(key=lambda x: x['ts'])
  114. return session_log
  115. async def variable_list(self, token: str, agent_id: str) -> list:
  116. url = f"{self.base_url}/api/v1/variable/list?flow_id={agent_id}"
  117. headers = {'cookie': f"access_token_cookie={token};"}
  118. async with httpx.AsyncClient() as client:
  119. response = await client.get(url, headers=headers)
  120. data = self._check_response(response)
  121. return data
  122. async def upload(self, token: str, filename: str, file: bytes) -> dict:
  123. url = f"{self.base_url}/api/v1/knowledge/upload"
  124. headers = {'cookie': f"access_token_cookie={token};"}
  125. # 创建表单数据,包含文件
  126. files = {"file": (filename, file)}
  127. async with httpx.AsyncClient() as client:
  128. response = await client.post(url, headers=headers, files=files)
  129. data = self._check_response(response)
  130. file_path = data.get("file_path", "")
  131. result = {
  132. "file_path": file_path
  133. }
  134. return result
  135. async def user_list(self, token: str) -> list:
  136. url = f"{self.base_url}/api/v1/user/list"
  137. headers = {'cookie': f"access_token_cookie={token};"}
  138. async with httpx.AsyncClient() as client:
  139. response = await client.get(url, headers=headers)
  140. data = self._check_response(response)
  141. return data
  142. async def change_password_public(self, token: str, username: str, password: str, new_password:str) -> dict:
  143. url = f"{self.base_url}/api/v1/user/change_password_public"
  144. headers = {'cookie': f"access_token_cookie={token};"}
  145. public_key = await self.get_public_key_api()
  146. password = BishengCrypto(public_key, settings.PRIVATE_KEY).encrypt(password)
  147. new_password = BishengCrypto(public_key, settings.PRIVATE_KEY).encrypt(new_password)
  148. json = {"username": username, "password": password, "new_password": new_password}
  149. async with httpx.AsyncClient() as client:
  150. response = await client.post(url, headers=headers, json=json)
  151. data = self._check_response(response)
  152. return data