bisheng.py 6.1 KB

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