File size: 3,237 Bytes
79adf4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import gradio as gr
from huggingface_hub import InferenceClient
import os

# Obt茅n el token de manera segura desde el entorno
hf_token = os.getenv("HF_API_TOKEN")

# Clase para manejar m煤ltiples modelos
class ModelHandler:
    def __init__(self, model_names, token):
        """
        Inicializa el manejador de modelos con los nombres de los modelos y el token de API.
        """
        self.clients = {
            model_name: InferenceClient(model_name, token=token)
            for model_name in model_names
        }
        self.current_model = model_names[0]

    def switch_model(self, model_name):
        """
        Cambia el modelo actual.
        """
        if model_name in self.clients:
            self.current_model = model_name
        else:
            raise ValueError(f"Modelo {model_name} no est谩 disponible.")

    def generate_response(self, input_text):
        """
        Genera una respuesta utilizando el modelo actual.
        """
        prompt = f"Debes de responder a cualquier pregunta:\nPregunta: {input_text}"
        try:
            messages = [{"role": "user", "content": prompt}]
            client = self.clients[self.current_model]
            response = client.chat_completion(messages=messages, max_tokens=500)
            if hasattr(response, 'choices') and response.choices:
                return response.choices[0].message.content
            else:
                return str(response)
        except Exception as e:
            return f"Error al realizar la inferencia: {e}"

# Lista de modelos disponibles
model_names = [
    "microsoft/Phi-3-mini-4k-instruct",
    "bigscience/bloomz-560m",
    "tiiuae/falcon-7b-instruct"
]

# Inicializa el manejador de modelos
model_handler = ModelHandler(model_names, hf_token)

# Configura la interfaz en Gradio con selecci贸n de modelos
with gr.Blocks(title="Multi-Model LLM Chatbot") as demo:
    gr.Markdown(
        """
        ## Chatbot Multi-Modelo LLM
        Este chatbot permite elegir entre m煤ltiples modelos de lenguaje para responder preguntas. 
        Selecciona un modelo, escribe tu consulta, y presiona el bot贸n de enviar para obtener una respuesta.
        """
    )
    with gr.Row():
        model_dropdown = gr.Dropdown(
            choices=model_names,
            value=model_names[0],
            label="Seleccionar Modelo",
            interactive=True
        )
    with gr.Row():
        with gr.Column():
            input_text = gr.Textbox(
                lines=5,
                placeholder="Escribe tu pregunta aqu铆...",
                label="Pregunta"
            )
        with gr.Column():
            output_text = gr.Textbox(
                lines=5,
                label="Respuesta",
                interactive=False
            )
    submit_button = gr.Button("Enviar")
    
    # Define la funci贸n de actualizaci贸n
    def process_input(selected_model, user_input):
        model_handler.switch_model(selected_model)
        return model_handler.generate_response(user_input)
    
    # Conecta la funci贸n a los componentes
    submit_button.click(
        fn=process_input,
        inputs=[model_dropdown, input_text],
        outputs=output_text
    )

# Lanza la interfaz
demo.launch()