jewelzufo commited on
Commit
36b0eaf
·
verified ·
1 Parent(s): a677b25

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -56
app.py CHANGED
@@ -1,70 +1,101 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
3
 
 
 
 
 
 
 
4
 
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
14
- """
15
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
16
- """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
18
 
19
- messages = [{"role": "system", "content": system_message}]
 
20
 
21
- messages.extend(history)
 
 
 
 
 
 
 
22
 
23
- messages.append({"role": "user", "content": message})
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
- response = ""
26
 
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
38
 
39
- response += token
40
- yield response
 
 
 
 
41
 
 
 
 
 
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- chatbot = gr.ChatInterface(
47
- respond,
48
- type="messages",
49
- additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
54
- minimum=0.1,
55
- maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
- ],
61
- )
62
 
63
- with gr.Blocks() as demo:
64
- with gr.Sidebar():
65
- gr.LoginButton()
66
- chatbot.render()
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
 
69
  if __name__ == "__main__":
70
- demo.launch()
 
 
1
+ '''
2
+ This script creates a Gradio chatbot interface for the ibm-granite/granite-3.3-8b-instruct model.
3
 
4
+ Key Features:
5
+ - Loads the model and tokenizer from Hugging Face Hub.
6
+ - Uses a chat interface for interactive conversations.
7
+ - Manages chat history to maintain context.
8
+ - Handles API key management through Hugging Face Spaces secrets.
9
+ '''
10
 
11
+ import gradio as gr
12
+ import torch
13
+ from transformers import AutoModelForCausalLM, AutoTokenizer, set_seed
14
+ import os
 
 
 
 
 
 
 
 
 
15
 
16
+ # --- Configuration ---
17
+ MODEL_ID = "ibm-granite/granite-3.3-8b-instruct"
18
 
19
+ # --- Model and Tokenizer Loading ---
20
+ def load_model_and_tokenizer():
21
+ '''Load the model and tokenizer, handling potential errors.'''
22
+ try:
23
+ # Securely get the Hugging Face token from secrets
24
+ hf_token = os.getenv("HUGGINGFACE_TOKEN")
25
+ if not hf_token:
26
+ raise ValueError("HUGGINGFACE_TOKEN secret not found. Please add it to your Space settings.")
27
 
28
+ device = "cuda" if torch.cuda.is_available() else "cpu"
29
+
30
+ model = AutoModelForCausalLM.from_pretrained(
31
+ MODEL_ID,
32
+ device_map=device,
33
+ torch_dtype=torch.bfloat16,
34
+ token=hf_token
35
+ )
36
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, token=hf_token)
37
+
38
+ return model, tokenizer, device
39
+ except Exception as e:
40
+ # Provide a user-friendly error message
41
+ raise RuntimeError(f"Failed to load model or tokenizer: {e}")
42
 
43
+ model, tokenizer, device = load_model_and_tokenizer()
44
 
45
+ # --- Chatbot Logic ---
46
+ def chat_function(message, history):
47
+ '''
48
+ This function processes the user's message and returns the model's response.
49
+ '''
50
+ # Set seed for reproducibility
51
+ set_seed(42)
 
 
 
 
52
 
53
+ # Format the conversation history for the model
54
+ conv = []
55
+ for user_msg, model_msg in history:
56
+ conv.append({"role": "user", "content": user_msg})
57
+ conv.append({"role": "assistant", "content": model_msg})
58
+ conv.append({"role": "user", "content": message})
59
 
60
+ # Tokenize the input
61
+ input_ids = tokenizer.apply_chat_template(
62
+ conv,
63
+ return_tensors="pt",
64
+ thinking=False, # Set to False for direct response
65
+ add_generation_prompt=True
66
+ ).to(device)
67
 
68
+ # Generate the response
69
+ output = model.generate(
70
+ input_ids,
71
+ max_new_tokens=1024,
72
+ do_sample=True,
73
+ top_k=50,
74
+ top_p=0.95,
75
+ temperature=0.7,
76
+ )
 
 
 
 
 
 
 
 
 
 
77
 
78
+ # Decode the prediction
79
+ prediction = tokenizer.decode(output[0, input_ids.shape[1]:], skip_special_tokens=True)
80
+
81
+ return prediction
82
 
83
+ # --- Gradio Interface ---
84
+ def create_gradio_interface():
85
+ '''Create and return the Gradio ChatInterface.'''
86
+ return gr.ChatInterface(
87
+ fn=chat_function,
88
+ title="Granite 3.3 8B Chatbot",
89
+ description="A chatbot powered by the ibm-granite/granite-3.3-8b-instruct model. Ask any question!",
90
+ theme="soft",
91
+ examples=[
92
+ ["Hello, who are you?"],
93
+ ["What is the capital of France?"],
94
+ ["Explain the theory of relativity in simple terms."]
95
+ ]
96
+ )
97
 
98
+ # --- Main Execution ---
99
  if __name__ == "__main__":
100
+ chatbot_interface = create_gradio_interface()
101
+ chatbot_interface.launch()