File size: 1,948 Bytes
3fb378d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fced669
3fb378d
 
 
 
 
 
 
 
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
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
from threading import Thread
import gradio as gr

# Configuración del modelo
MODEL_NAME = "microsoft/phi-2"  # Modelo ligero y eficiente

# Cargar modelo y tokenizer
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
    MODEL_NAME,
    torch_dtype=torch.float16,
    device_map="auto"
)

def generate_response(message, history, system_prompt="Eres un asistente útil llamado Gerardo."):
    # Formatear el historial de chat
    messages = [{"role": "system", "content": system_prompt}]
    for user_msg, bot_msg in history:
        messages.extend([
            {"role": "user", "content": user_msg},
            {"role": "assistant", "content": bot_msg}
        ])
    messages.append({"role": "user", "content": message})

    # Generar respuesta con streaming
    inputs = tokenizer.apply_chat_template(messages, return_tensors="pt").to(model.device)
    streamer = TextIteratorStreamer(tokenizer, skip_prompt=True)
    
    Thread(
        target=model.generate,
        kwargs=dict(
            inputs,
            streamer=streamer,
            max_new_tokens=512,
            temperature=0.7,
            do_sample=True
        )
    ).start()

    # Retornar la respuesta progresivamente
    response = ""
    for token in streamer:
        response += token
        yield response

# Interfaz con Gradio
demo = gr.ChatInterface(
    fn=generate_response,
    title="🤖 Chatbot Gerardo",
    description="Un asistente IA creado por Gerardo. ¡Pregúntame lo que quieras!",
    examples=["Hola", "¿Cómo funciona la inteligencia artificial?"],
    additional_inputs=[
        gr.Textbox(
            "Eres un asistente útil llamado Gerardo .",
            label="Personalidad del bot"
        )
    ],
    theme="soft"
)

if __name__ == "__main__":
    demo.launch()