DanielNettoHeckert commited on
Commit
9ec1e40
·
verified ·
1 Parent(s): 735744e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -31
app.py CHANGED
@@ -1,32 +1,96 @@
1
  import gradio as gr
2
- from transformers import LlamaForCausalLM, LlamaTokenizer
3
- import torch
4
-
5
- class Chatbot:
6
- def __init__(self, model_name="meta-llama/Llama-3.1-8B"):
7
- self.tokenizer = LlamaTokenizer.from_pretrained(model_name)
8
- self.model = LlamaForCausalLM.from_pretrained(model_name)
9
-
10
- def respond(self, prompt):
11
- inputs = self.tokenizer.encode(prompt + self.tokenizer.eos_token, return_tensors="pt")
12
- outputs = self.model.generate(
13
- inputs,
14
- max_length=150,
15
- num_return_sequences=1,
16
- no_repeat_ngram_size=2,
17
- top_k=50,
18
- top_p=0.95,
19
- temperature=0.7,
20
- pad_token_id=self.tokenizer.eos_token_id
21
- )
22
- response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
23
- return response
24
-
25
- chatbot = Chatbot()
26
-
27
- def chatbot_interface(user_input):
28
- return chatbot.respond(user_input)
29
-
30
- interface = gr.Interface(fn=chatbot_interface, inputs="text", outputs="text", title="Chatbot LLaMA", description="Converse com seu chatbot!")
31
-
32
- interface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from huggingface_hub import InferenceClient
3
+
4
+ """
5
+ 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
6
+ """
7
+ client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
+ #client = InferenceClient("unsloth/Llama-3.2-1B-Instruct")
9
+
10
+
11
+ def respond(
12
+ message,
13
+ history: list[tuple[str, str]],
14
+ system_message,
15
+ max_tokens,
16
+ temperature,
17
+ top_p,
18
+ ):
19
+ messages = [{"role": "system", "content": system_message}]
20
+
21
+ for val in history:
22
+ if val[0]:
23
+ messages.append({"role": "user", "content": val[0]})
24
+ if val[1]:
25
+ messages.append({"role": "assistant", "content": val[1]})
26
+
27
+ messages.append({"role": "user", "content": message})
28
+
29
+ response = ""
30
+
31
+
32
+ try:
33
+ for message in client.chat_completion(
34
+ messages,
35
+ max_tokens=max_tokens,
36
+ stream=True,
37
+ temperature=temperature,
38
+ top_p=top_p,
39
+ ):
40
+ # Ensure the message has a valid structure
41
+ if not message or not isinstance(message, dict):
42
+ continue
43
+
44
+ try:
45
+ # Extract content and finish reason
46
+ content = message.choices[0].delta.content
47
+ finish_reason = message.choices[0].finish_reason
48
+
49
+ # Check if the content is empty
50
+ if content.strip() == "":
51
+ # If the finish reason is 'stop', it's expected and we can break the loop
52
+ if finish_reason == "stop":
53
+ print("Stream ended normally.")
54
+ break
55
+ else:
56
+ print("Received unexpected empty content, skipping...")
57
+ continue
58
+
59
+ response += content
60
+ yield response
61
+
62
+ except (AttributeError, IndexError, KeyError) as e:
63
+ print(f"Error processing message: {e}")
64
+ continue
65
+
66
+ except Exception as e:
67
+ print(f"Unexpected error: {e}")
68
+ yield "An error occurred while generating the response."
69
+
70
+ # Final check if the response is empty
71
+ if response.strip() == "":
72
+ yield "No response generated. Please try again or adjust the settings."
73
+
74
+
75
+ """
76
+ For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
77
+ """
78
+ demo = gr.ChatInterface(
79
+ respond,
80
+ additional_inputs=[
81
+ gr.Textbox(value="You are a friendly Chatbot. Your name is Juninho.", label="System message"),
82
+ gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
83
+ gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
84
+ gr.Slider(
85
+ minimum=0.1,
86
+ maximum=1.0,
87
+ value=0.95,
88
+ step=0.05,
89
+ label="Top-p (nucleus sampling)",
90
+ ),
91
+ ],
92
+ )
93
+
94
+
95
+ if __name__ == "__main__":
96
+ demo.launch()