Spaces:
Running
Running
Update main.py
Browse files
main.py
CHANGED
@@ -10,6 +10,7 @@ from pathlib import Path
|
|
10 |
import json
|
11 |
import datetime
|
12 |
import time
|
|
|
13 |
from typing import Optional, Dict, List, Any, Generator
|
14 |
import asyncio
|
15 |
from starlette.status import HTTP_403_FORBIDDEN
|
@@ -380,57 +381,106 @@ async def get_completion(payload: Payload, request: Request, authenticated: bool
|
|
380 |
else:
|
381 |
endpoint = env_vars['secret_api_endpoint']
|
382 |
custom_headers = {}
|
383 |
-
print(payload_dict)
|
384 |
-
print(f"laude ye endpoint use kia: {endpoint}")
|
385 |
-
scraper = get_scraper()
|
386 |
|
387 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
388 |
try:
|
389 |
-
#
|
390 |
-
|
391 |
-
f"{endpoint}/v1/chat/completions",
|
392 |
-
json=payload_dict,
|
393 |
-
headers=custom_headers,
|
394 |
-
stream=True
|
395 |
-
)
|
396 |
-
|
397 |
-
# Handle response errors
|
398 |
-
if response.status_code >= 400:
|
399 |
-
error_messages = {
|
400 |
-
422: "Unprocessable entity. Check your payload.",
|
401 |
-
400: "Bad request. Verify input data.",
|
402 |
-
403: "Forbidden. You do not have access to this resource.",
|
403 |
-
404: "The requested resource was not found.",
|
404 |
-
}
|
405 |
-
detail = error_messages.get(response.status_code, f"Error code: {response.status_code}")
|
406 |
-
raise HTTPException(status_code=response.status_code, detail=detail)
|
407 |
-
|
408 |
-
# Stream response lines to the client - use buffer for efficiency
|
409 |
-
buffer = []
|
410 |
-
buffer_size = 0
|
411 |
-
max_buffer = 8192 # 8KB buffer
|
412 |
|
413 |
-
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
|
|
|
|
|
|
|
|
|
|
418 |
|
419 |
-
|
420 |
-
|
421 |
-
|
422 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
423 |
|
424 |
-
#
|
425 |
-
|
426 |
-
|
427 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
428 |
except Exception as e:
|
|
|
|
|
429 |
# Use a generic error message that doesn't expose internal details
|
430 |
-
raise HTTPException(status_code=500, detail="An error occurred while processing your request")
|
431 |
-
|
432 |
-
return StreamingResponse(stream_generator(payload_dict), media_type="application/json")
|
433 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
434 |
# Asynchronous logging function
|
435 |
async def log_request(request, model):
|
436 |
# Get minimal data for logging
|
|
|
10 |
import json
|
11 |
import datetime
|
12 |
import time
|
13 |
+
import threading
|
14 |
from typing import Optional, Dict, List, Any, Generator
|
15 |
import asyncio
|
16 |
from starlette.status import HTTP_403_FORBIDDEN
|
|
|
381 |
else:
|
382 |
endpoint = env_vars['secret_api_endpoint']
|
383 |
custom_headers = {}
|
|
|
|
|
|
|
384 |
|
385 |
+
print(f"Using endpoint: {endpoint}")
|
386 |
+
|
387 |
+
# Create a new scraper for each request to avoid potential blocking
|
388 |
+
scraper = cloudscraper.create_scraper(browser={
|
389 |
+
'browser': 'chrome',
|
390 |
+
'platform': 'windows',
|
391 |
+
'mobile': False
|
392 |
+
})
|
393 |
+
|
394 |
+
# Set a timeout for the entire request handling
|
395 |
+
TIMEOUT_SECONDS = 20
|
396 |
+
|
397 |
+
async def stream_generator_with_timeout(payload_dict):
|
398 |
try:
|
399 |
+
# Create a thread-safe event for cancellation
|
400 |
+
cancel_event = threading.Event()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
401 |
|
402 |
+
def request_with_timeout():
|
403 |
+
try:
|
404 |
+
# Send POST request with the correct headers and timeout
|
405 |
+
response = scraper.post(
|
406 |
+
f"{endpoint}/v1/chat/completions",
|
407 |
+
json=payload_dict,
|
408 |
+
headers=custom_headers,
|
409 |
+
stream=True,
|
410 |
+
timeout=TIMEOUT_SECONDS
|
411 |
+
)
|
412 |
|
413 |
+
# Handle response errors
|
414 |
+
if response.status_code >= 400:
|
415 |
+
error_messages = {
|
416 |
+
422: "Unprocessable entity. Check your payload.",
|
417 |
+
400: "Bad request. Verify input data.",
|
418 |
+
403: "Forbidden. You do not have access to this resource.",
|
419 |
+
404: "The requested resource was not found.",
|
420 |
+
}
|
421 |
+
detail = error_messages.get(response.status_code, f"Error code: {response.status_code}")
|
422 |
+
return {"error": detail, "status_code": response.status_code}
|
423 |
+
|
424 |
+
result = []
|
425 |
+
|
426 |
+
# Process the streaming response with timeout checks
|
427 |
+
for line in response.iter_lines():
|
428 |
+
# Check for cancellation
|
429 |
+
if cancel_event.is_set():
|
430 |
+
break
|
431 |
+
|
432 |
+
if line:
|
433 |
+
decoded = line.decode('utf-8') + "\n"
|
434 |
+
result.append(decoded)
|
435 |
+
|
436 |
+
return {"lines": result}
|
437 |
+
|
438 |
+
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError) as e:
|
439 |
+
return {"error": "Request timed out or connection failed", "status_code": 504}
|
440 |
+
except Exception as e:
|
441 |
+
return {"error": str(e), "status_code": 500}
|
442 |
|
443 |
+
# Execute request in a ThreadPoolExecutor with a timeout
|
444 |
+
loop = asyncio.get_running_loop()
|
445 |
+
with ThreadPoolExecutor() as pool:
|
446 |
+
response_future = loop.run_in_executor(pool, request_with_timeout)
|
447 |
+
|
448 |
+
try:
|
449 |
+
# Wait for response with a timeout
|
450 |
+
response_data = await asyncio.wait_for(response_future, timeout=TIMEOUT_SECONDS)
|
451 |
+
|
452 |
+
# If there was an error, raise an HTTPException
|
453 |
+
if "error" in response_data:
|
454 |
+
raise HTTPException(
|
455 |
+
status_code=response_data.get("status_code", 500),
|
456 |
+
detail=response_data["error"]
|
457 |
+
)
|
458 |
+
|
459 |
+
# Stream the response lines
|
460 |
+
for line in response_data.get("lines", []):
|
461 |
+
yield line
|
462 |
+
|
463 |
+
except asyncio.TimeoutError:
|
464 |
+
# Cancel the ongoing request
|
465 |
+
cancel_event.set()
|
466 |
+
raise HTTPException(status_code=504, detail="Request timed out after 20 seconds")
|
467 |
+
|
468 |
except Exception as e:
|
469 |
+
if isinstance(e, HTTPException):
|
470 |
+
raise e
|
471 |
# Use a generic error message that doesn't expose internal details
|
472 |
+
raise HTTPException(status_code=500, detail=f"An error occurred while processing your request: {str(e)}")
|
|
|
|
|
473 |
|
474 |
+
# Return streaming response with proper timeout handling
|
475 |
+
try:
|
476 |
+
return StreamingResponse(
|
477 |
+
stream_generator_with_timeout(payload_dict),
|
478 |
+
media_type="application/json"
|
479 |
+
)
|
480 |
+
except Exception as e:
|
481 |
+
if isinstance(e, HTTPException):
|
482 |
+
raise e
|
483 |
+
raise HTTPException(status_code=500, detail=f"Failed to initialize streaming response: {str(e)}")
|
484 |
# Asynchronous logging function
|
485 |
async def log_request(request, model):
|
486 |
# Get minimal data for logging
|