Update app.py
Browse files
app.py
CHANGED
|
@@ -1,45 +1,35 @@
|
|
| 1 |
from flask import Flask, render_template, request, jsonify
|
| 2 |
-
import subprocess
|
| 3 |
-
import tempfile
|
| 4 |
import os
|
| 5 |
-
import
|
| 6 |
-
from
|
|
|
|
| 7 |
from langchain.prompts import PromptTemplate
|
| 8 |
from langchain.chains import LLMChain
|
| 9 |
from langchain.memory import ConversationBufferMemory
|
| 10 |
from datetime import datetime
|
| 11 |
-
import json
|
| 12 |
-
from typing import Dict, List
|
| 13 |
import sqlite3
|
| 14 |
from contextlib import contextmanager
|
| 15 |
-
import re
|
| 16 |
from werkzeug.utils import secure_filename
|
| 17 |
-
import torch
|
| 18 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 19 |
|
|
|
|
| 20 |
app = Flask(__name__)
|
| 21 |
|
| 22 |
-
# Configuration
|
| 23 |
PORT = int(os.environ.get("PORT", 7860))
|
| 24 |
-
|
| 25 |
-
# Create and set up a writable directory in /tmp
|
| 26 |
CACHE_DIR = "/tmp/huggingface_cache"
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
os.environ['HF_HOME'] = CACHE_DIR
|
| 30 |
-
os.environ['XDG_CACHE_HOME'] = CACHE_DIR
|
| 31 |
|
| 32 |
-
#
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
| 36 |
-
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
| 37 |
|
| 38 |
-
#
|
| 39 |
-
|
|
|
|
| 40 |
|
| 41 |
-
|
| 42 |
-
|
| 43 |
|
| 44 |
# Initialize prompt template
|
| 45 |
prompt_template = """
|
|
@@ -59,15 +49,14 @@ Output Guidelines:
|
|
| 59 |
- Use ```python for code blocks
|
| 60 |
- Use `code` for inline code references
|
| 61 |
- Provide raw text without HTML formatting
|
| 62 |
-
-
|
| 63 |
|
| 64 |
2. Code Organization:
|
| 65 |
-
- Default to single, focused code snippets
|
| 66 |
-
- Only split into multiple snippets
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
- Mark critical information with [IMPORTANT] prefix and give small explanations with some bold headings if required and in white font always.
|
| 71 |
"""
|
| 72 |
|
| 73 |
prompt = PromptTemplate(
|
|
@@ -85,47 +74,59 @@ def get_db_connection():
|
|
| 85 |
finally:
|
| 86 |
conn.close()
|
| 87 |
|
| 88 |
-
def
|
| 89 |
-
"""Initialize the
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
| 121 |
)
|
| 122 |
-
|
| 123 |
-
return HuggingFacePipeline(pipeline=pipe)
|
| 124 |
except Exception as e:
|
| 125 |
-
print(f"Error initializing
|
| 126 |
raise
|
| 127 |
|
| 128 |
-
|
| 129 |
class ChatSession:
|
| 130 |
def __init__(self, session_id):
|
| 131 |
self.session_id = session_id
|
|
@@ -230,65 +231,28 @@ class ChatSession:
|
|
| 230 |
|
| 231 |
self.important_info = []
|
| 232 |
|
|
|
|
| 233 |
|
| 234 |
-
|
| 235 |
-
"
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
conn.execute('''
|
| 239 |
-
CREATE TABLE IF NOT EXISTS chats (
|
| 240 |
-
id TEXT PRIMARY KEY,
|
| 241 |
-
title TEXT,
|
| 242 |
-
date TEXT,
|
| 243 |
-
last_message TEXT
|
| 244 |
-
)
|
| 245 |
-
''')
|
| 246 |
-
|
| 247 |
-
conn.execute('''
|
| 248 |
-
CREATE TABLE IF NOT EXISTS messages (
|
| 249 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 250 |
-
chat_id TEXT,
|
| 251 |
-
role TEXT,
|
| 252 |
-
content TEXT,
|
| 253 |
-
timestamp TEXT,
|
| 254 |
-
FOREIGN KEY (chat_id) REFERENCES chats (id)
|
| 255 |
-
)
|
| 256 |
-
''')
|
| 257 |
-
|
| 258 |
-
conn.execute('''
|
| 259 |
-
CREATE TABLE IF NOT EXISTS important_info (
|
| 260 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 261 |
-
chat_id TEXT,
|
| 262 |
-
content TEXT,
|
| 263 |
-
FOREIGN KEY (chat_id) REFERENCES chats (id)
|
| 264 |
-
)
|
| 265 |
-
''')
|
| 266 |
-
conn.commit()
|
| 267 |
-
except Exception as e:
|
| 268 |
-
print(f"Error initializing database: {e}")
|
| 269 |
-
raise
|
| 270 |
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
print("Initializing database...")
|
| 277 |
-
init_db()
|
| 278 |
-
print("Database initialized successfully")
|
| 279 |
-
|
| 280 |
-
print("Starting model initialization...")
|
| 281 |
-
llm = initialize_model()
|
| 282 |
-
print("Model initialized successfully")
|
| 283 |
-
|
| 284 |
-
print("Creating LLM chain...")
|
| 285 |
-
llm_chain = LLMChain(llm=llm, prompt=prompt)
|
| 286 |
-
print("LLM chain created successfully")
|
| 287 |
-
except Exception as e:
|
| 288 |
-
print(f"Initialization error: {e}")
|
| 289 |
-
raise
|
| 290 |
|
| 291 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
# Rest of the prompt template and other configurations remain the same
|
| 293 |
prompt_template = """
|
| 294 |
Role: You are Figr Code Assistant, specializing in providing clear, error-free Python code solutions.
|
|
@@ -468,11 +432,10 @@ def get_chat_list():
|
|
| 468 |
|
| 469 |
@app.route("/api/chat", methods=["POST"])
|
| 470 |
def chat():
|
| 471 |
-
|
| 472 |
-
if llm_chain is None:
|
| 473 |
return jsonify({
|
| 474 |
-
"
|
| 475 |
-
"
|
| 476 |
})
|
| 477 |
data = request.json
|
| 478 |
user_input = data.get("message", "")
|
|
@@ -720,7 +683,7 @@ def home():
|
|
| 720 |
return render_template("index.html")
|
| 721 |
|
| 722 |
|
| 723 |
-
|
| 724 |
|
| 725 |
if __name__ == "__main__":
|
| 726 |
app.run(host="0.0.0.0", port=PORT)
|
|
|
|
| 1 |
from flask import Flask, render_template, request, jsonify
|
|
|
|
|
|
|
| 2 |
import os
|
| 3 |
+
import tempfile
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from langchain_community.llms import HuggingFaceHub
|
| 6 |
from langchain.prompts import PromptTemplate
|
| 7 |
from langchain.chains import LLMChain
|
| 8 |
from langchain.memory import ConversationBufferMemory
|
| 9 |
from datetime import datetime
|
|
|
|
|
|
|
| 10 |
import sqlite3
|
| 11 |
from contextlib import contextmanager
|
|
|
|
| 12 |
from werkzeug.utils import secure_filename
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
# Initialize Flask application
|
| 15 |
app = Flask(__name__)
|
| 16 |
|
| 17 |
+
# Configuration
|
| 18 |
PORT = int(os.environ.get("PORT", 7860))
|
|
|
|
|
|
|
| 19 |
CACHE_DIR = "/tmp/huggingface_cache"
|
| 20 |
+
UPLOAD_DIR = "/tmp/uploads"
|
| 21 |
+
DATABASE_PATH = "/tmp/chat_database.db"
|
|
|
|
|
|
|
| 22 |
|
| 23 |
+
# Create necessary directories
|
| 24 |
+
for dir_path in [CACHE_DIR, UPLOAD_DIR]:
|
| 25 |
+
Path(dir_path).mkdir(parents=True, exist_ok=True)
|
|
|
|
|
|
|
| 26 |
|
| 27 |
+
# Set environment variables
|
| 28 |
+
os.environ['TRANSFORMERS_CACHE'] = CACHE_DIR
|
| 29 |
+
os.environ['HUGGINGFACE_HUB_CACHE'] = CACHE_DIR
|
| 30 |
|
| 31 |
+
# Configure Flask app
|
| 32 |
+
app.config['UPLOAD_FOLDER'] = UPLOAD_DIR
|
| 33 |
|
| 34 |
# Initialize prompt template
|
| 35 |
prompt_template = """
|
|
|
|
| 49 |
- Use ```python for code blocks
|
| 50 |
- Use `code` for inline code references
|
| 51 |
- Provide raw text without HTML formatting
|
| 52 |
+
- Include explanations after code blocks
|
| 53 |
|
| 54 |
2. Code Organization:
|
| 55 |
+
- Default to single, focused code snippets
|
| 56 |
+
- Only split into multiple snippets if necessary
|
| 57 |
+
- Mark critical information with [IMPORTANT] prefix
|
| 58 |
+
|
| 59 |
+
Please provide a clear and detailed response:
|
|
|
|
| 60 |
"""
|
| 61 |
|
| 62 |
prompt = PromptTemplate(
|
|
|
|
| 74 |
finally:
|
| 75 |
conn.close()
|
| 76 |
|
| 77 |
+
def init_db():
|
| 78 |
+
"""Initialize the database"""
|
| 79 |
+
with get_db_connection() as conn:
|
| 80 |
+
conn.execute('''
|
| 81 |
+
CREATE TABLE IF NOT EXISTS chats (
|
| 82 |
+
id TEXT PRIMARY KEY,
|
| 83 |
+
title TEXT,
|
| 84 |
+
date TEXT,
|
| 85 |
+
last_message TEXT
|
| 86 |
+
)
|
| 87 |
+
''')
|
| 88 |
+
|
| 89 |
+
conn.execute('''
|
| 90 |
+
CREATE TABLE IF NOT EXISTS messages (
|
| 91 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 92 |
+
chat_id TEXT,
|
| 93 |
+
role TEXT,
|
| 94 |
+
content TEXT,
|
| 95 |
+
timestamp TEXT,
|
| 96 |
+
FOREIGN KEY (chat_id) REFERENCES chats (id)
|
| 97 |
+
)
|
| 98 |
+
''')
|
| 99 |
+
|
| 100 |
+
conn.execute('''
|
| 101 |
+
CREATE TABLE IF NOT EXISTS important_info (
|
| 102 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 103 |
+
chat_id TEXT,
|
| 104 |
+
content TEXT,
|
| 105 |
+
FOREIGN KEY (chat_id) REFERENCES chats (id)
|
| 106 |
+
)
|
| 107 |
+
''')
|
| 108 |
+
conn.commit()
|
| 109 |
|
| 110 |
+
def initialize_llm():
|
| 111 |
+
"""Initialize the language model"""
|
| 112 |
+
try:
|
| 113 |
+
# Using Mistral model through Hugging Face Hub
|
| 114 |
+
llm = HuggingFaceHub(
|
| 115 |
+
repo_id="mistralai/Mistral-7B-Instruct-v0.1",
|
| 116 |
+
huggingfacehub_api_token=os.environ.get('HUGGINGFACE_API_TOKEN'),
|
| 117 |
+
model_kwargs={
|
| 118 |
+
"temperature": 0.7,
|
| 119 |
+
"max_new_tokens": 512,
|
| 120 |
+
"top_p": 0.95,
|
| 121 |
+
"repetition_penalty": 1.15
|
| 122 |
+
}
|
| 123 |
)
|
| 124 |
+
return llm
|
|
|
|
| 125 |
except Exception as e:
|
| 126 |
+
print(f"Error initializing LLM: {e}")
|
| 127 |
raise
|
| 128 |
|
| 129 |
+
|
| 130 |
class ChatSession:
|
| 131 |
def __init__(self, session_id):
|
| 132 |
self.session_id = session_id
|
|
|
|
| 231 |
|
| 232 |
self.important_info = []
|
| 233 |
|
| 234 |
+
print("Starting application initialization...")
|
| 235 |
|
| 236 |
+
try:
|
| 237 |
+
print("Initializing database...")
|
| 238 |
+
init_db()
|
| 239 |
+
print("Database initialized successfully")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 240 |
|
| 241 |
+
print("Initializing LLM...")
|
| 242 |
+
llm = initialize_llm()
|
| 243 |
+
if llm is None:
|
| 244 |
+
raise ValueError("LLM initialization failed")
|
| 245 |
+
print("LLM initialized successfully")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
|
| 247 |
+
print("Creating LLM chain...")
|
| 248 |
+
llm_chain = LLMChain(llm=llm, prompt=prompt)
|
| 249 |
+
print("LLM chain created successfully")
|
| 250 |
+
|
| 251 |
+
except Exception as e:
|
| 252 |
+
print(f"Fatal initialization error: {e}")
|
| 253 |
+
raise
|
| 254 |
+
|
| 255 |
+
|
| 256 |
# Rest of the prompt template and other configurations remain the same
|
| 257 |
prompt_template = """
|
| 258 |
Role: You are Figr Code Assistant, specializing in providing clear, error-free Python code solutions.
|
|
|
|
| 432 |
|
| 433 |
@app.route("/api/chat", methods=["POST"])
|
| 434 |
def chat():
|
| 435 |
+
if not llm_chain:
|
|
|
|
| 436 |
return jsonify({
|
| 437 |
+
"success": False,
|
| 438 |
+
"response": "System is still initializing. Please try again in a moment."
|
| 439 |
})
|
| 440 |
data = request.json
|
| 441 |
user_input = data.get("message", "")
|
|
|
|
| 683 |
return render_template("index.html")
|
| 684 |
|
| 685 |
|
| 686 |
+
|
| 687 |
|
| 688 |
if __name__ == "__main__":
|
| 689 |
app.run(host="0.0.0.0", port=PORT)
|