zhaoqingang
2025-04-08 0650b889a36d9b9fd42415b9b9819676f839ae9b
app/service/bisheng.py
@@ -1,6 +1,8 @@
import json
from datetime import datetime
import httpx
from Log import logger
from app.config.config import settings
from app.utils.rsa_crypto import BishengCrypto
@@ -24,7 +26,7 @@
        else:
            return {}
    async def register(self, username: str, password: str):
    async def register(self, username: str, password: str, token:str=""):
        public_key = await self.get_public_key_api()
        password = BishengCrypto(public_key, settings.PRIVATE_KEY).encrypt(password)
        async with httpx.AsyncClient() as client:
@@ -33,7 +35,10 @@
                json={"user_name": username, "password": password},
                headers={'Content-Type': 'application/json'}
            )
            return self._check_response(response)
            res = self._check_response(response)
            if isinstance(res, dict):
                res["id"] = res.get("user_id")
            return res
    async def login(self, username: str, password: str) -> str:
        public_key = await self.get_public_key_api()
@@ -56,21 +61,55 @@
            data = self._check_response(response)
            return data.get('public_key')
    async def get_chat_sessions(self, token: str) -> list:
        url = f"{self.base_url}/api/v1/chat/list?page=1&limit=40"
    async def get_chat_sessions(self, token: str, agent_id,page: int = 1, limit: int=1000) -> list:
        url = f"{self.base_url}/api/v1/chat/list?page={page}&limit={limit}"
        headers = {'cookie': f"access_token_cookie={token};"}
        async with httpx.AsyncClient() as client:
            response = await client.get(url, headers=headers)
            data = self._check_response(response)
            # print(data)
            # result = [
            #     {
            #         "id": item["chat_id"],
            #         "name": item["latest_message"]["message"],
            #         "updated_time": int(datetime.strptime(item["update_time"], "%Y-%m-%dT%H:%M:%S").timestamp() * 1000),
            #         "update_date": item["update_time"]
            #     }
            #     for item in data
            #     if "latest_message" in item and "message" in item["latest_message"] and item["latest_message"]["message"]
            # ]
            def process_name(item):
                # logger.error("-----------------------process_name-------------------------------------")
                # logger.error(item)
                message = item.get("latest_message", {}).get("message", "")
                name = message
                try:
                    message_json = json.loads(message)
                    if 'question' in message_json:
                        name = message_json['question']
                    elif 'query' in message_json:
                        name = message_json['query']
                    elif 'report_name' in message_json:
                        name = message_json['report_name']
                except Exception as e:
                    pass
                if not name:
                    name = item.get("flow_name")
                return name[:50]
            result = [
                {
                    "id": item["chat_id"],
                    "name": item["latest_message"]["message"],
                    "name": process_name(item),
                    "update_date": item["update_time"].replace("T", " "),
                    "updated_time": int(datetime.strptime(item["update_time"], "%Y-%m-%dT%H:%M:%S").timestamp() * 1000)
                }
                for item in data
                if item.get("flow_id") == agent_id #if "latest_message" in item and "message" in item["latest_message"] and item["latest_message"]["message"] and
            ]
            return result
    async def get_session_log(self, token: str, agent_id: str, conversation_id: str):
@@ -85,13 +124,14 @@
            response.raise_for_status()
            data = self._check_response(response)
            session_log = [
                    {
                        "message": message.get("message"),
                        "role": message.get("category"),
                        "ts": message.get("create_time")
                    }
                    for message in data
                ]
                {
                    "message":message.get("message", "") if message.get("message", "") else message.get("intermediate_steps", ""),
                    "files": message.get("files", ""),
                    "role": "question" if message.get("category") == "question" and message.get("message", "") else "answer",
                    "ts": message.get("create_time")
                }
                for message in data if message.get("category") != "system"
            ]
            # 把session_log 按ts 升序排序
            session_log.sort(key=lambda x: x['ts'])
@@ -128,3 +168,17 @@
            response = await client.get(url, headers=headers)
            data = self._check_response(response)
            return data
    async def change_password_public(self, token: str, username: str, password: str, new_password:str) -> dict:
        url = f"{self.base_url}/api/v1/user/change_password_public"
        headers = {'cookie': f"access_token_cookie={token};"}
        public_key = await self.get_public_key_api()
        password = BishengCrypto(public_key, settings.PRIVATE_KEY).encrypt(password)
        new_password = BishengCrypto(public_key, settings.PRIVATE_KEY).encrypt(new_password)
        json = {"username": username, "password": password, "new_password": new_password}
        async with httpx.AsyncClient() as client:
            response = await client.post(url, headers=headers, json=json)
            data = self._check_response(response)
            return data