tmp
zhaoqingang
2025-01-09 d961b5e9290edef3bee5cd6adc4a636af209c1e7
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
import json
 
# from Log import logger
from app.models.v2.session_model import ChatData
from app.service.v2.app_driver.chat_base import ChatBase
 
 
class ChatAgent(ChatBase):
 
    async def chat_completions(self, url, data, headers):
        complete_response = ""
        async for line in self.http_stream(url, data, headers):
            # logger.error(line)
            if line.startswith("data:"):
                complete_response = line.strip("data:").strip()
            elif line.startswith("Error: "):
                yield {"event": "error", "message": line}
            else:
                complete_response += line.strip()
            try:
                json_data = json.loads(complete_response)
                # 处理 JSON 数据
                # print(json_data)
                complete_response = ""
                yield json_data
 
            except json.JSONDecodeError as e:
                # logger.info("Invalid JSON data------------------")
                print(e)
 
    @staticmethod
    async def request_data(query: str, conversation_id: str, user:str, chat_data: ChatData) -> dict:
        inputs = []
        files = []
        if hasattr(chat_data,  "inputs"):
            inputs = chat_data.inputs
        if hasattr(chat_data,  "files"):
            files = chat_data.files
 
        return {
            "inputs":inputs,
            "query": query,
            "response_mode": "streaming",
            "conversation_id": conversation_id,
            "user": user,
            "files": files
        }
 
 
if __name__ == "__main__":
    async def aa():
        chat_id = "16954f6d-c1e6-4a0b-b371-363c28e8a48b"
        token = "app-79ndndjNAFSV3qTuDAjDwuSO"
        base_url = "http://192.168.20.116"
        url = f"{base_url}/v1/chat-messages"
        chat = ChatAgent()
        data = {
            "inputs":{},
            "query": "你好,你能做什么?",
            "response_mode": "streaming",
            "conversation_id": "",
            "user": "1",
            "files": []
        }
        headers = {
            'Content-Type': 'application/json',
            'Authorization': f"Bearer {token}"
        }
        async for ans in chat.chat_completions(url, data, headers):
            print(ans)
 
 
    import asyncio
 
    asyncio.run(aa())