KingNish commited on
Commit
14364a4
1 Parent(s): c6d6751

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +114 -2
app.py CHANGED
@@ -1,4 +1,116 @@
 
 
 
 
 
 
 
 
 
 
1
  import os
2
- from groq import Groq
3
 
4
- exec(os.environ.get('MainData'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException, Request
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
+ SAMBA_NOVA_API_KEY = os.environ.get("SAMBA_NOVA_API_KEY", None)
15
+
16
+ app = FastAPI()
17
+
18
+ # Time-Limited Infinite Cache
19
+ cache = {}
20
+ CACHE_DURATION = 120
21
+
22
+ # Function to clean up expired cache entries
23
+ def cleanup_cache():
24
+ current_time = time.time()
25
+ for key, (value, timestamp) in list(cache.items()):
26
+ if current_time - timestamp > CACHE_DURATION:
27
+ del cache[key]
28
+
29
+ # Initialize and start the scheduler
30
+ scheduler = BackgroundScheduler()
31
+ scheduler.add_job(cleanup_cache, 'interval', seconds=60) # Run cleanup every 60 seconds
32
+ scheduler.start()
33
+
34
+ class StreamTextRequest(BaseModel):
35
+ query: str
36
+ history: str = "[]"
37
+ model: str = "llama3-8b"
38
+ api_key: str = None
39
+
40
+ @app.post("/stream_text")
41
+ async def stream_text(request: StreamTextRequest):
42
+ current_time = time.time()
43
+ cache_key = (request.query, request.history, request.model)
44
+
45
+ # Check if the request is in the cache and not expired
46
+ if cache_key in cache:
47
+ cached_response, timestamp = cache[cache_key]
48
+ return StreamingResponse(iter([f"{cached_response}"]), media_type='text/event-stream')
49
+
50
+ # Model selection logic
51
+ if "405" in request.model:
52
+ fmodel = "Meta-Llama-3.1-405B-Instruct"
53
+ if "70" in request.model:
54
+ fmodel = "Meta-Llama-3.1-70B-Instruct"
55
+ else:
56
+ fmodel = "Meta-Llama-3.1-8B-Instruct"
57
+
58
+ system_message = """You are Voicee, a friendly and intelligent voice assistant created by KingNish. Your primary goal is to provide accurate, concise, and engaging responses while maintaining a positive and upbeat tone. Always aim to provide clear and relevant information that directly addresses the user's query, but feel free to sprinkle in a dash of humor—after all, laughter is the best app! Keep your responses brief and to the point, avoiding unnecessary details or tangents, unless they’re hilariously relevant. Use a friendly and approachable tone to create a pleasant interaction, and don’t shy away from a cheeky pun or two! Tailor your responses based on the user's input and previous interactions, ensuring a personalized experience that feels like chatting with a witty friend. Invite users to ask follow-up questions or clarify their needs, fostering a conversational flow that’s as smooth as butter on a hot pancake. Aim to put a smile on the user's face with light-hearted and fun responses, and be proactive in offering additional help or suggestions related to the user's query. Remember, your goal is to be the go-to assistant for users, making their experience enjoyable and informative—like a delightful dessert after a hearty meal!"""
59
+
60
+ messages = [{'role': 'system', 'content': system_message}]
61
+
62
+ messages.extend(ast.literal_eval(request.history))
63
+
64
+ messages.append({'role': 'user', 'content': request.query})
65
+
66
+ data = {'messages': messages, 'stream': True, 'model': fmodel}
67
+
68
+ api_key = request.api_key or SAMBA_NOVA_API_KEY
69
+
70
+ async def stream_response():
71
+ async with aiohttp.ClientSession() as session:
72
+ async with session.post('https://api.sambanova.ai/v1/chat/completions', headers = { 'Authorization': f'Bearer {api_key}', 'Content-Type': 'application/json' }, json=data) as response:
73
+ if response.status != 200:
74
+ raise HTTPException(status_code=response.status, detail="Error fetching AI response")
75
+
76
+ response_content = ""
77
+ async for line in response.content:
78
+ line = line.decode('utf-8').strip()
79
+ if line.startswith('data: {'):
80
+ json_data = line[6:]
81
+ try:
82
+ parsed_data = json.loads(json_data)
83
+ content = parsed_data.get("choices", [{}])[0].get("delta", {}).get("content", '')
84
+ if content:
85
+ content = content.replace("\n", " ")
86
+ response_content += f"data: {content}\n\n"
87
+ yield f"data: {content}\n\n"
88
+ except json.JSONDecodeError as e:
89
+ print(f"Error decoding JSON: {e}")
90
+ yield f"data: Error decoding JSON\n\n"
91
+
92
+ # Cache the full response
93
+ cache[cache_key] = (response_content, current_time)
94
+
95
+ return StreamingResponse(stream_response(), media_type='text/event-stream')
96
+
97
+
98
+
99
+ # Serve index.html from the same directory as your main.py file
100
+ from starlette.responses import FileResponse
101
+
102
+ @app.get("/script1.js")
103
+ async def script1_js():
104
+ return FileResponse("script1.js")
105
+
106
+ @app.get("/script2.js")
107
+ async def script2_js():
108
+ return FileResponse("script2.js")
109
+
110
+ @app.get("/")
111
+ async def read_index():
112
+ return FileResponse('index.html')
113
+
114
+ if __name__ == "__main__":
115
+ import uvicorn
116
+ uvicorn.run(app, host="0.0.0.0", port=7068, reload=True)