File size: 8,505 Bytes
e3596d7
a503c73
096dbd4
 
d3cddbc
096dbd4
ae95de2
 
 
 
 
 
096dbd4
 
ae95de2
 
 
 
 
 
 
 
 
 
096dbd4
ae95de2
 
 
 
 
 
 
 
 
 
096dbd4
faf18e1
ae95de2
 
 
 
 
 
 
 
 
 
e3596d7
ae95de2
096dbd4
ae95de2
096dbd4
ae95de2
 
 
 
 
 
 
 
 
 
 
a503c73
 
 
 
 
 
 
096dbd4
a503c73
 
 
 
096dbd4
a503c73
096dbd4
 
a503c73
ae95de2
 
 
 
 
 
e3596d7
ae95de2
 
 
 
a503c73
 
 
096dbd4
a503c73
 
 
 
096dbd4
 
ae95de2
 
 
096dbd4
ae95de2
 
096dbd4
ae95de2
096dbd4
 
 
 
 
 
 
 
 
 
ae95de2
 
 
 
 
568f598
ae95de2
995e6d1
ae95de2
 
 
 
 
 
 
 
 
 
 
 
 
 
995e6d1
 
ae95de2
568f598
f2a8ecd
ae95de2
 
9b77e4a
 
d3cddbc
 
 
 
 
 
 
 
 
f2a8ecd
 
d3cddbc
ae95de2
568f598
ae95de2
 
 
568f598
ae95de2
d3cddbc
 
 
 
 
0081309
568f598
 
 
d3cddbc
568f598
 
ae95de2
 
 
f2a8ecd
ae95de2
 
 
 
 
 
 
 
 
 
 
d3cddbc
 
 
 
 
 
 
ae95de2
 
d3cddbc
096dbd4
a503c73
ae95de2
 
 
 
 
 
 
 
096dbd4
ae95de2
 
 
 
 
 
 
 
d3cddbc
 
096dbd4
 
ae95de2
 
faf18e1
ae95de2
 
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
import os
import json
import uuid
from datetime import datetime
from flask import Flask, request, Response, jsonify
import socketio
import requests
import logging
from threading import Event

app = Flask(__name__)
logging.basicConfig(level=logging.INFO)

# 从环境变量中获取API密钥
API_KEY = os.environ.get('PPLX_KEY')

# 代理设置
proxy_url = os.environ.get('PROXY_URL')

# 设置代理
if proxy_url:
    proxies = {
        'http': proxy_url,
        'https': proxy_url
    }
    transport = requests.Session()
    transport.proxies.update(proxies)
else:
    transport = None

sio = socketio.Client(http_session=transport, logger=True, engineio_logger=True)

# 连接选项
connect_opts = {
    'transports': ['websocket', 'polling'],  # 允许回退到轮询
}

# 其他选项
sio_opts = {
    'extraHeaders': {
        'Cookie': os.environ.get('PPLX_COOKIE'),
        'User-Agent': os.environ.get('USER_AGENT'),
        'Accept': '*/*',
        'priority': 'u=1, i',
        'Referer': 'https://www.perplexity.ai/',
    }
}

def log_request(ip, route, status):
    timestamp = datetime.now().isoformat()
    logging.info(f"{timestamp} - {ip} - {route} - {status}")

def validate_api_key():
    api_key = request.headers.get('x-api-key')
    if api_key != API_KEY:
        log_request(request.remote_addr, request.path, 401)
        return jsonify({"error": "Invalid API key"}), 401
    return None

@app.route('/')
def root():
    log_request(request.remote_addr, request.path, 200)
    return jsonify({
        "message": "Welcome to the Perplexity AI Proxy API",
        "endpoints": {
            "/ai/v1/messages": {
                "method": "POST",
                "description": "Send a message to the AI",
                "headers": {
                    "x-api-key": "Your API key (required)",
                    "Content-Type": "application/json"
                },
                "body": {
                    "messages": "Array of message objects",
                    "stream": "Boolean (true for streaming response)",
                }
            }
        }
    })

