-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchatbot.py
588 lines (522 loc) · 31.1 KB
/
chatbot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
import os
import time
import requests
import random
from threading import Thread
from typing import List, Dict, Union
# import subprocess
# subprocess.run(
# "pip install flash-attn --no-build-isolation",
# env={"FLASH_ATTENTION_SKIP_CUDA_BUILD": "TRUE"},
# shell=True,
# )
import torch
import gradio as gr
from bs4 import BeautifulSoup
from transformers import LlavaProcessor, LlavaForConditionalGeneration, TextIteratorStreamer
from transformers import AutoModelForCausalLM, AutoTokenizer, LlamaTokenizer
from diffusers import StableDiffusion3Pipeline
from huggingface_hub import InferenceClient
from transformers import pipeline
from PIL import Image
import spaces
from functools import lru_cache
import cv2
import re
import io
import json
from gradio_client import Client, file
from groq import Groq
# export HF_ENDPOINT=https://hf-mirror.com
# You can also use models that are commented below
# model_id = "llava-hf/llava-interleave-qwen-0.5b-hf"
model_id = "/dev/pretrained_models/llava-hf/llava-interleave-qwen-7b-dpo-hf"
# model_id = "llava-hf/llava-interleave-qwen-7b-dpo-hf"
processor = LlavaProcessor.from_pretrained(model_id)
model = LlavaForConditionalGeneration.from_pretrained(model_id,torch_dtype=torch.float16, attn_implementation="flash_attention_2", device_map="auto")
# model.to("cuda")
# Credit to merve for code of llava interleave qwen
GROQ_API_KEY = ""
# GROQ_API_KEY = os.environ.get("GROQ_API_KEY", None)
client_groq = Groq(api_key=GROQ_API_KEY)
def sample_frames(video_file) :
try:
video = cv2.VideoCapture(video_file)
total_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
num_frames = 12
interval = total_frames // num_frames
frames = []
for i in range(total_frames):
ret, frame = video.read()
pil_img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
if not ret:
continue
if i % interval == 0:
frames.append(pil_img)
video.release()
return frames
except:
frames=[]
return frames
# Path to example images
examples_path = os.path.dirname(__file__)
EXAMPLES = [
[
{
"text": "What is Friction? Explain in Detail.",
}
],
[
{
"text": "Write me a Python function to generate unique passwords.",
}
],
[
{
"text": "What's the latest price of Bitcoin?",
}
],
[
{
"text": "Search and give me list of spaces trending on HuggingFace.",
}
],
[
{
"text": "Create a Beautiful Picture of Effiel at Night.",
}
],
[
{
"text": "Create image of cute cat.",
}
],
[
{
"text": "What unusual happens in this video.",
"files": [f"{examples_path}/example_video/accident.gif"],
}
],
[
{
"text": "What's name of superhero in this clip",
"files": [f"{examples_path}/example_video/spiderman.gif"],
}
],
[
{
"text": "What's written on this paper",
"files": [f"{examples_path}/example_images/paper_with_text.png"],
}
],
[
{
"text": "Who are they? Tell me about both of them",
"files": [f"{examples_path}/example_images/elon_smoking.jpg",
f"{examples_path}/example_images/steve_jobs.jpg", ]
}
]
]
# Set bot avatar image
BOT_AVATAR = "OpenAI_logo.png"
# Perform a Google search and return the results
@lru_cache(maxsize=128)
def extract_text_from_webpage(html_content):
"""Extracts visible text from HTML content using BeautifulSoup."""
soup = BeautifulSoup(html_content, "html.parser")
for tag in soup(["script", "style", "header", "footer", "nav", "form", "svg"]):
tag.extract()
visible_text = soup.get_text(strip=True)
return visible_text
# Perform a Google search and return the results
def search(query):
term = query
start = 0
all_results = []
max_chars_per_page = 8000
with requests.Session() as session:
resp = session.get(
url="https://www.bing.com/search",
headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0"},
params={"q": term, "num": 4, "udm": 14},
timeout=5,
verify=None,
)
resp.raise_for_status()
soup = BeautifulSoup(resp.text, "html.parser")
result_block = soup.find_all("div", attrs={"class": "g"})
for result in result_block:
link = result.find("a", href=True)
link = link["href"]
try:
webpage = session.get(link, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0"}, timeout=5, verify=False)
webpage.raise_for_status()
visible_text = extract_text_from_webpage(webpage.text)
if len(visible_text) > max_chars_per_page:
visible_text = visible_text[:max_chars_per_page]
all_results.append({"link": link, "text": visible_text})
except requests.exceptions.RequestException:
all_results.append({"link": link, "text": None})
return all_results
def image_gen(prompt):
client = Client("KingNish/Image-Gen-Pro")
return client.predict("Image Generation",None, prompt, api_name="/image_gen_pro")
def video_gen(prompt):
client = Client("KingNish/Instant-Video")
return client.predict(prompt, api_name="/instant_video")
def llava(user_prompt, chat_history):
if user_prompt["files"]:
image = user_prompt["files"][0]
else:
for hist in chat_history:
if type(hist[0])==tuple:
image = hist[0][0]
txt = user_prompt["text"]
img = user_prompt["files"]
video_extensions = ("avi", "mp4", "mov", "mkv", "flv", "wmv", "mjpeg", "wav", "gif", "webm", "m4v", "3gp")
image_extensions = Image.registered_extensions()
image_extensions = tuple([ex for ex, f in image_extensions.items()])
# import pdb;pdb.set_trace()
image = image['path']
if image.endswith(video_extensions):
image = sample_frames(image)
gr.Info("Analyzing Video")
image_tokens = "<image>" * int(len(image))
prompt = f"<|im_start|>user {image_tokens}\n{user_prompt}<|im_end|><|im_start|>assistant"
elif image.endswith(image_extensions):
image = Image.open(image).convert("RGB")
gr.Info("Analyzing image")
prompt = f"<|im_start|>user <image>\n{user_prompt}<|im_end|><|im_start|>assistant"
system_llava = "<|im_start|>system\nYou are OpenGPT 4o, an exceptionally capable and versatile AI assistant made by KingNish. Your task is to fulfill users query in best possible way. You are provided with image, videos and 3d structures as input with question your task is to give best possible detailed results to user according to their query. Reply the question asked by user properly and best possible way.<|im_end|>"
final_prompt = f"{system_llava}\n{prompt}"
inputs = processor(final_prompt, image, return_tensors="pt").to("cuda", torch.float16)
return inputs
# Initialize inference clients for different models
class Client_Mistral:
#https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.3
def __init__(self, path):
self.tokenizer = AutoTokenizer.from_pretrained(path)
self.model = AutoModelForCausalLM.from_pretrained(path, device_map="auto", attn_implementation="flash_attention_2",torch_dtype=torch.float16)
self.chatbot = pipeline("text-generation", tokenizer=self.tokenizer, model=self.model)
def chat_completion(self,conversation, max_new_tokens=200):
response_data = self.chatbot(conversation, max_new_tokens=max_new_tokens, return_full_text=False)
# import pdb;pdb.set_trace()
return response_data[0]
import torch.nn as nn
import torch.optim as optim
import itertools
def update_policy(model,tokenizer,state, pre_action):
optimizer = optim.Adam(itertools.chain(model.parameters()), lr=0.0003)
# import pdb;pdb.set_trace()
now_state = tokenizer(state,add_special_tokens=False).input_ids
next_label = tokenizer(pre_action,add_special_tokens=False).input_ids
input_ids = torch.tensor(now_state+next_label).to(model.device)
logits = model(input_ids.unsqueeze(0)).logits.squeeze(0)
pos_1, pos_2 = torch.arange(len(next_label))+(len(now_state)-1), torch.tensor(next_label)
# import pdb;pdb.set_trace()
ppl = -(logits.softmax(dim=-1)[pos_1,pos_2].log().sum())
optimizer.zero_grad()
ppl.backward()
optimizer.step()
class Client_Mixtral:
# https://huggingface.co/NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO
def __init__(self,path):
self.tokenizer = LlamaTokenizer.from_pretrained(path)
self.model = AutoModelForCausalLM.from_pretrained(path,attn_implementation="flash_attention_2", device_map="auto",torch_dtype=torch.float16)
def text_generation(self, messages, max_new_tokens=4000, do_sample=True, stream=True, details=True, return_full_text=False, update_flag=False, pre_action=None):
assert (update_flag ^ (pre_action is None))
if update_flag:
self.model.train()
update_policy(self.model,self.tokenizer,messages,pre_action)
self.model.eval()
streamer = TextIteratorStreamer(self.tokenizer, skip_prompt=True, **{"skip_special_tokens": True})
generation_kwargs = dict(self.tokenizer(messages,return_tensors="pt"), streamer=streamer, max_new_tokens=max_new_tokens,do_sample=do_sample)
thread = Thread(target=self.model.generate, kwargs=generation_kwargs)
thread.start()
return streamer
# client_mistral = InferenceClient("/dev/pretrained_models/mistralai/Mistral-7B-Instruct-v0.3")
client_mistral = Client_Mistral("/dev/pretrained_models/mistralai/Mistral-7B-Instruct-v0.3")
# client_mixtral = InferenceClient("/dev/pretrained_models/NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO")
client_mixtral = Client_Mixtral("/dev/pretrained_models/NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO")
# client_llama = InferenceClient("/dev/pretrained_models/meta-llama/Meta-Llama-3-8B-Instruct")
# client_llama = InferenceClient("/dev/pretrained_models/gradientai/Llama-3-8B-Instruct-Gradient-1048k")
# client_mistral_nemo = InferenceClient("/dev/pretrained_models/mistralai/Mistral-Nemo-Instruct-2407")
# huggingface-cli download --token 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 --resume-download gradientai/Llama-3-8B-Instruct-Gradient-1048k --local-dir gradientai/Llama-3-8B-Instruct-Gradient-1048k
class Client_SD3:
def __init__(self,path):
self.pipe = StableDiffusion3Pipeline.from_pretrained(path, torch_dtype=torch.float16).to("cuda")
# pipe = pipe.to("cuda")
def text_to_image(self, query, negative_prompt):
image = self.pipe(
query,
negative_prompt=negative_prompt,
num_inference_steps=28,
guidance_scale=7.0,
).images[0]
return image
@spaces.GPU(duration=60, queue=False)
# def model_inference( user_prompt, chat_history, update_flag=False, pre_action=None):
def model_inference( user_prompt, chat_history):
# import pdb;pdb.set_trace()
if 'other_params' in user_prompt:
print('heheh')
user_prompt['update_flag'] = True
user_prompt['pre_action'] = user_prompt['other_params']
else:
user_prompt['update_flag'] = False
user_prompt['pre_action'] = None
if user_prompt["files"]:
inputs = llava(user_prompt, chat_history)
streamer = TextIteratorStreamer(processor, skip_prompt=True, **{"skip_special_tokens": True})
generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=2048)
thread = Thread(target=model.generate, kwargs=generation_kwargs)
thread.start()
buffer = ""
for new_text in streamer:
buffer += new_text
yield buffer
else:
# if user_prompt['text'] == '-1':
# # import pdb;pdb.set_trace()
# temp = chat_history[-1][1]
# user_prompt = {'text': chat_history[-1][0], 'files': []}
# chat_history = chat_history[:-1]
# # return model_inference(user_prompt,chat_history, update_flag=True,pre_action=temp)
# else:
func_caller = []
message = user_prompt
functions_metadata = [
{"type": "function", "function": {"name": "web_search", "description": "Search query on google and find latest information, info about any person, object, place thing, everything that available on google.", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "web search query"}}, "required": ["query"]}}},
{"type": "function", "function": {"name": "general_query", "description": "Reply general query of USER, with LLM like you. But it does not answer tough questions and latest info's.", "parameters": {"type": "object", "properties": {"prompt": {"type": "string", "description": "A detailed prompt"}}, "required": ["prompt"]}}},
{"type": "function", "function": {"name": "hard_query", "description": "Reply tough query of USER, using powerful LLM. But it does not answer latest info's.", "parameters": {"type": "object", "properties": {"prompt": {"type": "string", "description": "A detailed prompt"}}, "required": ["prompt"]}}},
{"type": "function", "function": {"name": "image_generation", "description": "Generate image for user", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "image generation prompt"}}, "required": ["query"]}}},
{"type": "function", "function": {"name": "video_generation", "description": "Generate video for user", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "video generation prompt"}}, "required": ["query"]}}},
{"type": "function", "function": {"name": "image_qna", "description": "Answer question asked by user related to image", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "Question by user"}}, "required": ["query"]}}},
]
for msg in chat_history:
func_caller.append({"role": "user", "content": f"{str(msg[0])}"})
func_caller.append({"role": "assistant", "content": f"{str(msg[1])}"})
message_text = message["text"]
func_caller.append({"role": "user", "content": f'[SYSTEM]You are a helpful assistant. You have access to the following functions: \n {str(functions_metadata)}\n\nTo use these functions respond with:\n<functioncall> {{ "name": "function_name", "arguments": {{ "arg_1": "value_1", "arg_1": "value_1", ... }} }} </functioncall> , Reply in JSOn format, you can call only one function at a time, So, choose functions wisely. [USER] {message_text}'})
response = client_mistral.chat_completion(func_caller, max_new_tokens=2000)
response = str(response)
print(f"\n{response}")
# try:
# response = response[response.find("{"):response.index("</")]
# except:
# response = response[response.find("{"):(response.rfind("}")+1)]
# try:
# response = response[response.find("```json*{"):response.index("}```"+1)]
# except:
# response = response[response.find("{"):(response.rfind("}")+1)]
# try:
# response = response[response.find("<functioncall>*{"): "</functioncall>" ]
# except:
# response = response[response.find("{"):(response.rfind("}")+1)]
# 使用正则表达式提取所有符合条件的JSON对象
# pattern = r'\{*"name":\s*"(.*?)".*?"arguments":\s*(\{.*?\})\s*}'
# pattern = r'\{*"name":\s*"*"\s*,\s*"arguments":\s*\{*\}\}'
# matches = re.findall(pattern, response, re.DOTALL)
# # 存储所有提取的JSON对象
# extracted_json_objects = []
# # 尝试将每个匹配的字符串转换为字典
# for name, arguments in matches:
# try:
# # 构建完整的JSON字符串
# cleaned_json_str = f'{{"name": "{name}", "arguments": {arguments}}}'
# extracted_json_objects.append(cleaned_json_str)
# except json.JSONDecodeError as e:
# print("JSON解析错误:", e)
# print(extracted_json_objects)
# response = extracted_json_objects[0]
name_pos, arguments_pos = response.find("name"), response.find("arguments")
st_pos = name_pos
while response[st_pos] != '{':
st_pos -= 1
# import pdb;pdb.set_trace()
ed_pos = response.find("}",arguments_pos)
ed_pos = response.find("}",ed_pos+1)
response = response[st_pos:ed_pos+1]
# import pdb;pdb.set_trace()
response = response.replace("\\n", "")
response = response.replace("\\'", "'")
response = response.replace('\\"', '"')
# response = response.replace('"', "'")
response = response.replace('\\', '')
print(f"\n{response}")
# import pdb;pdb.set_trace()
try:
json_data = json.loads(str(response))
if json_data["name"] == "web_search":
query = json_data["arguments"]["query"]
gr.Info("Searching Web")
yield "Searching Web"
web_results = search(query)
gr.Info("Extracting relevant Info")
yield "Extracting Relevant Info"
web2 = ' '.join([f"Link: {res['link']}\nText: {res['text']}\n\n" for res in web_results])
try:
message_groq = []
message_groq.append({"role":"system", "content": "You are OpenGPT 4o a helpful and very powerful web assistant made by KingNish. You are provided with WEB results from which you can find informations to answer users query in Structured, Detailed and Better way, in Human Style. You are also Expert in every field and also learn and try to answer from contexts related to previous question. Try your best to give best response possible to user. You reply in detail like human, use short forms, structured format, friendly tone and emotions."})
for msg in chat_history:
message_groq.append({"role": "user", "content": f"{str(msg[0])}"})
message_groq.append({"role": "assistant", "content": f"{str(msg[1])}"})
message_groq.append({"role": "user", "content": f"[USER] {str(message_text)} , [WEB RESULTS] {str(web2)}"})
# its meta-llama/Meta-Llama-3.1-8B-Instruct
stream = client_groq.chat.completions.create(model="llama-3.1-8b-instant", messages=message_groq, max_tokens=4096, stream=True)
output = ""
for chunk in stream:
content = chunk.choices[0].delta.content
if content:
output += chunk.choices[0].delta.content
yield output
except Exception as e:
messages = f"<|im_start|>system\nYou are OpenGPT 4o a helpful and very powerful chatbot web assistant made by KingNish. You are provided with WEB results from which you can find informations to answer users query in Structured, Better and in Human Way. You do not say Unnecesarry things. You are also Expert in every field and also learn and try to answer from contexts related to previous question. Try your best to give best response possible to user. You also try to show emotions using Emojis and reply in details like human, use short forms, friendly tone and emotions.<|im_end|>"
for msg in chat_history:
messages += f"\n<|im_start|>user\n{str(msg[0])}<|im_end|>"
messages += f"\n<|im_start|>assistant\n{str(msg[1])}<|im_end|>"
messages+=f"\n<|im_start|>user\n{message_text}<|im_end|>\n<|im_start|>web_result\n{web2}<|im_end|>\n<|im_start|>assistant\n"
stream = client_mixtral.text_generation(messages, max_new_tokens=4000, do_sample=True, stream=True, details=True, return_full_text=False,
update_flag=user_prompt['update_flag'],pre_action=user_prompt['pre_action'])
output = ""
for response in stream:
if not response.token.text == "<|im_end|>":
output += response.token.text
yield output
elif json_data["name"] == "image_generation":
query = json_data["arguments"]["query"]
gr.Info("Generating Image, Please wait 10 sec...")
yield "Generating Image, Please wait 10 sec..."
# try:
# image = image_gen(f"{str(query)}")
# yield gr.Image(image[1])
# except:
# client_sd3 = InferenceClient("stabilityai/stable-diffusion-3-medium-diffusers")
client_sd3 = Client_SD3("/dev/pretrained_models/stabilityai/stable-diffusion-3-medium-diffusers")
seed = random.randint(0,999999)
image = client_sd3.text_to_image(query, negative_prompt=f"{seed}")
yield gr.Image(image)
elif json_data["name"] == "video_generation":
query = json_data["arguments"]["query"]
gr.Info("Generating Video, Please wait 15 sec...")
yield "Generating Video, Please wait 15 sec..."
video = video_gen(f"{str(query)}")
yield gr.Video(video)
elif json_data["name"] == "image_qna":
inputs = llava(user_prompt, chat_history)
streamer = TextIteratorStreamer(processor, skip_prompt=True, **{"skip_special_tokens": True})
generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=1024)
thread = Thread(target=model.generate, kwargs=generation_kwargs)
thread.start()
buffer = ""
for new_text in streamer:
buffer += new_text
yield buffer
else:
try:
message_groq = []
message_groq.append({"role":"system", "content": "You are OpenGPT 4o a helpful and powerful assistant made by KingNish. You answers users query in detail and structured format and style like human. You are also Expert in every field and also learn and try to answer from contexts related to previous question. You also try to show emotions using Emojis and reply like human, use short forms, structured manner, detailed explaination, friendly tone and emotions."})
for msg in chat_history:
message_groq.append({"role": "user", "content": f"{str(msg[0])}"})
message_groq.append({"role": "assistant", "content": f"{str(msg[1])}"})
message_groq.append({"role": "user", "content": f"{str(message_text)}"})
# its meta-llama/Meta-Llama-3.1-70B-Instruct
stream = client_groq.chat.completions.create(model="llama-3.1-70b-versatile", messages=message_groq, max_tokens=4096, stream=True)
output = ""
for chunk in stream:
content = chunk.choices[0].delta.content
if content:
output += chunk.choices[0].delta.content
yield output
except Exception as e:
print(e)
try:
message_groq = []
message_groq.append({"role":"system", "content": "You are OpenGPT 4o a helpful and powerful assistant made by KingNish. You answers users query in detail and structured format and style like human. You are also Expert in every field and also learn and try to answer from contexts related to previous question. You also try to show emotions using Emojis and reply like human, use short forms, structured manner, detailed explaination, friendly tone and emotions."})
for msg in chat_history:
message_groq.append({"role": "user", "content": f"{str(msg[0])}"})
message_groq.append({"role": "assistant", "content": f"{str(msg[1])}"})
message_groq.append({"role": "user", "content": f"{str(message_text)}"})
# its meta-llama/Meta-Llama-3-70B-Instruct
stream = client_groq.chat.completions.create(model="llama3-70b-8192", messages=message_groq, max_tokens=4096, stream=True)
output = ""
for chunk in stream:
content = chunk.choices[0].delta.content
if content:
output += chunk.choices[0].delta.content
yield output
except Exception as e:
print(e)
message_groq = []
message_groq.append({"role":"system", "content": "You are OpenGPT 4o a helpful and powerful assistant made by KingNish. You answers users query in detail and structured format and style like human. You are also Expert in every field and also learn and try to answer from contexts related to previous question. You also try to show emotions using Emojis and reply like human, use short forms, structured manner, detailed explaination, friendly tone and emotions."})
for msg in chat_history:
message_groq.append({"role": "user", "content": f"{str(msg[0])}"})
message_groq.append({"role": "assistant", "content": f"{str(msg[1])}"})
message_groq.append({"role": "user", "content": f"{str(message_text)}"})
stream = client_groq.chat.completions.create(model="llama3-groq-70b-8192-tool-use-preview", messages=message_groq, max_tokens=4096, stream=True)
output = ""
for chunk in stream:
content = chunk.choices[0].delta.content
if content:
output += chunk.choices[0].delta.content
yield output
except Exception as e:
print(e)
try:
message_groq = []
message_groq.append({"role":"system", "content": "You are OpenGPT 4o a helpful and powerful assistant made by KingNish. You answers users query in detail and structured format and style like human. You are also Expert in every field and also learn and try to answer from contexts related to previous question. You also try to show emotions using Emojis and reply like human, use short forms, structured manner, detailed explaination, friendly tone and emotions."})
for msg in chat_history:
message_groq.append({"role": "user", "content": f"{str(msg[0])}"})
message_groq.append({"role": "assistant", "content": f"{str(msg[1])}"})
message_groq.append({"role": "user", "content": f"{str(message_text)}"})
# its meta-llama/Meta-Llama-3-70B-Instruct
stream = client_groq.chat.completions.create(model="llama3-70b-8192", messages=message_groq, max_tokens=4096, stream=True)
output = ""
for chunk in stream:
content = chunk.choices[0].delta.content
if content:
output += chunk.choices[0].delta.content
yield output
except Exception as e:
print(e)
try:
message_groq = []
message_groq.append({"role":"system", "content": "You are OpenGPT 4o a helpful and powerful assistant made by KingNish. You answers users query in detail and structured format and style like human. You are also Expert in every field and also learn and try to answer from contexts related to previous question. You also try to show emotions using Emojis and reply like human, use short forms, structured manner, detailed explaination, friendly tone and emotions."})
for msg in chat_history:
message_groq.append({"role": "user", "content": f"{str(msg[0])}"})
message_groq.append({"role": "assistant", "content": f"{str(msg[1])}"})
message_groq.append({"role": "user", "content": f"{str(message_text)}"})
# its meta-llama/Meta-Llama-3-8B-Instruct
stream = client_groq.chat.completions.create(model="llama3-8b-8192", messages=message_groq, max_tokens=4096, stream=True)
output = ""
for chunk in stream:
content = chunk.choices[0].delta.content
if content:
output += chunk.choices[0].delta.content
yield output
except Exception as e:
print(e)
messages = f"<|im_start|>system\nYou are OpenGPT 4o a helpful and powerful assistant made by KingNish. You answers users query in detail and structured format and style like human. You are also Expert in every field and also learn and try to answer from contexts related to previous question. You also try to show emotions using Emojis and reply like human, use short forms, structured manner, detailed explaination, friendly tone and emotions.<|im_end|>"
for msg in chat_history:
messages += f"\n<|im_start|>user\n{str(msg[0])}<|im_end|>"
messages += f"\n<|im_start|>assistant\n{str(msg[1])}<|im_end|>"
messages+=f"\n<|im_start|>user\n{message_text}<|im_end|>\n<|im_start|>assistant\n"
stream = client_mixtral.text_generation(messages, max_new_tokens=4000, do_sample=True, stream=True, details=True, return_full_text=False,
update_flag=user_prompt['update_flag'],pre_action=user_prompt['pre_action'])
output = ""
for response in stream:
# print(response)
# import pdb;pdb.set_trace()
if not response == "<|im_end|>":
output += response
yield output
# Create a chatbot interface
chatbot = gr.Chatbot(
label="OpenGPT-4o",
avatar_images=[None, BOT_AVATAR],
show_copy_button=True,
likeable=True,
layout="panel",
height=400,
)
output = gr.Textbox(label="Prompt")