bisheng.py 8.1 KB

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