@app.route('/ai/v1/messages', methods=['POST'])
def messages():
    auth_error = validate_api_key()
    if auth_error:
        return auth_error

    try:
        json_body = request.json
        if not json_body.get('stream', False):
            log_request(request.remote_addr, request.path, 200)
            return jsonify({
                "id": str(uuid.uuid4()),
                "content": [
                    {"text": "Please turn on streaming."},
                    {"id": "string", "name": "string", "input": {}}
                ],
                "model": "string",
                "stop_reason": "end_turn",
                "stop_sequence": "string",
                "usage": {"input_tokens": 0, "output_tokens": 0}
            })
        
        def generate():
            previous_messages = "\n\n".join([msg['content'] for msg in json_body['messages']])
            msg_id = str(uuid.uuid4())
            response_event = Event()
            response_text = []

            yield create_event("message_start", {
                "type": "message_start",
                "message": {
                    "id": msg_id,
                    "type": "message",
                    "role": "assistant",
                    "content": [],
                    "model": "claude-3-opus-20240229",
                    "stop_reason": None,
                    "stop_sequence": None,
                    "usage": {"input_tokens": 8, "output_tokens": 1},
                },
            })
            yield create_event("content_block_start", {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}})
            yield create_event("ping", {"type": "ping"})

            def on_connect():
                logging.info("Connected to Perplexity AI")
                emit_data = {
                    "version": "2.9",
                    "source": "default",
                    "attachments": [],
                    "language": "en-GB",
                    "timezone": "Europe/London",
                    "search_focus": "writing",
                    "frontend_uuid": str(uuid.uuid4()),
                    "mode": "concise",
                    "is_related_query": False,
                    "is_default_related_query": False,
                    "visitor_id": str(uuid.uuid4()),
                    "frontend_context_uuid": str(uuid.uuid4()),
                    "prompt_source": "user",
                    "query_source": "home"
                }
                sio.emit('perplexity_ask', (previous_messages, emit_data))

            def on_query_progress(data):
                nonlocal response_text
                if 'text' in data:
                    text = json.loads(data['text'])
                    chunks = text.get('chunks', [])
                    for chunk in chunks:
                        decoded_chunk = chunk.encode('utf-8').decode('unicode_escape')
                        response_text.append(decoded_chunk)
                        yield create_event("content_block_delta", {
                            "type": "content_block_delta",
                            "index": 0,
                            "delta": {"type": "text_delta", "text": decoded_chunk},
                        })

            def on_query_complete(data):
                nonlocal response_event
                logging.info("Query complete")
                response_event.set()

            def on_disconnect():
                logging.info("Disconnected from Perplexity AI")
                response_event.set()

            def on_connect_error(data):
                logging.error(f"Connection error: {data}")
                yield create_event("content_block_delta", {
                    "type": "content_block_delta",
                    "index": 0,
                    "delta": {"type": "text_delta", "text": f"Error connecting to Perplexity AI: {data}"},
                })
                response_event.set()

            sio.on('connect', on_connect)
            sio.on('query_progress', on_query_progress)
            sio.on('query_complete', on_query_complete)
            sio.on('disconnect', on_disconnect)
            sio.on('connect_error', on_connect_error)

            try:
                sio.connect('wss://www.perplexity.ai/', **connect_opts, headers=sio_opts['extraHeaders'])
                response_event.wait(timeout=30)  # 等待响应完成,最多30秒
            except Exception as e:
                logging.error(f"Error during socket connection: {str(e)}")
                yield create_event("content_block_delta", {
                    "type": "content_block_delta",
                    "index": 0,
                    "delta": {"type": "text_delta", "text": f"Error during socket connection: {str(e)}"},
                })
            finally:
                if sio.connected:
                    sio.disconnect()

            yield create_event("content_block_stop", {"type": "content_block_stop", "index": 0})
            yield create_event("message_delta", {
                "type": "message_delta",
                "delta": {"stop_reason": "end_turn", "stop_sequence": None},
                "usage": {"output_tokens": len(''.join(response_text))},
            })
            yield create_event("message_stop", {"type": "message_stop"})
            log_request(request.remote_addr, request.path, 200)

        return Response(generate(), content_type='text/event-stream')

    except Exception as e:
        logging.error(f"Request error: {str(e)}")
        log_request(request.remote_addr, request.path, 400)
        return jsonify({"error": str(e)}), 400

@app.errorhandler(404)
def not_found(error):
    log_request(request.remote_addr, request.path, 404)
    return "Not Found", 404

@app.errorhandler(500)
def server_error(error):
    logging.error(f"Server error: {str(error)}")
    log_request(request.remote_addr, request.path, 500)
    return "Something broke!", 500

def create_event(event, data):
    if isinstance(data, dict):
        data = json.dumps(data)
    return f"event: {event}\ndata: {data}\n\n"

if __name__ == '__main__':
    port = int(os.environ.get('PORT', 8081))
    logging.info(f"Perplexity proxy listening on port {port}")
    if not API_KEY:
        logging.warning("Warning: PPLX_KEY environment variable is not set. API key validation will fail.")
    app.run(host='0.0.0.0', port=port)