import asyncio from functools import lru_cache from huggingface_hub import hf_hub_download from llama_cpp import Llama MODEL_PATH = hf_hub_download("TheBloke/Mistral-7B-Instruct-v0.2-GGUF", filename="mistral-7b-instruct-v0.2.Q4_K_M.gguf") @lru_cache(maxsize=1) def get_llm(): return Llama(model_path=MODEL_PATH, n_ctx=2048, n_gpu_layers=1) llm = get_llm() async def llm_generate(prompt: str) -> str: loop = asyncio.get_running_loop() response = await loop.run_in_executor(None, lambda: llm(prompt, max_tokens=512, stop=[""], echo=False)) return response['choices'][0]['text'].strip()