File size: 2,119 Bytes
10f8cb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

# Load model and tokenizer
model_name = "Qwen/Qwen2.5-3B-Instruct"

model = AutoModelForCausalLM.from_pretrained(
    model_name,
    torch_dtype="auto",
    device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained(model_name)

# Chat history
chat_history = []

# System prompt
SYSTEM_PROMPT = "You are Qwen/Qwen2.5-3B-Instruct, created by Alibaba Cloud. You are a helpful assistant."

def generate_response(user_input, history):
    # Build message list
    messages = [{"role": "system", "content": SYSTEM_PROMPT}]
    for user_msg, bot_msg in history:
        messages.append({"role": "user", "content": user_msg})
        messages.append({"role": "assistant", "content": bot_msg})
    messages.append({"role": "user", "content": user_input})

    # Apply chat template
    prompt_text = tokenizer.apply_chat_template(
        messages,
        tokenize=False,
        add_generation_prompt=True
    )

    # Tokenize
    model_inputs = tokenizer([prompt_text], return_tensors="pt").to(model.device)

    # Generate response
    generated_ids = model.generate(
        **model_inputs,
        max_new_tokens=512,
        do_sample=True,
        temperature=0.7,
        top_p=0.9
    )

    # Only return new tokens
    new_tokens = generated_ids[0][model_inputs.input_ids.shape[-1]:]
    response = tokenizer.decode(new_tokens, skip_special_tokens=True)

    # Update chat history
    history.append((user_input, response))
    return history, history

# Launch Gradio Chatbot UI
chatbot_ui = gr.ChatInterface(
    fn=generate_response,
    title="🧠 Qwen 2.5 3B - Chatbot",
    description="A simple chatbot interface powered by Qwen2.5-3B-Instruct (Alibaba Cloud).",
    theme="soft",
    examples = [
    "How can virtual reality (VR) influence consumer behavior towards sustainability?",
    "What impact does sustainable packaging have on consumer purchasing decisions?",
    "In what ways can education promote more sustainable consumer behaviors?"
],

)

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