Seymour-Visions commited on
Commit
ee88413
·
verified ·
1 Parent(s): 6b838d0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -44
app.py CHANGED
@@ -1,60 +1,51 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient #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
3
- import json
4
  import logging
5
 
6
- # Set up logging
7
  logging.basicConfig(level=logging.DEBUG)
8
  logger = logging.getLogger(__name__)
9
 
10
- # Read the system message from the file
11
- with open("system_message.txt", "r") as file:
12
- system_message = file.read().strip()
13
 
14
- client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
15
-
16
- def respond(message, history: list[tuple[str, str]], max_tokens, temperature, top_p):
17
- messages = [{"role": "system", "content": system_message}]
18
- for val in history:
19
- if val[0]:
20
- messages.append({"role": "user", "content": val[0]})
21
- if val[1]:
22
- messages.append({"role": "assistant", "content": val[1]})
23
  messages.append({"role": "user", "content": message})
24
-
25
- response = ""
 
 
 
 
26
  try:
27
- for message in client.chat_completion(
28
- messages, max_tokens=max_tokens, stream=True, temperature=temperature, top_p=top_p,
29
- ):
30
- try:
31
- token = message.choices[0].delta.content
32
- response += token
33
- yield response
34
- except json.JSONDecodeError as e:
35
- logger.error(f"JSON Decode Error: {e}")
36
- logger.debug(f"Problematic message: {message}")
37
- # Handle the error gracefully, maybe skip this token or return an error message
38
- continue
39
- except Exception as e:
40
- logger.error(f"Unexpected error processing token: {e}")
41
- continue
42
  except Exception as e:
43
- logger.error(f"Error in chat completion: {e}")
44
- yield "I'm sorry, but I encountered an error while processing your request."
45
 
46
- """
47
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
48
- """
49
  demo = gr.ChatInterface(
50
  respond,
51
- additional_inputs=[
52
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
53
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
54
- gr.Slider(
55
- minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)",
56
- ),
57
- ],
 
 
 
58
  )
59
 
60
  if __name__ == "__main__":
 
1
  import gradio as gr
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer
3
+ import torch
4
  import logging
5
 
 
6
  logging.basicConfig(level=logging.DEBUG)
7
  logger = logging.getLogger(__name__)
8
 
9
+ model_id = "mistralai/Mixtral-8x7B-Instruct-v0.1"
10
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
11
+ model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", torch_dtype=torch.float16)
12
 
13
+ def respond(message, history):
14
+ messages = []
15
+ for human, assistant in history:
16
+ messages.append({"role": "user", "content": human})
17
+ messages.append({"role": "assistant", "content": assistant})
 
 
 
 
18
  messages.append({"role": "user", "content": message})
19
+
20
+ logger.debug(f"Preparing input messages: {messages}")
21
+
22
+ inputs = tokenizer.apply_chat_template(messages, return_tensors="pt").to(model.device)
23
+ logger.debug(f"Tokenized input shape: {inputs.shape}")
24
+
25
  try:
26
+ outputs = model.generate(inputs, max_new_tokens=512, do_sample=True, temperature=0.7, top_p=0.95)
27
+ logger.debug(f"Generated output shape: {outputs.shape}")
28
+
29
+ response = tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True)
30
+ logger.debug(f"Decoded response: {response}")
31
+
32
+ return response
 
 
 
 
 
 
 
 
33
  except Exception as e:
34
+ logger.error(f"Error in model generation: {e}")
35
+ return "I'm sorry, but I encountered an error while processing your request."
36
 
 
 
 
37
  demo = gr.ChatInterface(
38
  respond,
39
+ chatbot=gr.Chatbot(height=300),
40
+ textbox=gr.Textbox(placeholder="Ask me anything", container=False, scale=7),
41
+ title="Mixtral-8x7B-Instruct-v0.1 Chat",
42
+ description="Chat with the Mixtral-8x7B-Instruct-v0.1 model.",
43
+ theme="soft",
44
+ examples=["What is machine learning?", "Explain quantum computing in simple terms."],
45
+ cache_examples=False,
46
+ retry_btn=None,
47
+ undo_btn="Delete Previous",
48
+ clear_btn="Clear",
49
  )
50
 
51
  if __name__ == "__main__":