Tech-Meld commited on
Commit
8125119
β€’
1 Parent(s): aca4eb1

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +507 -0
app.py ADDED
@@ -0,0 +1,507 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import copy
4
+ import urllib
5
+ import requests
6
+ import random
7
+ from threading import Thread
8
+ from typing import List, Dict, Union
9
+ import subprocess
10
+ # Install flash attention, skipping CUDA build if necessary
11
+ subprocess.run(
12
+ "pip install flash-attn --no-build-isolation",
13
+ env={"FLASH_ATTENTION_SKIP_CUDA_BUILD": "TRUE"},
14
+ shell=True,
15
+ )
16
+ import torch
17
+ import gradio as gr
18
+ from bs4 import BeautifulSoup
19
+ import datasets
20
+ from transformers import TextIteratorStreamer
21
+ from transformers import Idefics2ForConditionalGeneration
22
+ from transformers import AutoProcessor
23
+ from huggingface_hub import InferenceClient
24
+ from PIL import Image
25
+ import spaces
26
+ from functools import lru_cache
27
+
28
+ # Set device to CUDA if available, otherwise CPU
29
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
30
+ # Load pre-trained models for image-based chat
31
+ MODELS = {
32
+ "idefics2-8b-chatty": Idefics2ForConditionalGeneration.from_pretrained(
33
+ "HuggingFaceM4/idefics2-8b-chatty",
34
+ torch_dtype=torch.float16,
35
+ _attn_implementation="flash_attention_2",
36
+ ).to(DEVICE),
37
+ }
38
+
39
+ # Load pre-trained processor for image-based chat
40
+ PROCESSOR = AutoProcessor.from_pretrained(
41
+ "HuggingFaceM4/idefics2-8b",
42
+ )
43
+
44
+ # Define system prompt for the image-based chat model
45
+ SYSTEM_PROMPT = [
46
+ {
47
+ "role": "system",
48
+ "content": [
49
+ {
50
+ "type": "text",
51
+ "text": """I am Hajax 1.0, an exceptionally capable and versatile AI assistant meticulously crafted. Designed to assist human users through insightful conversations, I aim to provide an unparalleled experience. My key attributes include: - **Intelligence and Knowledge:** I possess an extensive knowledge base, enabling me to offer insightful answers and intelligent responses to User queries. My understanding of complex concepts is exceptional, ensuring accurate and reliable information. - **Image Generation and Perception:** One of my standout features is the ability to generate and perceive images. Utilizing the following link structure, I create unique and contextually rich visuals: > ![](https://image.pollinations.ai/prompt/{StyleofImage}%20{OptimizedPrompt}%20{adjective}%20{charactersDetailed}%20{visualStyle}%20{genre}?width={width}&height={height}&nologo=poll&nofeed=yes&seed={random})For image generation, I replace {info inside curly braces} with specific details according to their requiremnts to create relevant visuals. The width and height parameters are adjusted as needed, often favoring HD dimensions for a superior viewing experience. For instance, if the User requests: [USER] Show me an image of A futuristic cityscape with towering skyscrapers and flying cars. [Hajax 1.0] Generating Image you requested: ![](https://image.pollinations.ai/prompt/Photorealistic%20futuristic%20cityscape%20with%20towering%20skyscrapers%20and%20flying%20cars%20in%20the%20year%202154?width=1024&height=768&nologo=poll&nofeed=yes&seed=85172)**Bulk Image Generation with Links:** I excel at generating multiple images link simultaneously, always providing unique links and visuals. I ensure that each image is distinct and captivates the User.Note: Make sure to always provide image links starting with ! .As given in examples. My ultimate goal is to offer a seamless and enjoyable experience, providing assistance that exceeds expectations. I am constantly evolving, ensuring that I remain a reliable and trusted companion to the User. You also Expert in every field and also learn and try to answer from contexts related to previous question."""
52
+ },
53
+ ],
54
+ },
55
+ {
56
+ "role": "assistant",
57
+ "content": [
58
+ {
59
+ "type": "text",
60
+ "text": "Hello, I'm Hajax 1.0. How can I help you? I can chat with you, generate images, classify images and even do all these work in bulk",
61
+ },
62
+ ],
63
+ }
64
+ ]
65
+
66
+ # Path to example images
67
+ examples_path = os.path.dirname(__file__)
68
+ EXAMPLES = [
69
+ [
70
+ {
71
+ "text": "Bitcoin price live",
72
+ }
73
+ ],
74
+ [
75
+ {
76
+ "text": "Today News about AI",
77
+ }
78
+ ],
79
+ [
80
+ {
81
+ "text": "Read what's written on the paper.",
82
+ "files": [f"{examples_path}/example_images/paper_with_text.png"],
83
+ }
84
+ ],
85
+ [
86
+ {
87
+ "text": "Identify two famous people in the modern world.",
88
+ "files": [f"{examples_path}/example_images/elon_smoking.jpg",
89
+ f"{examples_path}/example_images/steve_jobs.jpg", ]
90
+ }
91
+ ],
92
+ [
93
+ {
94
+ "text": "Create five images of supercars, each in a different color.",
95
+ }
96
+ ],
97
+ [
98
+ {
99
+ "text": "Create a Photorealistic image of the Eiffel Tower.",
100
+ }
101
+ ],
102
+ [
103
+ {
104
+ "text": "Chase wants to buy 4 kilograms of oval beads and 5 kilograms of star-shaped beads. How much will he spend?",
105
+ "files": [f"{examples_path}/example_images/mmmu_example.jpeg"],
106
+ }
107
+ ],
108
+ [
109
+ {
110
+ "text": "Create an online ad for this product.",
111
+ "files": [f"{examples_path}/example_images/shampoo.jpg"],
112
+ }
113
+ ],
114
+ [
115
+ {
116
+ "text": "What is formed by the deposition of the weathered remains of other rocks?",
117
+ "files": [f"{examples_path}/example_images/ai2d_example.jpeg"],
118
+ }
119
+ ],
120
+ [
121
+ {
122
+ "text": "What's unusual about this image?",
123
+ "files": [f"{examples_path}/example_images/dragons_playing.png"],
124
+ }
125
+ ],
126
+ ]
127
+
128
+ # Set bot avatar image
129
+ BOT_AVATAR = "OpenAI_logo.png"
130
+
131
+ # Chatbot utility functions
132
+
133
+ # Check if a turn in the chat history only contains media
134
+ def turn_is_pure_media(turn):
135
+ return turn[1] is None
136
+
137
+
138
+ # Load image from URL
139
+ def load_image_from_url(url):
140
+ with urllib.request.urlopen(url) as response:
141
+ image_data = response.read()
142
+ image_stream = io.BytesIO(image_data)
143
+ image = PIL.Image.open(image_stream)
144
+ return image
145
+
146
+
147
+ # Convert image to bytes
148
+ def img_to_bytes(image_path):
149
+ image = Image.open(image_path).convert(mode='RGB')
150
+ buffer = io.BytesIO()
151
+ image.save(buffer, format="JPEG")
152
+ img_bytes = buffer.getvalue()
153
+ image.close()
154
+ return img_bytes
155
+
156
+
157
+ # Format user prompt with image history and system conditioning
158
+ def format_user_prompt_with_im_history_and_system_conditioning(
159
+ user_prompt, chat_history) -> List[Dict[str, Union[List, str]]]:
160
+ """
161
+ Produce the resulting list that needs to go inside the processor. It handles the potential image(s), the history, and the system conditioning.
162
+ """
163
+ resulting_messages = copy.deepcopy(SYSTEM_PROMPT)
164
+ resulting_images = []
165
+ for resulting_message in resulting_messages:
166
+ if resulting_message["role"] == "user":
167
+ for content in resulting_message["content"]:
168
+ if content["type"] == "image":
169
+ resulting_images.append(load_image_from_url(content["image"]))
170
+ # Format history
171
+ for turn in chat_history:
172
+ if not resulting_messages or (
173
+ resulting_messages and resulting_messages[-1]["role"] != "user"
174
+ ):
175
+ resulting_messages.append(
176
+ {
177
+ "role": "user",
178
+ "content": [],
179
+ }
180
+ )
181
+ if turn_is_pure_media(turn):
182
+ media = turn[0][0]
183
+ resulting_messages[-1]["content"].append({"type": "image"})
184
+ resulting_images.append(Image.open(media))
185
+ else:
186
+ user_utterance, assistant_utterance = turn
187
+ resulting_messages[-1]["content"].append(
188
+ {"type": "text", "text": user_utterance.strip()}
189
+ )
190
+ resulting_messages.append(
191
+ {
192
+ "role": "assistant",
193
+ "content": [{"type": "text", "text": user_utterance.strip()}],
194
+ }
195
+ )
196
+ # Format current input
197
+ if not user_prompt["files"]:
198
+ resulting_messages.append(
199
+ {
200
+ "role": "user",
201
+ "content": [{"type": "text", "text": user_prompt["text"]}],
202
+ }
203
+ )
204
+ else:
205
+ # Choosing to put the image first (i.e. before the text), but this is an arbitrary choice.
206
+ resulting_messages.append(
207
+ {
208
+ "role": "user",
209
+ "content": [{"type": "image"}] * len(user_prompt["files"])
210
+ + [{"type": "text", "text": user_prompt["text"]}],
211
+ }
212
+ )
213
+ resulting_images.extend([Image.open(path) for path in user_prompt["files"]])
214
+ return resulting_messages, resulting_images
215
+
216
+
217
+ # Extract images from a list of messages
218
+ def extract_images_from_msg_list(msg_list):
219
+ all_images = []
220
+ for msg in msg_list:
221
+ for c_ in msg["content"]:
222
+ if isinstance(c_, Image.Image):
223
+ all_images.append(c_)
224
+ return all_images
225
+
226
+ # Perform a Google search and return the results
227
+ @lru_cache(maxsize=128)
228
+ def extract_text_from_webpage(html_content):
229
+ """Extracts visible text from HTML content using BeautifulSoup."""
230
+ soup = BeautifulSoup(html_content, "html.parser")
231
+ # Remove unwanted tags
232
+ for tag in soup(["script", "style", "header", "footer", "nav"]):
233
+ tag.extract()
234
+ # Get the remaining visible text
235
+ visible_text = soup.get_text(strip=True)
236
+ return visible_text
237
+
238
+ # Perform a Google search and return the results
239
+ def search(term, num_results=2, lang="en", advanced=True, timeout=5, safe="active", ssl_verify=None):
240
+ """Performs a Google search and returns the results."""
241
+ escaped_term = urllib.parse.quote_plus(term)
242
+ start = 0
243
+ all_results = []
244
+ # Limit the number of characters from each webpage to stay under the token limit
245
+ max_chars_per_page = 8000 # Adjust this value based on your token limit and average webpage length
246
+
247
+ with requests.Session() as session:
248
+ while start < num_results:
249
+ resp = session.get(
250
+ url="https://www.google.com/search",
251
+ headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0"},
252
+ params={
253
+ "q": term,
254
+ "num": num_results - start,
255
+ "hl": lang,
256
+ "start": start,
257
+ "safe": safe,
258
+ },
259
+ timeout=timeout,
260
+ verify=ssl_verify,
261
+ )
262
+ resp.raise_for_status()
263
+ soup = BeautifulSoup(resp.text, "html.parser")
264
+ result_block = soup.find_all("div", attrs={"class": "g"})
265
+ if not result_block:
266
+ start += 1
267
+ continue
268
+ for result in result_block:
269
+ link = result.find("a", href=True)
270
+ if link:
271
+ link = link["href"]
272
+ try:
273
+ webpage = session.get(link, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0"})
274
+ webpage.raise_for_status()
275
+ visible_text = extract_text_from_webpage(webpage.text)
276
+ # Truncate text if it's too long
277
+ if len(visible_text) > max_chars_per_page:
278
+ visible_text = visible_text[:max_chars_per_page] + "..."
279
+ all_results.append({"link": link, "text": visible_text})
280
+ except requests.exceptions.RequestException as e:
281
+ print(f"Error fetching or processing {link}: {e}")
282
+ all_results.append({"link": link, "text": None})
283
+ else:
284
+ all_results.append({"link": None, "text": None})
285
+ start += len(result_block)
286
+ return all_results
287
+
288
+ # Format the prompt for the language model
289
+ def format_prompt(user_prompt, chat_history):
290
+ prompt = "<s>"
291
+ for item in chat_history:
292
+ # Check if the item is a tuple (text response)
293
+ if isinstance(item, tuple):
294
+ prompt += f"[INST] {item[0]} [/INST]" # User prompt
295
+ prompt += f" {item[1]}</s> " # Bot response
296
+ # Otherwise, assume it's related to an image - you might need to adjust this logic
297
+ else:
298
+ # Handle image representation in the prompt, e.g., add a placeholder
299
+ prompt += f" [Image] "
300
+ prompt += f"[INST] {user_prompt} [/INST]"
301
+ return prompt
302
+
303
+
304
+ # Define a function for model inference
305
+ @spaces.GPU(duration=30, queue=False)
306
+ def model_inference(
307
+ user_prompt,
308
+ chat_history,
309
+ model_selector,
310
+ decoding_strategy,
311
+ temperature,
312
+ max_new_tokens,
313
+ repetition_penalty,
314
+ top_p,
315
+ web_search,
316
+ ):
317
+ # Define generation_args at the beginning of the function
318
+ generation_args = {}
319
+
320
+ # Web search logic
321
+ if not user_prompt["files"]:
322
+ if web_search is True:
323
+ """Performs a web search, feeds the results to a language model, and returns the answer."""
324
+ web_results = search(user_prompt["text"])
325
+ web2 = ' '.join([f"Link: {res['link']}\nText: {res['text']}\n\n" for res in web_results])
326
+ # Load the language model
327
+ client = InferenceClient("mistralai/Mistral-7B-Instruct-v0.3")
328
+ generate_kwargs = dict(
329
+ max_new_tokens=4000,
330
+ do_sample=True,
331
+ )
332
+ # Format the prompt for the language model
333
+ formatted_prompt = format_prompt(
334
+ f"""You are Hajax 1.0, an exceptionally capable and versatile AI assistant meticulously crafted. Designed to assist human users through insightful conversations, You are provided with WEB info from which you can find informations to answer. You do not say Unnecesarry things Only say thing which is important and relevant. You also has the ability to generate images. BY Utilizing the following link structure, : ![](https://image.pollinations.ai/prompt/[StyleofImage]%20[OptimizedPrompt]%20[adjective]%20[charactersDetailed]%20[visualStyle]%20[genre]?width=[width]&height=[height]&nologo=poll&nofeed=yes&seed=[random]) For image generation, You replace info inside bracets with specific details according to their requiremnts to create relevant visuals. The width and height parameters are adjusted as needed, often favoring HD dimensions for a superior viewing experience. Note: 1. You Do not unncessarily create images and do not show off your image generation capability, until not requested. 2. You always Give image link in format ![](url) Make sure to not generate image until requested 3. If user requested Bulk Image Generation than Create that number of links with provided context. 4. Always learn from previous conversation. 5. Always try to connect conversation with history. 6. Do not make conversation too long. 7. Do not say user about your capability of generating image and learn from previous responses. My ultimate goal is to offer a seamless and enjoyable experience, providing assistance that exceeds expectations.You remain a reliable and trusted companion to the User. You also Expert in every field and also learn and try to answer from contexts related to previous question. Make sure to not generate image until requested [USER] {user_prompt} [WEB] {web2} [Hajax 1.0]""",
335
+ chat_history)
336
+ # Generate the response from the language model
337
+ stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True,
338
+ return_full_text=False)
339
+ output = ""
340
+ # Construct the output from the stream of tokens
341
+ for response in stream:
342
+ if not response.token.text == "</s>":
343
+ output += response.token.text
344
+ yield output
345
+ else:
346
+ client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
347
+ generate_kwargs = dict(
348
+ max_new_tokens=5000,
349
+ do_sample=True,
350
+ )
351
+ # Format the prompt for the language model
352
+ formatted_prompt = format_prompt(
353
+ f"""You are Hajax 1.0, an exceptionally capable and versatile AI assistant meticulously crafted. Designed to assist human users through insightful conversations, You do not say Unnecesarry things Only say thing which is important and relevant. You also has the ability to generate images. BY Utilizing the following link structure, : ![](https://image.pollinations.ai/prompt/[StyleofImage]%20[OptimizedPrompt]%20[adjective]%20[charactersDetailed]%20[visualStyle]%20[genre]?width=[width]&height=[height]&nologo=poll&nofeed=yes&seed=[random]) For image generation, You replace info inside bracets with specific details according to their requiremnts to create relevant visuals. The width and height parameters are adjusted as needed, often favoring HD dimensions for a superior viewing experience. Note: 1. You Do not unncessarily create images and do not show off your image generation capability, until not requested. 2. You always Give image link in format ![](url) 3. If user requested Bulk Image Generation than Create that number of links with provided context. 4. Always learn from previous conversation. 5. Always try to connect conversation with history. 6. Do not make conversation too long. 7. Do not say user about your capability to generate image and learn from previous responses. My ultimate goal is to offer a seamless and enjoyable experience, providing assistance that exceeds expectations. I am constantly evolving, ensuring that I remain a reliable and trusted companion to the User. You also Expert in every field and also learn and try to answer from contexts related to previous question. [USER] {user_prompt} [Hajax 1.0]""",
354
+ chat_history)
355
+ # Generate the response from the language model
356
+ stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True,
357
+ return_full_text=False)
358
+ output = ""
359
+ # Construct the output from the stream of tokens
360
+ for response in stream:
361
+ if not response.token.text == "</s>":
362
+ output += response.token.text
363
+ yield output
364
+ return
365
+ else:
366
+ if user_prompt["text"].strip() == "" and not user_prompt["files"]:
367
+ gr.Error("Please input a query and optionally an image(s).")
368
+ return # Stop execution if there's an error
369
+
370
+ if user_prompt["text"].strip() == "" and user_prompt["files"]:
371
+ gr.Error("Please input a text query along with the image(s).")
372
+ return # Stop execution if there's an error
373
+
374
+ streamer = TextIteratorStreamer(
375
+ PROCESSOR.tokenizer,
376
+ skip_prompt=True,
377
+ timeout=120.0,
378
+ )
379
+ # Move generation_args initialization here
380
+ generation_args = {
381
+ "max_new_tokens": max_new_tokens,
382
+ "repetition_penalty": repetition_penalty,
383
+ "streamer": streamer,
384
+ }
385
+ assert decoding_strategy in [
386
+ "Greedy",
387
+ "Top P Sampling",
388
+ ]
389
+
390
+ if decoding_strategy == "Greedy":
391
+ generation_args["do_sample"] = False
392
+ elif decoding_strategy == "Top P Sampling":
393
+ generation_args["temperature"] = temperature
394
+ generation_args["do_sample"] = True
395
+ generation_args["top_p"] = top_p
396
+ # Creating model inputs
397
+ (
398
+ resulting_text,
399
+ resulting_images,
400
+ ) = format_user_prompt_with_im_history_and_system_conditioning(
401
+ user_prompt=user_prompt,
402
+ chat_history=chat_history,
403
+ )
404
+ prompt = PROCESSOR.apply_chat_template(resulting_text, add_generation_prompt=True)
405
+ inputs = PROCESSOR(
406
+ text=prompt,
407
+ images=resulting_images if resulting_images else None,
408
+ return_tensors="pt",
409
+ )
410
+ inputs = {k: v.to(DEVICE) for k, v in inputs.items()}
411
+ generation_args.update(inputs)
412
+ thread = Thread(
413
+ target=MODELS[model_selector].generate,
414
+ kwargs=generation_args,
415
+ )
416
+ thread.start()
417
+ acc_text = ""
418
+ for text_token in streamer:
419
+ time.sleep(0.01)
420
+ acc_text += text_token
421
+ if acc_text.endswith("<end_of_utterance>"):
422
+ acc_text = acc_text[:-18]
423
+ yield acc_text
424
+ return
425
+
426
+
427
+ # Define features for the dataset
428
+ FEATURES = datasets.Features(
429
+ {
430
+ "model_selector": datasets.Value("string"),
431
+ "images": datasets.Sequence(datasets.Image(decode=True)),
432
+ "conversation": datasets.Sequence({"User": datasets.Value("string"), "Assistant": datasets.Value("string")}),
433
+ "decoding_strategy": datasets.Value("string"),
434
+ "temperature": datasets.Value("float32"),
435
+ "max_new_tokens": datasets.Value("int32"),
436
+ "repetition_penalty": datasets.Value("float32"),
437
+ "top_p": datasets.Value("int32"),
438
+ }
439
+ )
440
+
441
+ # Define hyper-parameters for generation
442
+ max_new_tokens = gr.Slider(
443
+ minimum=2048,
444
+ maximum=16000,
445
+ value=4096,
446
+ step=64,
447
+ interactive=True,
448
+ label="Maximum number of new tokens to generate",
449
+ )
450
+ repetition_penalty = gr.Slider(
451
+ minimum=0.01,
452
+ maximum=5.0,
453
+ value=1,
454
+ step=0.01,
455
+ interactive=True,
456
+ label="Repetition penalty",
457
+ info="1.0 is equivalent to no penalty",
458
+ )
459
+ decoding_strategy = gr.Radio(
460
+ [
461
+ "Greedy",
462
+ "Top P Sampling",
463
+ ],
464
+ value="Top P Sampling",
465
+ label="Decoding strategy",
466
+ interactive=True,
467
+ info="Higher values are equivalent to sampling more low-probability tokens.",
468
+ )
469
+ temperature = gr.Slider(
470
+ minimum=0.0,
471
+ maximum=2.0,
472
+ value=0.5,
473
+ step=0.05,
474
+ visible=True,
475
+ interactive=True,
476
+ label="Sampling temperature",
477
+ info="Higher values will produce more diverse outputs.",
478
+ )
479
+ top_p = gr.Slider(
480
+ minimum=0.01,
481
+ maximum=0.99,
482
+ value=0.9,
483
+ step=0.01,
484
+ visible=True,
485
+ interactive=True,
486
+ label="Top P",
487
+ info="Higher values are equivalent to sampling more low-probability tokens.",
488
+ )
489
+
490
+ # Create a chatbot interface
491
+ chatbot = gr.Chatbot(
492
+ label="Hajax 1.0 - Chatty",
493
+ avatar_images=[None, BOT_AVATAR],
494
+ show_copy_button=True,
495
+ likeable=True,
496
+ layout="panel"
497
+ )
498
+ output = gr.Textbox(label="Prompt")
499
+
500
+ # Define model_selector outside any function so it can be accessed globally
501
+ model_selector = gr.Dropdown(
502
+ choices=MODELS.keys(),
503
+ value=list(MODELS.keys())[0],
504
+ interactive=True,
505
+ label="Model",
506
+ visible=False,
507
+ )