Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import pipeline
|
| 3 |
+
|
| 4 |
+
# Load the text-generation pipeline
|
| 5 |
+
pipe = pipeline(
|
| 6 |
+
"text-generation",
|
| 7 |
+
model="ibm-granite/granite-3.3-2b-instruct",
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
def chat(user_input, history):
|
| 11 |
+
# Convert chat history to Granite-compatible message format
|
| 12 |
+
messages = []
|
| 13 |
+
for user_msg, bot_msg in history:
|
| 14 |
+
messages.append({"role": "user", "content": user_msg})
|
| 15 |
+
messages.append({"role": "assistant", "content": bot_msg})
|
| 16 |
+
|
| 17 |
+
messages.append({"role": "user", "content": user_input})
|
| 18 |
+
|
| 19 |
+
# Generate response
|
| 20 |
+
output = pipe(
|
| 21 |
+
messages,
|
| 22 |
+
max_new_tokens=256,
|
| 23 |
+
do_sample=True,
|
| 24 |
+
temperature=0.7,
|
| 25 |
+
top_p=0.9,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
# Extract assistant reply
|
| 29 |
+
assistant_reply = output[0]["generated_text"][-1]["content"]
|
| 30 |
+
|
| 31 |
+
return assistant_reply
|
| 32 |
+
|
| 33 |
+
# Gradio UI
|
| 34 |
+
with gr.Blocks() as demo:
|
| 35 |
+
gr.Markdown("# 🤖 IBM Granite 3.3 Chatbot")
|
| 36 |
+
gr.Markdown("Powered by **ibm-granite/granite-3.3-2b-instruct**")
|
| 37 |
+
|
| 38 |
+
chatbot = gr.Chatbot()
|
| 39 |
+
msg = gr.Textbox(
|
| 40 |
+
placeholder="Ask me anything...",
|
| 41 |
+
label="Your message"
|
| 42 |
+
)
|
| 43 |
+
clear = gr.Button("Clear")
|
| 44 |
+
|
| 45 |
+
def respond(message, chat_history):
|
| 46 |
+
bot_message = chat(message, chat_history)
|
| 47 |
+
chat_history.append((message, bot_message))
|
| 48 |
+
return "", chat_history
|
| 49 |
+
|
| 50 |
+
msg.submit(respond, [msg, chatbot], [msg, chatbot])
|
| 51 |
+
clear.click(lambda: [], None, chatbot)
|
| 52 |
+
|
| 53 |
+
demo.launch()
|