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