zhaoqingang
2024-11-25 8804c88450e4a1b6c8ab2ce1b433d073c4a9624d
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
import json
from datetime import datetime
 
import httpx
from typing import Union, Dict, List
from fastapi import HTTPException
from starlette import status
 
from Log import logger
from app.config.config import settings
from app.utils.rsa_crypto import RagflowCrypto
 
 
class DifyService:
    def __init__(self, base_url: str):
        self.base_url = base_url
 
    def _handle_response(self, response: httpx.Response) -> Union[Dict, List]:
        if response.status_code != 200:
            return {}
 
        data = response.json()
        ret_code = data.get("retcode")
        if ret_code == 401:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="登录过期",
            )
        if ret_code != 0:
            return {}
 
        # 检查返回的数据类型
        if isinstance(data.get("data"), dict):
            return data.get("data", {})
        elif isinstance(data.get("data"), list):
            return data.get("data", [])
        else:
            return {}
 
    async def register(self, username: str, password: str):
        password = RagflowCrypto(settings.PUBLIC_KEY, settings.PRIVATE_KEY).encrypt(password)
        async with httpx.AsyncClient() as client:
            response = await client.post(
                f"{self.base_url}/v1/user/register",
                headers={'Content-Type': 'application/json'},
                json={"nickname": username, "email":  f"{username}@example.com", "password": password}
            )
            if response.status_code != 200:
                raise Exception(f"Ragflow registration failed: {response.text}")
            return self._handle_response(response)
 
    async def login(self, username: str, password: str) -> str:
        password = RagflowCrypto(settings.PUBLIC_KEY, settings.PRIVATE_KEY).encrypt(password)
        async with httpx.AsyncClient() as client:
            response = await client.post(
                f"{self.base_url}/v1/user/login",
                headers={'Content-Type': 'application/json'},
                json={"email": f"{username}@example.com", "password": password}
            )
            if response.status_code != 200:
                raise Exception(f"Ragflow login failed: {response.text}")
            authorization = response.headers.get('Authorization')
            if not authorization:
                raise Exception("Authorization header not found in response")
            return authorization
 
    async def chat(self, token: str, user_id: int,  message: str, upload_file_id: str, conversation_id: str):
 
        target_url = f"{self.base_url}/v1/chat-messages"
        files = []
        if upload_file_id:
            files = [
                {
                    "type": "image",
                    "transfer_method": "local_file",
                    "url": "",
                    "upload_file_id": upload_file_id
                }
            ]
        data = {
            "inputs": {},
            "query": message,
            "response_mode": "streaming",
            "conversation_id": "",
            "user": str(user_id),
            "files": files
        }
 
        async with httpx.AsyncClient(timeout=300.0) as client:
            headers = {
                'Content-Type': 'application/json',
                'Authorization': f'Bearer {token}'
            }
            async with client.stream("POST", target_url, data=json.dumps(data), headers=headers) as response:
                if response.status_code == 200:
                    try:
                        async for answer in response.aiter_text():
                            # print(f"response of ragflow chat: {answer}")
                            yield answer
                    except GeneratorExit as e:
                        print(e)
                        return
                else:
                    yield f"Error: {response.status_code}"
 
 
 
    async def get_session_history(self, token: str, chat_id: str, is_all: int=0):
        url = f"{self.base_url}/v1/conversation/get?conversation_id={chat_id}"
        headers = {"Authorization": token}
        async with httpx.AsyncClient() as client:
            response = await client.get(url, headers=headers)
            data = self._handle_response(response)
            # print("----------------data----------------------:", data)
            if is_all:
                return data
            return data.get("message", [])
 
    async def upload(self, token: str, filename: str, file: bytes, user_id) -> dict:
        url = f"{self.base_url}/v1/files/upload"
        headers = {
            # 'Content-Type': 'application/json',
            'Authorization': f'Bearer {token}'
        }
        data = {
            'user': str(user_id)
        }
        # 创建表单数据,包含文件
        files = {"file": (filename, file)}
        async with httpx.AsyncClient() as client:
            response = await client.post(url, headers=headers, files=files, data=data)
            data = self._handle_response(response)
            logger.error("----------------------------ffff-------------------------------")
            logger.error(response.status_code)
            logger.error(response.text)
            # file_path = data.get("file_path", "")
            result = {
                "file_path": data
            }
 
            return result
 
 
 
 
if __name__ == "__main__":
    async def a():
        a = DifyService("http://192.168.20.119:11080")
        b = await a.get_knowledge_list("ImY3ZTZlZWQwYTY2NTExZWY5ZmFiMDI0MmFjMTMwMDA2Ig.Zzxwmw.uI_HAWzOkipQuga1aeQtoeIc3IM", 1,
                                 10)
        print(b)
 
    import asyncio
 
    asyncio.run(a())