Spaces:
Runtime error

File size: 1,157 Bytes
993eeff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
from transformers import pipeline
import gradio as gr

# Load model once (important for deployment efficiency)
pipe = pipeline(
    "text-generation",
    model="ibm-granite/granite-3.3-2b-instruct",
    torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
    device_map="auto"
)

def chat_with_granite(user_input):
    messages = [
        {"role": "user", "content": user_input}
    ]

    response = pipe(
        messages,
        max_new_tokens=256,
        temperature=0.7,
        do_sample=True
    )

    # Extract generated text safely
    if isinstance(response, list):
        output_text = response[0]["generated_text"][-1]["content"]
    else:
        output_text = str(response)

    return output_text


# Gradio Chat Interface
interface = gr.Interface(
    fn=chat_with_granite,
    inputs=gr.Textbox(
        lines=4,
        placeholder="Ask something...",
        label="User Input"
    ),
    outputs=gr.Textbox(label="Granite Response"),
    title="IBM Granite 3.3 Chatbot",
    description="Chatbot powered by IBM Granite 3.3 2B Instruct model."
)

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