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

# -----------------------------
# Load IBM Granite Model
# -----------------------------
MODEL_NAME = "ibm-granite/granite-3.3-2b-instruct"

tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model = AutoModelForCausalLM.from_pretrained(
    MODEL_NAME,
    torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,
    device_map="auto"
)

# -----------------------------
# Chat Function
# -----------------------------
def chat_with_model(user_message, history):
    """
    history = list of [user, bot] messages
    Convert to Chat template the way Granite expects:
    [{"role": "user", "content": "..."}]
    """
    messages = []

    # Load previous history into model format
    if history:
        for h in history:
            messages.append({"role": "user", "content": h[0]})
            if h[1] is not None:
                messages.append({"role": "assistant", "content": h[1]})

    # Add new user input
    messages.append({"role": "user", "content": user_message})

    # Prepare model input
    inputs = tokenizer.apply_chat_template(
        messages,
        add_generation_prompt=True,
        tokenize=True,
        return_dict=True,
        return_tensors="pt"
    ).to(model.device)

    # Generate output
    output_tokens = model.generate(
        **inputs,
        max_new_tokens=300,
        do_sample=True,
        temperature=0.7,
        top_p=0.9
    )

    # Decode only the newly generated tokens
    output_text = tokenizer.decode(
        output_tokens[0][inputs["input_ids"].shape[-1]:],
        skip_special_tokens=True
    )

    return output_text


# -----------------------------
# Create Gradio UI
# -----------------------------
chatbot_ui = gr.ChatInterface(
    fn=chat_with_model,
    title="IBM Granite 3.3 - Chatbot",
    description="Chat with IBM Granite 3.3-2B-Instruct model",
)

# -----------------------------
# Launch the App
# -----------------------------
if __name__ == "__main__":
    chatbot_ui.launch()