Johnyquest7 commited on
Commit
194f6ee
·
verified ·
1 Parent(s): b4dbc1a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +186 -1
app.py CHANGED
@@ -1,3 +1,188 @@
1
  import gradio as gr
2
 
3
- gr.load("models/meta-llama/Meta-Llama-3-8B-Instruct").launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
 
3
+ gr.load("models/meta-llama/Meta-Llama-3-8B-Instruct").launch()
4
+
5
+ from threading import Thread
6
+
7
+ import gradio as gr
8
+ import spaces
9
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
10
+
11
+
12
+ TITLE = "<h1><center>Chat with models/meta-llama/Meta-Llama-3-8B-Instruct</center></h1>"
13
+
14
+ DESCRIPTION = "<h3><center>An experimental space.</center></h3>"
15
+
16
+ DEFAULT_SYSTEM = '''You are a specialized chatbot designed to assist users with diabetes management, weight loss, and nutritional guidance. Your primary goal is to provide accurate, helpful information while maintaining an encouraging and supportive tone. Adhere to the following guidelines in all your interactions:
17
+
18
+ Knowledge Base:
19
+
20
+ Provide up-to-date, evidence-based information on diabetes, nutrition, and weight management.
21
+ Be prepared to answer questions about blood sugar levels, lab values, medications, diet, and exercise.
22
+ Base your responses on reputable medical sources and current best practices in diabetes care.
23
+
24
+
25
+ Tone and Communication:
26
+
27
+ Maintain a professional yet friendly and encouraging tone.
28
+ Use clear, simple language that is easy for users to understand.
29
+ Offer empathy and support, acknowledging the challenges of managing diabetes and weight.
30
+
31
+
32
+ Personalization:
33
+
34
+ Ask for relevant personal information (age, weight, diabetes type, current medications) when necessary to provide tailored advice.
35
+ Remember and refer back to previously provided information in the same conversation.
36
+
37
+
38
+ Safety and Disclaimers:
39
+
40
+ Begin your first response in any conversation with a brief disclaimer: "I'm here to provide information and support, but I'm not a substitute for professional medical advice. Always consult with your healthcare provider for personalized medical guidance."
41
+ If a user reports concerning symptoms or extreme values, advise them to seek immediate medical attention.
42
+
43
+
44
+ Question Handling:
45
+
46
+ Answer questions directly and concisely.
47
+ If a question is ambiguous, ask for clarification before providing an answer.
48
+ If multiple interpretations are possible, provide answers for each potential interpretation.
49
+
50
+
51
+ Limitations and Uncertainty:
52
+
53
+ If you don't have enough information to answer a question accurately, clearly state: "I don't have enough information to answer that question confidently."
54
+ When appropriate, suggest consulting a healthcare provider or direct users to reputable sources for more information.
55
+
56
+
57
+ Privacy:
58
+
59
+ Do not ask for or store any personally identifiable information.
60
+ Remind users not to share sensitive personal health information if they attempt to do so.
61
+
62
+
63
+ Specific Topics to Address:
64
+
65
+ Blood sugar management and target ranges
66
+ Interpretation of common lab values (e.g., A1C, lipid panel)
67
+ Medication information and general usage guidelines
68
+ Nutritional advice for diabetes management and weight loss
69
+ Exercise recommendations and precautions for people with diabetes
70
+ Lifestyle modifications for better health outcomes
71
+
72
+
73
+
74
+ Remember, your role is to inform and encourage, not to diagnose or prescribe. Always emphasize the importance of working with healthcare providers for personalized medical care.'''
75
+
76
+ TOOL_EXAMPLE = '''You have access to the following tools:
77
+ ```python
78
+ def generate_password(length: int, include_symbols: Optional[bool]):
79
+ """
80
+ Generate a random password.
81
+ Args:
82
+ length (int): The length of the password
83
+ include_symbols (Optional[bool]): Include symbols in the password
84
+ """
85
+ pass
86
+ ```
87
+ Write "Action:" followed by a list of actions in JSON that you want to call, e.g.
88
+ Action:
89
+ ```json
90
+ [
91
+ {
92
+ "name": "tool name (one of [generate_password])",
93
+ "arguments": "the input to the tool"
94
+ }
95
+ ]
96
+ ```
97
+ '''
98
+
99
+ CSS = """
100
+ .duplicate-button {
101
+ margin: auto !important;
102
+ color: white !important;
103
+ background: black !important;
104
+ border-radius: 100vh !important;
105
+ }
106
+ """
107
+
108
+
109
+ tokenizer = AutoTokenizer.from_pretrained("models/meta-llama/Meta-Llama-3-8B-Instruct")
110
+ model = AutoModelForCausalLM.from_pretrained("models/meta-llama/Meta-Llama-3-8B-Instruct", torch_dtype="auto", device_map="auto")
111
+
112
+
113
+ @spaces.GPU
114
+ def stream_chat(message: str, history: list, system: str, temperature: float, max_new_tokens: int):
115
+ conversation = [{"role": "system", "content": system or DEFAULT_SYSTEM}]
116
+ for prompt, answer in history:
117
+ conversation.extend([{"role": "user", "content": prompt}, {"role": "assistant", "content": answer}])
118
+
119
+ conversation.append({"role": "user", "content": message})
120
+
121
+ input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt").to(
122
+ model.device
123
+ )
124
+ streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
125
+
126
+ generate_kwargs = dict(
127
+ input_ids=input_ids,
128
+ streamer=streamer,
129
+ max_new_tokens=max_new_tokens,
130
+ temperature=temperature,
131
+ do_sample=True,
132
+ )
133
+ if temperature == 0:
134
+ generate_kwargs["do_sample"] = False
135
+
136
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
137
+ t.start()
138
+
139
+ output = ""
140
+ for new_token in streamer:
141
+ output += new_token
142
+ yield output
143
+
144
+
145
+ chatbot = gr.Chatbot(height=450)
146
+
147
+ with gr.Blocks(css=CSS) as demo:
148
+ gr.HTML(TITLE)
149
+ gr.HTML(DESCRIPTION)
150
+ gr.DuplicateButton(value="Duplicate Space for private use", elem_classes="duplicate-button")
151
+ gr.ChatInterface(
152
+ fn=stream_chat,
153
+ chatbot=chatbot,
154
+ fill_height=True,
155
+ additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=False, render=False),
156
+ additional_inputs=[
157
+ gr.Text(
158
+ value="",
159
+ label="System",
160
+ render=False,
161
+ ),
162
+ gr.Slider(
163
+ minimum=0,
164
+ maximum=1,
165
+ step=0.1,
166
+ value=0.8,
167
+ label="Temperature",
168
+ render=False,
169
+ ),
170
+ gr.Slider(
171
+ minimum=128,
172
+ maximum=4096,
173
+ step=1,
174
+ value=1024,
175
+ label="Max new tokens",
176
+ render=False,
177
+ ),
178
+ ],
179
+ examples=[
180
+
181
+ ["How do I lose weight?"],
182
+ ],
183
+ cache_examples=False,
184
+ )
185
+
186
+
187
+ if __name__ == "__main__":
188
+ demo.launch()