Threatthriver commited on
Commit
29567f1
1 Parent(s): 3e4a10f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -62
app.py CHANGED
@@ -1,82 +1,50 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
3
 
4
- # Define available models and their Hugging Face IDs
5
- available_models = {
6
- "Zephyr 7B Beta": "HuggingFaceH4/zephyr-7b-beta",
7
- # Add more models here as needed
8
- }
9
 
10
- def respond(
11
- message: str,
12
- history: list[tuple[str, str]],
13
- system_message: str,
14
- max_tokens: int,
15
- temperature: float,
16
- top_p: float,
17
- model_name: str,
18
- ):
19
  """
20
- Generates a response from the AI model based on the user's message and chat history.
21
  """
22
- client = InferenceClient(model=available_models[model_name])
23
-
24
- # Prepare the conversation history for the API call
25
- messages = [{"role": "system", "content": system_message}]
26
- for user_input, assistant_response in history:
27
- messages.append({"role": "user", "content": user_input})
28
- messages.append({"role": "assistant", "content": assistant_response})
29
- messages.append({"role": "user", "content": message})
30
-
31
- streamed_response = ""
32
-
33
- try:
34
- # Generate a response from the model with streaming
35
- for response in client.chat_completion(
36
- messages=messages,
37
- max_tokens=max_tokens,
38
- stream=True,
39
  temperature=temperature,
40
  top_p=top_p,
41
- ):
42
- chunk = response.choices[0].delta.get("content", "")
43
- streamed_response += chunk
44
- yield streamed_response
45
-
46
- except Exception as e:
47
- yield f"**Error:** {str(e)}"
48
-
49
 
50
- def update_chatbox(history, message, model_name, system_message, max_tokens, temperature, top_p):
51
  """
52
  Update the chat history and generate the next AI response.
53
  """
54
  history.append(("User", message)) # Add user message to history
55
- ai_response = next(respond(
56
- message=message,
57
- history=history,
58
- system_message=system_message,
59
- max_tokens=max_tokens,
60
- temperature=temperature,
61
- top_p=top_p,
62
- model_name=model_name
63
- ))
64
- history.append(("AI", ai_response)) # Add AI response to history
65
  return history, "" # Return updated history and clear the user input
66
 
67
  # Define the Gradio interface with the Blocks context
68
  with gr.Blocks(css=".gradio-container {border: none;}") as demo:
69
  chat_history = gr.State([]) # Initialize an empty chat history state
70
- system_message = gr.Textbox(
71
- value="You are a friendly and helpful assistant.",
72
- label="System message",
73
- lines=2
74
- )
75
- max_tokens = gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens")
76
  temperature = gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="Temperature")
77
- top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)")
78
- model_dropdown = gr.Dropdown(choices=list(available_models.keys()), value="Zephyr 7B Beta", label="Select Model")
79
-
80
  chatbot = gr.Chatbot(label="Character-like AI Chat")
81
 
82
  user_input = gr.Textbox(show_label=False, placeholder="Type your message here...")
@@ -85,7 +53,7 @@ with gr.Blocks(css=".gradio-container {border: none;}") as demo:
85
  # When the send button is clicked, update chat history
86
  send_button.click(
87
  fn=update_chatbox,
88
- inputs=[chat_history, user_input, model_dropdown, system_message, max_tokens, temperature, top_p],
89
  outputs=[chatbot, user_input], # Update chatbox and clear user input
90
  queue=True # Ensure responses are shown in order
91
  )
 
1
  import gradio as gr
2
+ import torch
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM
4
 
5
+ # Load the tokenizer and model (lightweight model as per your suggestion)
6
+ tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3.1-8B-Instruct")
7
+ model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3.1-8B-Instruct")
 
 
8
 
9
+ device = "cuda" if torch.cuda.is_available() else "cpu"
10
+ model = model.to(device)
11
+
12
+ def generate_response(message, history, max_tokens, temperature, top_p):
 
 
 
 
 
13
  """
14
+ Generates a response from the model.
15
  """
16
+ # Prepare conversation history as input
17
+ input_ids = tokenizer.encode(message + tokenizer.eos_token, return_tensors="pt").to(device)
18
+
19
+ # Generate the output using the model
20
+ with torch.no_grad():
21
+ output = model.generate(
22
+ input_ids,
23
+ max_length=max_tokens,
 
 
 
 
 
 
 
 
 
24
  temperature=temperature,
25
  top_p=top_p,
26
+ pad_token_id=tokenizer.eos_token_id,
27
+ )
28
+
29
+ response = tokenizer.decode(output[:, input_ids.shape[-1]:][0], skip_special_tokens=True)
30
+ history.append((message, response))
31
+ return history, ""
 
 
32
 
33
+ def update_chatbox(history, message, max_tokens, temperature, top_p):
34
  """
35
  Update the chat history and generate the next AI response.
36
  """
37
  history.append(("User", message)) # Add user message to history
38
+ history, _ = generate_response(message, history, max_tokens, temperature, top_p)
 
 
 
 
 
 
 
 
 
39
  return history, "" # Return updated history and clear the user input
40
 
41
  # Define the Gradio interface with the Blocks context
42
  with gr.Blocks(css=".gradio-container {border: none;}") as demo:
43
  chat_history = gr.State([]) # Initialize an empty chat history state
44
+ max_tokens = gr.Slider(minimum=1, maximum=1024, value=256, step=1, label="Max Tokens")
 
 
 
 
 
45
  temperature = gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="Temperature")
46
+ top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.9, step=0.05, label="Top-p (nucleus sampling)")
47
+
 
48
  chatbot = gr.Chatbot(label="Character-like AI Chat")
49
 
50
  user_input = gr.Textbox(show_label=False, placeholder="Type your message here...")
 
53
  # When the send button is clicked, update chat history
54
  send_button.click(
55
  fn=update_chatbox,
56
+ inputs=[chat_history, user_input, max_tokens, temperature, top_p],
57
  outputs=[chatbot, user_input], # Update chatbox and clear user input
58
  queue=True # Ensure responses are shown in order
59
  )