Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,122 +1,69 @@
|
|
| 1 |
-
from
|
| 2 |
-
|
| 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 |
-
# Initialize
|
| 12 |
-
app =
|
| 13 |
-
|
| 14 |
-
#
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
def
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
if
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
messages.extend(json.loads(request.history)) # Load history from the request
|
| 62 |
-
messages.append({'role': 'user', 'content': request.query})
|
| 63 |
|
| 64 |
-
|
| 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 |
-
#
|
| 102 |
-
|
| 103 |
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
return FileResponse("script2.js")
|
| 111 |
-
|
| 112 |
-
@app.get("/styles.css")
|
| 113 |
-
async def styles_css():
|
| 114 |
-
return FileResponse("styles.css")
|
| 115 |
-
|
| 116 |
-
@app.get("/")
|
| 117 |
-
async def read_index():
|
| 118 |
-
return FileResponse('index.html')
|
| 119 |
|
| 120 |
-
if __name__ ==
|
| 121 |
-
|
| 122 |
-
uvicorn.run(app, host="0.0.0.0", port=7068, reload=True)
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify
|
| 2 |
+
import openai
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import os
|
|
|
|
|
|
|
| 4 |
|
| 5 |
+
# Initialize Flask application
|
| 6 |
+
app = Flask(__name__)
|
| 7 |
+
|
| 8 |
+
# Set the base URL for the API endpoint and API key from environment variables
|
| 9 |
+
openai.api_base = "https://api.pawan.krd/unfiltered/v1"
|
| 10 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 11 |
+
|
| 12 |
+
history = []
|
| 13 |
+
first_message = True
|
| 14 |
+
file_name = "Default"
|
| 15 |
+
chatbot_name = "Lunar Ai"
|
| 16 |
+
word_limit = 2000
|
| 17 |
+
|
| 18 |
+
# Introduce the chatbot with its name
|
| 19 |
+
system_message = f"You are a helpful assistant named {chatbot_name}. You only answer coding-related questions. If a non-coding related question is asked, respond with 'I am not programmed to do that.'"
|
| 20 |
+
history.append({"role": "system", "content": system_message})
|
| 21 |
+
|
| 22 |
+
def get_word_count(text):
|
| 23 |
+
return len(text.split())
|
| 24 |
+
|
| 25 |
+
def trim_history_to_word_limit(history, word_limit):
|
| 26 |
+
total_words = sum(get_word_count(message['content']) for message in history)
|
| 27 |
+
while total_words > word_limit:
|
| 28 |
+
if history[1]['role'] == 'user':
|
| 29 |
+
removed_message = history.pop(1)
|
| 30 |
+
total_words -= get_word_count(removed_message['content'])
|
| 31 |
+
if len(history) > 1 and history[1]['role'] == 'assistant':
|
| 32 |
+
removed_message = history.pop(1)
|
| 33 |
+
total_words -= get_word_count(removed_message['content'])
|
| 34 |
+
|
| 35 |
+
@app.route('/chat', methods=['POST'])
|
| 36 |
+
def chat_bot():
|
| 37 |
+
global first_message, file_name
|
| 38 |
+
data = request.json
|
| 39 |
+
message = data.get('message', '')
|
| 40 |
+
|
| 41 |
+
if first_message:
|
| 42 |
+
file_name = message[:20]
|
| 43 |
+
first_message = False
|
| 44 |
+
|
| 45 |
+
history.append({"role": "user", "content": message})
|
| 46 |
+
|
| 47 |
+
try:
|
| 48 |
+
chat_completion = openai.ChatCompletion.create(
|
| 49 |
+
model="gpt-4o",
|
| 50 |
+
messages=history
|
| 51 |
+
)
|
| 52 |
+
response = chat_completion.choices[0].message.content
|
| 53 |
+
except Exception as e:
|
| 54 |
+
return jsonify({"error": str(e)}), 500
|
|
|
|
|
|
|
| 55 |
|
| 56 |
+
history.append({"role": "assistant", "content": response})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
+
# Trim history to keep within the word limit
|
| 59 |
+
trim_history_to_word_limit(history, word_limit)
|
| 60 |
|
| 61 |
+
# Save to a text file
|
| 62 |
+
with open(f"{file_name}.txt", 'a', encoding='utf-8') as f:
|
| 63 |
+
f.write(f"User: {message}\n")
|
| 64 |
+
f.write(f"{chatbot_name}: {response}\n")
|
| 65 |
+
|
| 66 |
+
return jsonify({"response": response, "history": history})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
+
if __name__ == '__main__':
|
| 69 |
+
app.run(host='0.0.0.0', port=5000)
|
|
|