Pamudu13 commited on
Commit
79d7b2d
·
verified ·
1 Parent(s): a985dfd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -30
app.py CHANGED
@@ -8,10 +8,20 @@ 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 = {}
@@ -32,8 +42,7 @@ scheduler.start()
32
  class StreamTextRequest(BaseModel):
33
  query: str
34
  history: str = "[]"
35
- model: str = "gpt-4"
36
- api_key: str = None
37
 
38
  @app.post("/stream_text")
39
  async def stream_text(request: StreamTextRequest):
@@ -45,52 +54,52 @@ async def stream_text(request: StreamTextRequest):
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
 
92
  # Serve static files
93
- from starlette.responses import FileResponse
94
 
95
  @app.get("/script1.js")
96
  async def script1_js():
 
8
  from pydantic import BaseModel
9
  from apscheduler.schedulers.background import BackgroundScheduler
10
 
11
+ # Initialize FastAPI application
12
  app = FastAPI()
13
 
14
+ # CORS settings
15
+ app.add_middleware(
16
+ CORSMiddleware,
17
+ allow_origins=["*"],
18
+ allow_credentials=True,
19
+ allow_methods=["*"],
20
+ allow_headers=["*"],
21
+ )
22
+
23
+ # Set the OpenAI API key
24
+ OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", None)
25
 
26
  # Time-Limited Infinite Cache
27
  cache = {}
 
42
  class StreamTextRequest(BaseModel):
43
  query: str
44
  history: str = "[]"
45
+ model: str = "gpt-3.5-turbo" # Default model can be changed as needed
 
46
 
47
  @app.post("/stream_text")
48
  async def stream_text(request: StreamTextRequest):
 
54
  cached_response, timestamp = cache[cache_key]
55
  return StreamingResponse(iter([f"{cached_response}"]), media_type='text/event-stream')
56
 
57
+ # Define system message for OpenAI
 
 
 
58
  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."""
59
 
60
  messages = [{'role': 'system', 'content': system_message}]
61
+ messages.extend(json.loads(request.history)) # Load history from the request
62
  messages.append({'role': 'user', 'content': request.query})
63
+
64
+ data = {'model': request.model, 'messages': messages, 'stream': True}
 
 
 
 
65
 
66
  async def stream_response():
67
  async with aiohttp.ClientSession() as session:
68
  async with session.post(
69
+ 'https://api.openai.com/v1/chat/completions',
70
+ headers={
71
+ 'Authorization': f'Bearer {OPENAI_API_KEY}',
72
+ 'Content-Type': 'application/json'
73
+ },
74
  json=data
75
  ) as response:
76
  if response.status != 200:
77
  raise HTTPException(status_code=response.status, detail="Error fetching AI response")
78
 
79
+ response_content = ""
80
  async for line in response.content:
81
  line = line.decode('utf-8').strip()
82
  if line.startswith('data:'):
83
+ json_data = line[5:].strip() # Remove 'data: ' prefix
84
+ if json_data:
85
+ try:
86
+ parsed_data = json.loads(json_data)
87
+ content = parsed_data.get("choices", [{}])[0].get("delta", {}).get("content", '')
88
+ if content:
89
+ content = content.replace("\n", " ")
90
+ response_content += f"data: {content}\n\n"
91
+ yield f"data: {content}\n\n"
92
+ except json.JSONDecodeError as e:
93
+ print(f"Error decoding JSON: {e}")
94
+ yield f"data: Error decoding JSON\n\n"
95
+
96
+ # Cache the full response
97
+ cache[cache_key] = (response_content, current_time)
98
 
99
  return StreamingResponse(stream_response(), media_type='text/event-stream')
100
 
101
  # Serve static files
102
+ from starlette.responses import FileResponse
103
 
104
  @app.get("/script1.js")
105
  async def script1_js():