Update llm_utils.py
Browse files- llm_utils.py +23 -7
llm_utils.py
CHANGED
|
@@ -1,27 +1,43 @@
|
|
| 1 |
import logging
|
| 2 |
-
from llama_cpp import Llama
|
| 3 |
from huggingface_hub import hf_hub_download
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 6 |
|
| 7 |
def load_model():
|
| 8 |
try:
|
| 9 |
-
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
except Exception as e:
|
| 12 |
-
logging.error(f"Error loading model: {str(e)}")
|
| 13 |
return None
|
| 14 |
|
| 15 |
llm = load_model()
|
| 16 |
|
| 17 |
def get_llm_response(prompt):
|
| 18 |
if llm is None:
|
| 19 |
-
return "
|
| 20 |
try:
|
| 21 |
response = llm(prompt, max_tokens=2000)
|
| 22 |
text_response = response['choices'][0]['text']
|
| 23 |
logging.info(f"Raw LLM response: {text_response}")
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
except Exception as e:
|
| 26 |
logging.error(f"Error in LLM response: {str(e)}")
|
| 27 |
-
return
|
|
|
|
| 1 |
import logging
|
|
|
|
| 2 |
from huggingface_hub import hf_hub_download
|
| 3 |
+
from llama_cpp import Llama
|
| 4 |
+
import json
|
| 5 |
+
import re
|
| 6 |
|
| 7 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 8 |
|
| 9 |
def load_model():
|
| 10 |
try:
|
| 11 |
+
logging.info("Starting model download...")
|
| 12 |
+
model_path = hf_hub_download("TheBloke/Mistral-7B-Instruct-v0.2-GGUF",
|
| 13 |
+
filename="mistral-7b-instruct-v0.2.Q4_K_M.gguf")
|
| 14 |
+
logging.info(f"Model downloaded to {model_path}")
|
| 15 |
+
logging.info("Initializing Llama model...")
|
| 16 |
+
llm = Llama(model_path=model_path, n_ctx=32768, n_gpu_layers=2)
|
| 17 |
+
logging.info("Llama model initialized successfully")
|
| 18 |
+
return llm
|
| 19 |
except Exception as e:
|
| 20 |
+
logging.error(f"Error loading model: {str(e)}", exc_info=True)
|
| 21 |
return None
|
| 22 |
|
| 23 |
llm = load_model()
|
| 24 |
|
| 25 |
def get_llm_response(prompt):
|
| 26 |
if llm is None:
|
| 27 |
+
return {"error": "Model not loaded"}
|
| 28 |
try:
|
| 29 |
response = llm(prompt, max_tokens=2000)
|
| 30 |
text_response = response['choices'][0]['text']
|
| 31 |
logging.info(f"Raw LLM response: {text_response}")
|
| 32 |
+
|
| 33 |
+
json_match = re.search(r'\{.*\}', text_response, re.DOTALL)
|
| 34 |
+
if json_match:
|
| 35 |
+
json_str = json_match.group()
|
| 36 |
+
json_str = re.sub(r'\\n', ' ', json_str)
|
| 37 |
+
json_str = re.sub(r'\\', '', json_str)
|
| 38 |
+
return json.loads(json_str)
|
| 39 |
+
else:
|
| 40 |
+
return {"error": "No valid JSON found in response"}
|
| 41 |
except Exception as e:
|
| 42 |
logging.error(f"Error in LLM response: {str(e)}")
|
| 43 |
+
return {"error": str(e)}
|