bisheng.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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):
  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. return self._check_response(response)
  34. async def login(self, username: str, password: str) -> str:
  35. public_key = await self.get_public_key_api()
  36. password = BishengCrypto(public_key, settings.PRIVATE_KEY).encrypt(password)
  37. async with httpx.AsyncClient() as client:
  38. response = await client.post(
  39. f"{self.base_url}/api/v1/user/login",
  40. json={"user_name": username, "password": password},
  41. headers={'Content-Type': 'application/json'}
  42. )
  43. data = self._check_response(response)
  44. return data.get('access_token')
  45. async def get_public_key_api(self) -> dict:
  46. async with httpx.AsyncClient() as client:
  47. response = await client.get(
  48. f"{self.base_url}/api/v1/user/public_key",
  49. headers={'Content-Type': 'application/json'}
  50. )
  51. data = self._check_response(response)
  52. return data.get('public_key')
  53. async def get_chat_sessions(self, token: str, agent_id,page: int = 1, limit: int=1000) -> list:
  54. url = f"{self.base_url}/api/v1/chat/list?page={page}&limit={limit}"
  55. headers = {'cookie': f"access_token_cookie={token};"}
  56. async with httpx.AsyncClient() as client:
  57. response = await client.get(url, headers=headers)
  58. data = self._check_response(response)
  59. # print(data)
  60. # result = [
  61. # {
  62. # "id": item["chat_id"],
  63. # "name": item["latest_message"]["message"],
  64. # "updated_time": int(datetime.strptime(item["update_time"], "%Y-%m-%dT%H:%M:%S").timestamp() * 1000),
  65. # "update_date": item["update_time"]
  66. # }
  67. # for item in data
  68. # if "latest_message" in item and "message" in item["latest_message"] and item["latest_message"]["message"]
  69. # ]
  70. def process_name(item):
  71. # logger.error("-----------------------process_name-------------------------------------")
  72. # logger.error(item)
  73. message = item.get("latest_message", {}).get("message", "")
  74. name = message
  75. try:
  76. message_json = json.loads(message)
  77. if 'question' in message_json:
  78. name = message_json['question']
  79. elif 'query' in message_json:
  80. name = message_json['query']
  81. elif 'report_name' in message_json:
  82. name = message_json['report_name']
  83. except Exception as e:
  84. pass
  85. if not name:
  86. name = item.get("flow_name")
  87. return name[:50]
  88. result = [
  89. {
  90. "id": item["chat_id"],
  91. "name": process_name(item),
  92. "update_date": item["update_time"].replace("T", " "),
  93. "updated_time": int(datetime.strptime(item["update_time"], "%Y-%m-%dT%H:%M:%S").timestamp() * 1000)
  94. }
  95. for item in data
  96. if item.get("flow_id") == agent_id #if "latest_message" in item and "message" in item["latest_message"] and item["latest_message"]["message"] and
  97. ]
  98. return result
  99. async def get_session_log(self, token: str, agent_id: str, conversation_id: str):
  100. url = (
  101. f"{self.base_url}/api/v1/chat/history?"
  102. f"flow_id={agent_id}&"
  103. f"chat_id={conversation_id}&page_size=30&id="
  104. )
  105. headers = {'cookie': f"access_token_cookie={token};"}
  106. async with httpx.AsyncClient() as client:
  107. response = await client.get(url, headers=headers)
  108. response.raise_for_status()
  109. data = self._check_response(response)
  110. session_log = [
  111. {
  112. "message":message.get("message", "") if message.get("message", "") else message.get("intermediate_steps", ""),
  113. "files": message.get("files", ""),
  114. "role": "question" if message.get("category") == "question" and message.get("message", "") else "answer",
  115. "ts": message.get("create_time")
  116. }
  117. for message in data if message.get("category") != "system"
  118. ]
  119. # 把session_log 按ts 升序排序
  120. session_log.sort(key=lambda x: x['ts'])
  121. return session_log
  122. async def variable_list(self, token: str, agent_id: str) -> list:
  123. url = f"{self.base_url}/api/v1/variable/list?flow_id={agent_id}"
  124. headers = {'cookie': f"access_token_cookie={token};"}
  125. async with httpx.AsyncClient() as client:
  126. response = await client.get(url, headers=headers)
  127. data = self._check_response(response)
  128. return data
  129. async def upload(self, token: str, filename: str, file: bytes) -> dict:
  130. url = f"{self.base_url}/api/v1/knowledge/upload"
  131. headers = {'cookie': f"access_token_cookie={token};"}
  132. # 创建表单数据,包含文件
  133. files = {"file": (filename, file)}
  134. async with httpx.AsyncClient() as client:
  135. response = await client.post(url, headers=headers, files=files)
  136. data = self._check_response(response)
  137. file_path = data.get("file_path", "")
  138. result = {
  139. "file_path": file_path
  140. }
  141. return result
  142. async def user_list(self, token: str) -> list:
  143. url = f"{self.base_url}/api/v1/user/list"
  144. headers = {'cookie': f"access_token_cookie={token};"}
  145. async with httpx.AsyncClient() as client:
  146. response = await client.get(url, headers=headers)
  147. data = self._check_response(response)
  148. return data
  149. async def change_password_public(self, token: str, username: str, password: str, new_password:str) -> dict:
  150. url = f"{self.base_url}/api/v1/user/change_password_public"
  151. headers = {'cookie': f"access_token_cookie={token};"}
  152. public_key = await self.get_public_key_api()
  153. password = BishengCrypto(public_key, settings.PRIVATE_KEY).encrypt(password)
  154. new_password = BishengCrypto(public_key, settings.PRIVATE_KEY).encrypt(new_password)
  155. json = {"username": username, "password": password, "new_password": new_password}
  156. async with httpx.AsyncClient() as client:
  157. response = await client.post(url, headers=headers, json=json)
  158. data = self._check_response(response)
  159. return data