File size: 1,728 Bytes
09ba624
76a9806
 
473b660
76a9806
 
473b660
76a9806
 
 
473b660
76a9806
473b660
 
 
 
 
 
 
 
 
 
 
76a9806
 
 
473b660
76a9806
 
 
 
473b660
76a9806
607faa4
473b660
 
09ba624
473b660
 
 
 
 
 
 
09ba624
473b660
 
09ba624
473b660
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
import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

# Model name
MODEL_NAME = "Qwen/Qwen2.5-0.5B-Instruct-GGUF"

# Load tokenizer and model
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, torch_dtype=torch.float16, device_map="auto")

def respond(message, history: list[tuple[str, str]], system_message, max_tokens, temperature, top_p):
    messages = [{"role": "system", "content": system_message}]
    
    # Add chat history to messages
    for user_msg, assistant_msg in history:
        if user_msg:
            messages.append({"role": "user", "content": user_msg})
        if assistant_msg:
            messages.append({"role": "assistant", "content": assistant_msg})
    
    messages.append({"role": "user", "content": message})
    
    # Tokenize input
    inputs = tokenizer(message, return_tensors="pt").to("cpu")
    
    # Generate response
    with torch.no_grad():
        outputs = model.generate(
            **inputs, max_length=max_tokens, temperature=temperature, top_p=top_p
        )
    
    response = tokenizer.decode(outputs[0], skip_special_tokens=True)
    return response

# Define Gradio interface
demo = gr.ChatInterface(
    respond,
    additional_inputs=[
        gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
        gr.Slider(minimum=1, maximum=512, value=64, step=1, label="Max new tokens"),
        gr.Slider(minimum=0.1, maximum=1.5, value=0.3, step=0.1, label="Temperature"),
        gr.Slider(minimum=0.1, maximum=0.8, value=0.75, step=0.05, label="Top-p (nucleus sampling)"),
    ],
)

# Launch Gradio app
if __name__ == "__main__":
    demo.launch()