zhaoqingang
2025-04-10 abb91124a4372b0efe5ab1b7aa25859c635d30eb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
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
 
 
class BishengService:
    def __init__(self, base_url: str):
        self.base_url = base_url
 
    def _check_response(self, response: httpx.Response):
        if response.status_code not in [200, 201]:
            raise Exception(f"Failed to fetch data from Bisheng API: {response.text}")
        response_data = response.json()
        status_code = response_data.get("status_code", 0)
        if status_code != 200:
            raise Exception(f"Failed to fetch data from Bisheng API: {response.text}")
        # 检查返回的数据类型
        if isinstance(response_data.get("data"), dict):
            return response_data.get("data", {})
        elif isinstance(response_data.get("data"), list):
            return response_data.get("data", [])
        else:
            return {}
 
    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:
            response = await client.post(
                f"{self.base_url}/api/v1/user/regist",
                json={"user_name": username, "password": password},
                headers={'Content-Type': 'application/json'}
            )
            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()
        password = BishengCrypto(public_key, settings.PRIVATE_KEY).encrypt(password)
        async with httpx.AsyncClient() as client:
            response = await client.post(
                f"{self.base_url}/api/v1/user/login",
                json={"user_name": username, "password": password},
                headers={'Content-Type': 'application/json'}
            )
            data = self._check_response(response)
            return data.get('access_token')
 
    async def get_public_key_api(self) -> dict:
        async with httpx.AsyncClient() as client:
            response = await client.get(
                f"{self.base_url}/api/v1/user/public_key",
                headers={'Content-Type': 'application/json'}
            )
            data = self._check_response(response)
            return data.get('public_key')
 
    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": 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):
        url = (
            f"{self.base_url}/api/v1/chat/history?"
            f"flow_id={agent_id}&"
            f"chat_id={conversation_id}&page_size=30&id="
        )
        headers = {'cookie': f"access_token_cookie={token};"}
        async with httpx.AsyncClient() as client:
            response = await client.get(url, headers=headers)
            response.raise_for_status()
            data = self._check_response(response)
            session_log = [
                {
                    "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'])
            return session_log
 
    async def variable_list(self, token: str, agent_id: str) -> list:
        url = f"{self.base_url}/api/v1/variable/list?flow_id={agent_id}"
        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)
            return data
 
    async def upload(self, token: str, filename: str, file: bytes) -> dict:
        url = f"{self.base_url}/api/v1/knowledge/upload"
        headers = {'cookie': f"access_token_cookie={token};"}
 
        # 创建表单数据,包含文件
        files = {"file": (filename, file)}
        async with httpx.AsyncClient() as client:
            response = await client.post(url, headers=headers, files=files)
            data = self._check_response(response)
            file_path = data.get("file_path", "")
            result = {
                "file_path": file_path
            }
 
            return result
 
    async def user_list(self, token: str) -> list:
        url = f"{self.base_url}/api/v1/user/list"
        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)
            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