import logging from huggingface_hub import hf_hub_download from llama_cpp import Llama import json import re logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') def load_model(): try: logging.info("Starting model download...") model_path = hf_hub_download("TheBloke/Mistral-7B-Instruct-v0.2-GGUF", filename="mistral-7b-instruct-v0.2.Q4_K_M.gguf") logging.info(f"Model downloaded to {model_path}") logging.info("Initializing Llama model...") llm = Llama(model_path=model_path, n_ctx=32768, n_gpu_layers=2) logging.info("Llama model initialized successfully") return llm except Exception as e: logging.error(f"Error loading model: {str(e)}", exc_info=True) return None llm = load_model() def get_llm_response(prompt): if llm is None: return {"error": "Model not loaded"} try: response = llm(prompt, max_tokens=2000) text_response = response['choices'][0]['text'] logging.info(f"Raw LLM response: {text_response}") json_match = re.search(r'\{.*\}', text_response, re.DOTALL) if json_match: json_str = json_match.group() json_str = re.sub(r'\\n', ' ', json_str) json_str = re.sub(r'\\', '', json_str) return json.loads(json_str) else: return {"error": "No valid JSON found in response"} except Exception as e: logging.error(f"Error in LLM response: {str(e)}") return {"error": str(e)}