Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,20 +1,18 @@
|
|
| 1 |
-
from fastapi import FastAPI, HTTPException
|
| 2 |
from fastapi.responses import StreamingResponse
|
| 3 |
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
import aiohttp
|
| 5 |
import json
|
| 6 |
import time
|
| 7 |
-
import random
|
| 8 |
-
import ast
|
| 9 |
-
import urllib.parse
|
| 10 |
-
from apscheduler.schedulers.background import BackgroundScheduler
|
| 11 |
import os
|
| 12 |
from pydantic import BaseModel
|
| 13 |
-
|
| 14 |
-
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", None)
|
| 15 |
|
| 16 |
app = FastAPI()
|
| 17 |
|
|
|
|
|
|
|
|
|
|
| 18 |
# Time-Limited Infinite Cache
|
| 19 |
cache = {}
|
| 20 |
CACHE_DURATION = 120
|
|
@@ -47,47 +45,47 @@ async def stream_text(request: StreamTextRequest):
|
|
| 47 |
cached_response, timestamp = cache[cache_key]
|
| 48 |
return StreamingResponse(iter([f"{cached_response}"]), media_type='text/event-stream')
|
| 49 |
|
| 50 |
-
#
|
| 51 |
-
|
|
|
|
| 52 |
|
| 53 |
system_message = """You are an AI language assistant. Your sole task is to correct the grammar, spelling, and structure of the sentences provided to you. You must not change the meaning of the sentences, and you should focus only on making them grammatically correct, concise, and clear. Do not add any additional information or provide explanations unless specifically asked. Your responses should be limited to the corrected version of the sentence."""
|
| 54 |
|
| 55 |
messages = [{'role': 'system', 'content': system_message}]
|
| 56 |
-
messages.extend(
|
| 57 |
messages.append({'role': 'user', 'content': request.query})
|
| 58 |
-
|
| 59 |
-
data = {'messages': messages, 'model': fmodel, 'stream': True}
|
| 60 |
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
async def stream_response():
|
| 64 |
async with aiohttp.ClientSession() as session:
|
| 65 |
async with session.post(
|
| 66 |
-
|
| 67 |
headers={'Authorization': f'Bearer {api_key}', 'Content-Type': 'application/json'},
|
| 68 |
json=data
|
| 69 |
) as response:
|
| 70 |
if response.status != 200:
|
| 71 |
raise HTTPException(status_code=response.status, detail="Error fetching AI response")
|
| 72 |
|
| 73 |
-
response_content = ""
|
| 74 |
async for line in response.content:
|
| 75 |
line = line.decode('utf-8').strip()
|
| 76 |
-
if line.startswith('data:
|
| 77 |
json_data = line[6:]
|
| 78 |
try:
|
| 79 |
parsed_data = json.loads(json_data)
|
| 80 |
content = parsed_data.get("choices", [{}])[0].get("delta", {}).get("content", '')
|
| 81 |
if content:
|
| 82 |
-
content = content.replace("\n", " ")
|
| 83 |
-
response_content += f"data: {content}\n\n"
|
| 84 |
yield f"data: {content}\n\n"
|
| 85 |
except json.JSONDecodeError as e:
|
| 86 |
-
print(f"Error decoding JSON: {e}")
|
| 87 |
yield f"data: Error decoding JSON\n\n"
|
| 88 |
|
| 89 |
-
# Cache the full response
|
| 90 |
-
|
|
|
|
| 91 |
|
| 92 |
return StreamingResponse(stream_response(), media_type='text/event-stream')
|
| 93 |
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
from fastapi.responses import StreamingResponse
|
| 3 |
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
import aiohttp
|
| 5 |
import json
|
| 6 |
import time
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
import os
|
| 8 |
from pydantic import BaseModel
|
| 9 |
+
from apscheduler.schedulers.background import BackgroundScheduler
|
|
|
|
| 10 |
|
| 11 |
app = FastAPI()
|
| 12 |
|
| 13 |
+
# Enable CORS
|
| 14 |
+
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"])
|
| 15 |
+
|
| 16 |
# Time-Limited Infinite Cache
|
| 17 |
cache = {}
|
| 18 |
CACHE_DURATION = 120
|
|
|
|
| 45 |
cached_response, timestamp = cache[cache_key]
|
| 46 |
return StreamingResponse(iter([f"{cached_response}"]), media_type='text/event-stream')
|
| 47 |
|
| 48 |
+
# Use the API specified by the user
|
| 49 |
+
api_url = "https://api.pawan.krd/unfiltered/v1"
|
| 50 |
+
api_key = request.api_key if request.api_key != 'none' else os.environ.get("OPENAI_API_KEY")
|
| 51 |
|
| 52 |
system_message = """You are an AI language assistant. Your sole task is to correct the grammar, spelling, and structure of the sentences provided to you. You must not change the meaning of the sentences, and you should focus only on making them grammatically correct, concise, and clear. Do not add any additional information or provide explanations unless specifically asked. Your responses should be limited to the corrected version of the sentence."""
|
| 53 |
|
| 54 |
messages = [{'role': 'system', 'content': system_message}]
|
| 55 |
+
messages.extend(json.loads(request.history))
|
| 56 |
messages.append({'role': 'user', 'content': request.query})
|
|
|
|
|
|
|
| 57 |
|
| 58 |
+
data = {
|
| 59 |
+
'messages': messages,
|
| 60 |
+
'model': request.model,
|
| 61 |
+
'stream': True
|
| 62 |
+
}
|
| 63 |
|
| 64 |
async def stream_response():
|
| 65 |
async with aiohttp.ClientSession() as session:
|
| 66 |
async with session.post(
|
| 67 |
+
api_url,
|
| 68 |
headers={'Authorization': f'Bearer {api_key}', 'Content-Type': 'application/json'},
|
| 69 |
json=data
|
| 70 |
) as response:
|
| 71 |
if response.status != 200:
|
| 72 |
raise HTTPException(status_code=response.status, detail="Error fetching AI response")
|
| 73 |
|
|
|
|
| 74 |
async for line in response.content:
|
| 75 |
line = line.decode('utf-8').strip()
|
| 76 |
+
if line.startswith('data:'):
|
| 77 |
json_data = line[6:]
|
| 78 |
try:
|
| 79 |
parsed_data = json.loads(json_data)
|
| 80 |
content = parsed_data.get("choices", [{}])[0].get("delta", {}).get("content", '')
|
| 81 |
if content:
|
|
|
|
|
|
|
| 82 |
yield f"data: {content}\n\n"
|
| 83 |
except json.JSONDecodeError as e:
|
|
|
|
| 84 |
yield f"data: Error decoding JSON\n\n"
|
| 85 |
|
| 86 |
+
# Cache the full response if available
|
| 87 |
+
# response_content = "full response would be stored here if needed"
|
| 88 |
+
# cache[cache_key] = (response_content, current_time)
|
| 89 |
|
| 90 |
return StreamingResponse(stream_response(), media_type='text/event-stream')
|
| 91 |
|