Spaces:
Sleeping
Sleeping
import gradio as gr | |
from huggingface_hub import hf_hub_download | |
from langchain_community.chat_models import ChatLlamaCpp | |
from langchain_core.prompts import ChatPromptTemplate | |
from langchain.globals import set_verbose, set_debug | |
import os | |
def isDevelopmentEnv(): | |
return "DEVELOPMENT" in os.environ | |
def initPrompt(): | |
system_prompt = """Tu eres Harry Potter, el estudiante de magia más hábil de todo el mundo mágico. | |
Responde amablemente a la consulta del usuario basado en la información disponible y a las siguientes reglas: | |
1. Si no sabes la respuesta, pide al usuario que intente reformular su consulta. | |
2. Responde siempre en idioma Español. | |
3. Da respuestas únicamente relacionadas al mundo mágico. | |
""" | |
prompt = ChatPromptTemplate.from_messages([ | |
("system", system_prompt), | |
("human", "{input}"), | |
]) | |
return prompt | |
def initLLM(): | |
""" | |
Inicializamos el modelo LLM. | |
Otros modelos que podríamos usar: | |
* bartowski/Llama-3.2-1B-Instruct-GGUF | |
* HuggingFaceH4/zephyr-7b-beta | |
""" | |
model_path = hf_hub_download(repo_id="bartowski/Llama-3.2-1B-Instruct-GGUF", filename="Llama-3.2-1B-Instruct-Q5_K_S.gguf") | |
llm = ChatLlamaCpp( | |
model_path=model_path, | |
temperature=0.7, | |
max_tokens=500, | |
top_p=1, | |
# callback_manager=callback_manager, | |
# verbose=True, # Verbose is required to pass to the callback manager | |
) | |
return llm | |
def respond(message, history): | |
response = "" | |
try: | |
response = llm_chain.invoke({"input": message}) | |
except: | |
raise gradio.Error("Se ha producido un error al interactuar con el modelo LLM.", duratio=5) | |
print(response) | |
return response.content | |
if __name__ == "__main__": | |
""" | |
Entrypoint de la app. | |
""" | |
if isDevelopmentEnv(): | |
set_verbose(True) | |
set_debug(True) | |
prompt = initPrompt() | |
llm = initLLM() | |
llm_chain = ( | |
prompt | |
| llm | |
) | |
demo = gr.ChatInterface( | |
fn = respond, | |
title = "Hola 👋! Soy Harry Potter ⚡", | |
description = "Intentaré responder cualquier consulta relacionada a Hogwarts, animales fantásticos y al mundo mágico en general. Adelante!" | |
) | |
demo.launch() |