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