Download app.py from sunder987/chatbot: direct link, hf CLI and curl.
- Browser
- Download file 1.16 kB
-
https://huggingface.co/spaces/sunder987/chatbot/resolve/main/app.py
- Command line
-
hf download hf://spaces/sunder987/chatbot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/sunder987/chatbot/resolve/main/app.py
1.16 kB
| 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() |