File size: 6,297 Bytes
b78a49d
 
 
 
 
 
7743fdc
b78a49d
c7fad4e
7743fdc
 
b78a49d
 
 
7743fdc
 
 
 
 
 
d9dbeb6
 
 
 
 
 
 
 
 
 
 
 
7e4060c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9dbeb6
7743fdc
b78a49d
 
c6ac7c1
b78a49d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8452340
b78a49d
 
 
 
 
8452340
b78a49d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8452340
 
 
 
 
 
 
 
 
 
 
7743fdc
 
 
a65fb83
7743fdc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a65fb83
 
 
 
 
 
 
b78a49d
 
7743fdc
b78a49d
 
 
 
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
from flask import Flask, request, jsonify, Response
import requests
import uuid
import json
import time
import os
import re

_COOKIES = os.environ.get("COOKIES", "")

API_KEY = os.getenv("API_KEY", "linux.do")

app = Flask(__name__)

@app.before_request
def check_api_key():
    key = request.headers.get("Authorization")
    if key != "Bearer "+API_KEY:
        return jsonify({"success": False, "message": "Unauthorized: Invalid API key"}), 403

@app.route('/v1/models', methods=['GET'])
def get_models():
     # 构建请求头
    headers = {
        "Content-Type": "application/json",
        "Cookie": _COOKIES
    }
    # 发送请求到Akash API
    response = requests.get(
        'https://chat.akash.network/api/models',
        headers=headers
    )
    models_data = response.json()
    current_timestamp = int(time.time())   
    converted_data = {
        "object": "list",
        "data": [
            {
                "id": model["id"],
                "object": "model",
                "created": current_timestamp,
                "owned_by": model["name"].lower().replace(" ", "_")
            }
            for model in models_data["models"]
        ]
    }
    return converted_data


@app.route('/v1/chat/completions', methods=['POST'])
def chat_completions():
    print("start")
    try:
        # 获取OpenAI格式的请求数据
        data = request.json
        
        # 生成唯一ID
        chat_id = str(uuid.uuid4()).replace('-', '')[:16]
        
        # 构建Akash格式的请求数据
        akash_data = {
            "id": chat_id,
            "messages": data.get('messages', []),
            "model": data.get('model', "DeepSeek-R1"),
            "system": data.get('system_message', "You are a helpful assistant."),
            "temperature": data.get('temperature', 0.6),
            "topP": data.get('top_p', 0.95)
        }
        # 构建请求头
        headers = {
            "Content-Type": "application/json",
            "Cookie": _COOKIES
        }
        _stream=data.get('stream', True)
        # 发送请求到Akash API
        response = requests.post(
            'https://chat.akash.network/api/chat',
            json=akash_data,
            headers=headers,
            stream=_stream
        )
        
        def generate():
            content_buffer = ""
            for line in response.iter_lines():
                if not line:
                    continue
                    
                try:
                    # 解析行数据,格式为 "type:json_data"
                    line_str = line.decode('utf-8')
                    msg_type, msg_data = line_str.split(':', 1)
                    
                    # 处理内容类型的消息
                    if msg_type == '0':
                        # 只去掉两边的双引号
                        if msg_data.startswith('"') and msg_data.endswith('"'):
                            msg_data = msg_data.replace('\\"', '"')
                            msg_data = msg_data[1:-1]
                        msg_data = msg_data.replace("\\n", "\n")
                        content_buffer += msg_data
                        
                        # 构建 OpenAI 格式的响应块
                        chunk = {
                            "id": f"chatcmpl-{chat_id}",
                            "object": "chat.completion.chunk",
                            "created": int(time.time()),
                            "model": data.get('model', "DeepSeek-R1"),
                            "choices": [{
                                "delta": {"content": msg_data},
                                "index": 0,
                                "finish_reason": None
                            }]
                        }
                        yield f"data: {json.dumps(chunk)}\n\n"
                    
                    # 处理结束消息
                    elif msg_type in ['e', 'd']:
                        chunk = {
                            "id": f"chatcmpl-{chat_id}",
                            "object": "chat.completion.chunk",
                            "created": int(time.time()),
                            "model": data.get('model', "DeepSeek-R1"),
                            "choices": [{
                                "delta": {},
                                "index": 0,
                                "finish_reason": "stop"
                            }]
                        }
                        yield f"data: {json.dumps(chunk)}\n\n"
                        yield "data: [DONE]\n\n"
                        break
                        
                except Exception as e:
                    print(f"Error processing line: {e}")
                    continue

        if _stream == True:
            return Response(
                generate(),
                mimetype='text/event-stream',
                headers={
                    'Cache-Control': 'no-cache',
                    'Connection': 'keep-alive',
                    'Content-Type': 'text/event-stream'
                }
            )
        else:
            text_matches = re.findall(r'0:"(.*?)"', response.text)
            parsed_text = "".join(text_matches)

            return Response(
                json.dumps({
                    "object": "chat.completion",
                    "created": int(time.time() * 1000),
                    "model": data.get('model', "DeepSeek-R1"),
                    "choices": [
                        {
                            "index": 0,
                            "message": {
                                "role": "user",
                                "content": parsed_text
                            },
                            "finish_reason": "stop"
                        }
                    ]
                },ensure_ascii=False),
                status=response.status_code,
                headers={
                    'Cache-Control': 'no-cache',
                    'Connection': 'keep-alive',
                    'Content-Type': 'application/json'
                }
            )
    
    except Exception as e:
        print(e)
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5200)