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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from huggingface_hub import InferenceClient
|
| 2 |
+
#from html2image import Html2Image
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import markdown
|
| 5 |
+
import requests
|
| 6 |
+
import random
|
| 7 |
+
#import prompts
|
| 8 |
+
#import im_prompts
|
| 9 |
+
import uuid
|
| 10 |
+
import json
|
| 11 |
+
#import PIL
|
| 12 |
+
#import bs4
|
| 13 |
+
import re
|
| 14 |
+
import os
|
| 15 |
+
loc_folder="chat_history"
|
| 16 |
+
loc_file="chat_json"
|
| 17 |
+
|
| 18 |
+
clients = [
|
| 19 |
+
{'type':'image','name':'black-forest-labs/FLUX.1-dev','rank':'op','max_tokens':16384,'schema':{'bos':'<|im_start|>','eos':'<|im_end|>'}},
|
| 20 |
+
{'type':'text','name':'deepseek-ai/DeepSeek-V2.5-1210','rank':'op','max_tokens':16384,'schema':{'bos':'<|im_start|>','eos':'<|im_end|>'}},
|
| 21 |
+
{'type':'text','name':'Qwen/Qwen2.5-Coder-32B-Instruct','rank':'op','max_tokens':32768,'schema':{'bos':'<|im_start|>','eos':'<|im_end|>'}},
|
| 22 |
+
{'type':'text','name':'meta-llama/Meta-Llama-3-8B','rank':'op','max_tokens':32768,'schema':{'bos':'<|im_start|>','eos':'<|im_end|>'}},
|
| 23 |
+
{'type':'text','name':'Snowflake/snowflake-arctic-embed-l-v2.0','rank':'op','max_tokens':4096,'schema':{'bos':'<|im_start|>','eos':'<|im_end|>'}},
|
| 24 |
+
{'type':'text','name':'Snowflake/snowflake-arctic-embed-m-v2.0','rank':'op','max_tokens':4096,'schema':{'bos':'<|im_start|>','eos':'<|im_end|>'}},
|
| 25 |
+
{'type':'text','name':'HuggingFaceTB/SmolLM2-1.7B-Instruct','rank':'op','max_tokens':4096,'schema':{'bos':'<|im_start|>','eos':'<|im_end|>'}},
|
| 26 |
+
{'type':'text','name':'Qwen/QwQ-32B-Preview','rank':'op','max_tokens':16384,'schema':{'bos':'<|im_start|>','eos':'<|im_end|>'}},
|
| 27 |
+
{'type':'text','name':'meta-llama/Llama-3.3-70B-Instruct','rank':'pro','max_tokens':16384,'schema':{'bos':'<|im_start|>','eos':'<|im_end|>'}},
|
| 28 |
+
{'type':'text','name':'mistralai/Mixtral-8x7B-Instruct-v0.1','rank':'op','max_tokens':40000,'schema':{'bos':'<s>','eos':'</s>'}},
|
| 29 |
+
]
|
| 30 |
+
def generate(prompt,history,mod=2,tok=None,seed=1,role="ASSISTANT",data=None):
|
| 31 |
+
#print("#####",history,"######")
|
| 32 |
+
gen_images=False
|
| 33 |
+
client=InferenceClient(clients[int(mod)]['name'])
|
| 34 |
+
client_tok=clients[int(mod)]['max_tokens']
|
| 35 |
+
good_seed=[947385642222,7482965345792,8584806344673]
|
| 36 |
+
if not history:
|
| 37 |
+
history=[{'role':'user','content':prompt}]
|
| 38 |
+
if not os.path.isdir(loc_folder):os.mkdir(loc_folder)
|
| 39 |
+
|
| 40 |
+
if os.path.isfile(f'{loc_folder}/{loc_file}.json'):
|
| 41 |
+
with open(f'{loc_folder}/{loc_file}.json','r') as word_dict:
|
| 42 |
+
lod=json.loads(word_dict.read())
|
| 43 |
+
word_dict.close()
|
| 44 |
+
else:
|
| 45 |
+
lod=[]
|
| 46 |
+
if role == "ASSISTANT":
|
| 47 |
+
system_prompt = prompts.ASSISTANT
|
| 48 |
+
formatted_prompt = format_prompt(f'USER:{prompt}', history, system_prompt)
|
| 49 |
+
elif role == "CREATE_FILE":
|
| 50 |
+
system_prompt = prompts.CREATE_FILE.replace("**FILENAME**",str(data[4]))
|
| 51 |
+
formatted_prompt = format_prompt(prompt, history, system_prompt)
|
| 52 |
+
elif role == "MANAGER":
|
| 53 |
+
system_prompt = prompts.MANAGER.replace("**TIMELINE**",data[4]).replace("**HISTORY**",str(history))
|
| 54 |
+
formatted_prompt = format_prompt(prompt, history, system_prompt)
|
| 55 |
+
elif role == "SEARCH":
|
| 56 |
+
system_prompt = prompts.SEARCH.replace("**DATA**",data)
|
| 57 |
+
formatted_prompt = format_prompt(f'USER:{prompt}', history, system_prompt)
|
| 58 |
+
else: system_prompt = "";formatted_prompt = format_prompt(f'USER:{prompt}', history, system_prompt)
|
| 59 |
+
|
| 60 |
+
if tok==None:tok=client_tok-len(formatted_prompt)+10
|
| 61 |
+
print("tok",tok)
|
| 62 |
+
generate_kwargs = dict(
|
| 63 |
+
temperature=0.9,
|
| 64 |
+
max_new_tokens=tok, #total tokens - input tokens
|
| 65 |
+
top_p=0.99,
|
| 66 |
+
repetition_penalty=1.0,
|
| 67 |
+
do_sample=True,
|
| 68 |
+
seed=seed,
|
| 69 |
+
)
|
| 70 |
+
output = ""
|
| 71 |
+
if role=="MANAGER":
|
| 72 |
+
print("Running Manager")
|
| 73 |
+
stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=True)
|
| 74 |
+
for response in stream:
|
| 75 |
+
output += response.token.text
|
| 76 |
+
yield output
|
| 77 |
+
yield history
|
| 78 |
+
yield prompt
|
| 79 |
+
elif role=="ASSISTANT" or role=="WEBDEVELOPER" or role=="PATHMAKER":
|
| 80 |
+
print("Runnning ", role)
|
| 81 |
+
stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=True)
|
| 82 |
+
#prompt=f"We just completed role:{role}, now choose the next tool to complete the task:{prompt}, or COMPLETE"
|
| 83 |
+
for response in stream:
|
| 84 |
+
output += response.token.text
|
| 85 |
+
#print(output)
|
| 86 |
+
yield output
|
| 87 |
+
yield history
|
| 88 |
+
yield prompt
|
| 89 |
+
elif role=="CREATE_FILE":
|
| 90 |
+
print("Running Create File")
|
| 91 |
+
stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=True)
|
| 92 |
+
for response in stream:
|
| 93 |
+
output += response.token.text
|
| 94 |
+
yield output
|
| 95 |
+
yield history
|
| 96 |
+
yield prompt
|
| 97 |
+
#with open(f'{loc_folder}/{loc_file}.json','w') as jobj:
|
| 98 |
+
# lod.append({'prompt':prompt,'response':output,'image':im_box,'model':clients[1]['name'],'seed':seed}),
|
| 99 |
+
# jobj.write(json.dumps(lod,indent=4))
|
| 100 |
+
#jobj.close()
|
| 101 |
+
#chat_im_out=chat_img(output)
|
| 102 |
+
|
| 103 |
+
def gen_im(prompt,seed):
|
| 104 |
+
print('generating image')
|
| 105 |
+
image_out = im_client.text_to_image(prompt=prompt['text'],height=128,width=128,num_inference_steps=10,seed=seed)
|
| 106 |
+
#print(type(image_out))
|
| 107 |
+
output=f'images/{uuid.uuid4()}.png'
|
| 108 |
+
image_out.save(output)
|
| 109 |
+
print('Done: ',output)
|
| 110 |
+
return [{'role':'assistant','content': {'path':output}}]
|
| 111 |
+
|
| 112 |
+
def build_space(repo_name,file_name,file_content,access_token=""):
|
| 113 |
+
try:
|
| 114 |
+
#access_token=""
|
| 115 |
+
client = hf_api(access_token)
|
| 116 |
+
# Create a new Space
|
| 117 |
+
response = client.create_repo(repo_name)
|
| 118 |
+
space_info = response.json()
|
| 119 |
+
print(space_info)
|
| 120 |
+
space_id = space_info["name"]
|
| 121 |
+
print(f"Created Space with ID: {space_id}")
|
| 122 |
+
local_file_path=str(uuid.uuid4()
|
| 123 |
+
with open(local_file_path, 'w') as f:
|
| 124 |
+
f.write(str(file_content))
|
| 125 |
+
f.close()
|
| 126 |
+
# Upload a local file to the Space
|
| 127 |
+
commit_message = "Adding file test: "+str(uuid.uuid4())
|
| 128 |
+
client.upload_file(local_file_path, repo_id=space_id, path=file_name, commit_message=commit_message)
|
| 129 |
+
print("File uploaded successfully.")
|
| 130 |
+
# Commit changes
|
| 131 |
+
commit_message += "\nInitial commit to the repository."+ local_file_path
|
| 132 |
+
client.commit_repo(space_id, message=commit_message)
|
| 133 |
+
return [{'role':'assistant','content': commit_message+'\nCommit Success' }]
|
| 134 |
+
except Exception as e:
|
| 135 |
+
return [{'role':'assistant','content': 'There was an Error: '+e}]
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def agent(prompt,history,mod,data="None"):
|
| 139 |
+
in_data=[None,None,None,None,None,]
|
| 140 |
+
in_data[0]=data
|
| 141 |
+
prompt=prompt['text']
|
| 142 |
+
fn=""
|
| 143 |
+
com=""
|
| 144 |
+
go=True
|
| 145 |
+
while go == True:
|
| 146 |
+
seed = random.randint(1,9999999999999)
|
| 147 |
+
c=0
|
| 148 |
+
history = [history[-4:]]
|
| 149 |
+
if len(str(history)) > MAX_DATA*4:
|
| 150 |
+
history = [history[-2:]]
|
| 151 |
+
role="MANAGER"
|
| 152 |
+
outp=generate(prompt,history,mod,128,seed,role,in_data)
|
| 153 |
+
outpp=list(outp)[0]
|
| 154 |
+
outp0 = re.sub('[^a-zA-Z0-9\s.,?!%()]', '', outpp)
|
| 155 |
+
history=history+[{'role':'assistant','content':str(outp0)}]
|
| 156 |
+
yield history
|
| 157 |
+
for line in outp0.split("\n"):
|
| 158 |
+
if "action:" in line:
|
| 159 |
+
try:
|
| 160 |
+
com_line = line.split('action:')[1]
|
| 161 |
+
fn = com_line.split('action_input=')[0]
|
| 162 |
+
com = com_line.split('action_input=')[1].split('<|im_end|>')[0]
|
| 163 |
+
#com = com_line.split('action_input=')[1].replace('<|im_end|>','').replace("}","").replace("]","").replace("'","")
|
| 164 |
+
print(com)
|
| 165 |
+
except Exception as e:
|
| 166 |
+
pass
|
| 167 |
+
fn="NONE"
|
| 168 |
+
if 'CREATE_FILE' in fn:
|
| 169 |
+
print('CREATE_FILE called')
|
| 170 |
+
out_w =generate(com,history,mod=mod,tok=None,seed=seed,role="CREATE_FILE")
|
| 171 |
+
build_space(out_w[0],out_w[1])
|
| 172 |
+
elif 'IMAGE' in fn:
|
| 173 |
+
print('IMAGE called')
|
| 174 |
+
out_im=gen_im(prompt,seed)
|
| 175 |
+
yield [{'role':'assistant','content': out_im}]
|
| 176 |
+
elif 'SEARCH' in fn:
|
| 177 |
+
print('SEARCH called')
|
| 178 |
+
elif 'COMPLETE' in fn:
|
| 179 |
+
print('COMPLETE')
|
| 180 |
+
go=False
|
| 181 |
+
break
|
| 182 |
+
elif 'NONE' in fn:
|
| 183 |
+
print('ERROR ACTION NOT FOUND')
|
| 184 |
+
history+=[{'role':'system','content':f'observation:The last thing we attempted resulted in an error, check formatting on the tool call'}]
|
| 185 |
+
|
| 186 |
+
else:pass;seed = random.randint(1,9999999999999)
|
| 187 |
+
with gr.Blocks() as ux:
|
| 188 |
+
with gr.Row():
|
| 189 |
+
with gr.Column():
|
| 190 |
+
gr.HTML("""<center><div style='font-size:xx-large;font-weight:900;'>Chatbo</div>""")
|
| 191 |
+
chatbot=gr.Chatbot(type='messages',show_label=False, show_share_button=False, show_copy_button=True, layout="panel")
|
| 192 |
+
prompt=gr.MultimodalTextbox(label="Prompt",file_count="multiple", file_types=["image"])
|
| 193 |
+
|
| 194 |
+
mod_c=gr.Dropdown(choices=[n['name'] for n in clients],value='Qwen/Qwen2.5-Coder-32B-Instruct',type='index')
|
| 195 |
+
|
| 196 |
+
with gr.Row():
|
| 197 |
+
submit_b = gr.Button()
|
| 198 |
+
stop_b = gr.Button("Stop")
|
| 199 |
+
clear = gr.ClearButton([chatbot,prompt])
|
| 200 |
+
with gr.Row(visible=False):
|
| 201 |
+
stt=gr.Textbox()
|
| 202 |
+
with gr.Column():
|
| 203 |
+
file_name=gr.Textbox(label="File Name")
|
| 204 |
+
file_btn=gr.Button("Load Files")
|
| 205 |
+
file_json=gr.JSON()
|
| 206 |
+
sub_b = submit_b.click(agent, [prompt,chatbot,mod_c,file_name,file_json],chatbot)
|
| 207 |
+
sub_p = prompt.submit(agent, [prompt,chatbot,mod_c,file_name,file_json],chatbot)
|
| 208 |
+
stop_b.click(None,None,None, cancels=[sub_b,sub_p])
|
| 209 |
+
ux.queue(default_concurrency_limit=20).launch(max_threads=40)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
|