smgc commited on
Commit
ec67b57
1 Parent(s): f2a8ecd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +15 -17
app.py CHANGED
@@ -146,19 +146,11 @@ def messages():
146
  nonlocal response_text
147
  if 'text' in data:
148
  text = json.loads(data['text'])
149
- chunks = text.get('chunks', [])
150
- for chunk in chunks:
151
- decoded_chunk = chunk.encode('utf-8').decode('unicode_escape')
152
- response_text.append(decoded_chunk)
153
- yield create_event("content_block_delta", {
154
- "type": "content_block_delta",
155
- "index": 0,
156
- "delta": {"type": "text_delta", "text": decoded_chunk},
157
- })
158
 
159
  def on_query_complete(data):
160
- nonlocal response_event
161
- logging.info("Query complete")
162
  response_event.set()
163
 
164
  def on_disconnect():
@@ -167,11 +159,7 @@ def messages():
167
 
168
  def on_connect_error(data):
169
  logging.error(f"Connection error: {data}")
170
- yield create_event("content_block_delta", {
171
- "type": "content_block_delta",
172
- "index": 0,
173
- "delta": {"type": "text_delta", "text": f"Error connecting to Perplexity AI: {data}"},
174
- })
175
  response_event.set()
176
 
177
  sio.on('connect', on_connect)
@@ -182,7 +170,17 @@ def messages():
182
 
183
  try:
184
  sio.connect('wss://www.perplexity.ai/', **connect_opts, headers=sio_opts['extraHeaders'])
185
- response_event.wait(timeout=30) # 等待响应完成,最多30秒
 
 
 
 
 
 
 
 
 
 
186
  except Exception as e:
187
  logging.error(f"Error during socket connection: {str(e)}")
188
  yield create_event("content_block_delta", {
 
146
  nonlocal response_text
147
  if 'text' in data:
148
  text = json.loads(data['text'])
149
+ chunk = text['chunks'][-1] if text['chunks'] else None
150
+ if chunk:
151
+ response_text.append(chunk)
 
 
 
 
 
 
152
 
153
  def on_query_complete(data):
 
 
154
  response_event.set()
155
 
156
  def on_disconnect():
 
159
 
160
  def on_connect_error(data):
161
  logging.error(f"Connection error: {data}")
162
+ response_text.append(f"Error connecting to Perplexity AI: {data}")
 
 
 
 
163
  response_event.set()
164
 
165
  sio.on('connect', on_connect)
 
170
 
171
  try:
172
  sio.connect('wss://www.perplexity.ai/', **connect_opts, headers=sio_opts['extraHeaders'])
173
+
174
+ while not response_event.is_set():
175
+ sio.sleep(0.1)
176
+ while response_text:
177
+ chunk = response_text.pop(0)
178
+ yield create_event("content_block_delta", {
179
+ "type": "content_block_delta",
180
+ "index": 0,
181
+ "delta": {"type": "text_delta", "text": chunk},
182
+ })
183
+
184
  except Exception as e:
185
  logging.error(f"Error during socket connection: {str(e)}")
186
  yield create_event("content_block_delta", {