Spaces:
Running
Running
File size: 18,904 Bytes
4d1746c |
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 |
import gradio as gr
from backend import get_handler
import time
import uuid
import json
import os
import queue
from db import collection
from info_table import api_info, api_samples
custom_css = """
/* Highlight the entire message box for the bot */
.bot-highlight {
background-color: yellow !important;
padding: 0px;
border-radius: 8px;
}
"""
# Initialize test_entry and handler
def initialize_empty_test_entry():
return {
"initial_config": {},
"involved_classes": [],
"id": str(uuid.uuid4()), # Generate unique ID
"question": [],
"function": []
}
test_entry_1 = initialize_empty_test_entry()
test_entry_2 = initialize_empty_test_entry()
inference_data_1 = {"message": []} # Do not change this
inference_data_2 = {"message": []} # Do not change this
# Define available models and categories
models = ["gpt-4o-mini-2024-07-18-FC", "gpt-4o-2024-08-06-FC", "gpt-4o-mini-2024-07-18-FC", "gpt-4-turbo-2024-04-09-FC", "gpt-3.5-turbo-0125-FC"]
categories = ["GorillaFileSystem", "MathAPI", "MessageAPI", "TwitterAPI", "TicketAPI", "TradingBot", "TravelAPI", "VehicleControlAPI"]
initial_chat_history = [
{"role": "user", "content": "Hi, can you help me with some tasks?"},
{"role": "assistant", "content": "Hello there! How can I assist you today?"},
]
shared_queue = queue.Queue()
def get_initial_state():
return initial_chat_history
DEFAULT_MODEL_1 = models[0]
DEFAULT_MODEL_2 = models[1]
DEFAULT_TEMPERATURE_1 = 0.7
DEFAULT_TEMPERATURE_2 = 0.4
current_model_1 = models[0]
current_model_2 = models[0]
current_category = categories[0]
current_temperature = DEFAULT_TEMPERATURE_1
current_temperature = DEFAULT_TEMPERATURE_2
# Initialize handler
handler_1 = get_handler(DEFAULT_MODEL_1, DEFAULT_TEMPERATURE_1)
handler_2 = get_handler(DEFAULT_MODEL_2, DEFAULT_TEMPERATURE_2)
def print_like_dislike(x: gr.LikeData):
print(x.index, x.value, x.liked)
def add_message(history1, history2, message, target):
if target in ["Model 1", "Both"]:
for x in message["files"]:
history1.append({"role": "user", "content": {"path": x}})
if message["text"] is not None:
history1.append({"role": "user", "content": message["text"]})
test_entry_1["question"] = [{"role": "user", "content": message["text"]}]
if target in ["Model 2", "Both"]:
for x in message["files"]:
history2.append({"role": "user", "content": {"path": x}})
if message["text"] is not None:
history2.append({"role": "user", "content": message["text"]})
test_entry_2["question"] = [{"role": "user", "content": message["text"]}]
return history1, history2, gr.MultimodalTextbox(value=None, interactive=False)
def equalize_and_zip(list1, list2):
# Determine the maximum length of the two lists
if list1 == None:
list1 = []
if list2 == None:
list2 = []
if isinstance(list1, str):
list1 = [list1]
if isinstance(list2, str):
list2 = [list2]
max_len = max(len(list1), len(list2))
# Extend both lists to the same length by appending None
list1.extend([None] * (max_len - len(list1)))
list2.extend([None] * (max_len - len(list2)))
# Zip the lists together
return list(zip(list1, list2))
def consume_data(shared_queue):
none_list = []
while True:
data = shared_queue.get()
if data is None:
if data in none_list:
print("[Consumer] No more data to consume. Exiting.")
break
else:
none_list.append(data)
yield data
def bot(history1: list, history2: list, target):
if target == "Model 1":
gen = bot_response(history1, handler_1, test_entry_1, inference_data_1, "Model 1")
print("gen: ", gen)
while True:
stop = True
try:
gen_his_1 = next(gen)
stop = False
yield gen_his_1, history2
except StopIteration:
pass
if stop:
break
elif target == "Model 2":
gen = bot_response(history2, handler_2, test_entry_2, inference_data_2, "Model 2")
while True:
stop = True
try:
gen_his_2 = next(gen)
stop = False
yield history1, gen_his_2
except StopIteration:
pass
if stop:
break
elif target == "Both":
gen1 = bot_response(history1, handler_1, test_entry_1, inference_data_1, "Model 1")
gen2 = bot_response(history2, handler_2, test_entry_2, inference_data_2, "Model 2")
while True:
stop = True
try:
gen_his_1 = next(gen1)
stop = False
except StopIteration:
pass
try:
gen_his_2 = next(gen2)
stop = False
except StopIteration:
pass
yield gen_his_1, gen_his_2
if stop:
break
def bot_response(history, handler, test_entry, inference_data, model_target):
global inference_data_1, inference_data_2
for item in handler.inference(test_entry, inference_data):
# Processing logic remains the same
if item[0] == "regular":
responses_results = equalize_and_zip(item[1], item[2])
for (model_res, exec_res) in responses_results:
if model_res is not None:
response = model_res
history.append({"role": "assistant", "content": "<b>Model Response🤖: </b><br>"})
for character in response:
history[-1]["content"] += character
time.sleep(0.01)
yield history
if exec_res is not None:
response = exec_res
history[-1]["content"] += "<br><br><b>Model Execution💻: </b><br>"
yield history
# history.append({"role": "assistant", "content": "<span class='bot-highlight'> Model Execution: </span>"})
for character in response:
# history[-1]["content"] = history[-1]["content"][0:-7] + character + "</span>"
history[-1]["content"] += character
time.sleep(0.01)
yield history
elif item[0] == 'summary':
response = item[1]
if response is not None:
history.append({"role": "assistant", "content": "<b>Summary✅: </b><br>"})
for character in response:
history[-1]["content"] += character
time.sleep(0.01)
yield history
elif item[0] == "final":
# Update inference data based on the target
if model_target == "Model 1":
inference_data_1 = item[2]
elif model_target == "Model 2":
inference_data_2 = item[2]
# Saves the model, cateogry, temperature, and history to the database
def save_1(history):
if len(history) > 2:
document = {"model": current_model_1,
"category": current_category,
"temperature": current_temperature_1,
"history": history}
# Have error in database connection
collection.insert_one(document)
def save_2(history):
if len(history) > 2:
document = {"model": current_model_2,
"category": current_category,
"temperature": current_temperature_2,
"history": history}
# Have error in database connection
collection.insert_one(document)
# Function to assign new unique ID on restart or at the start
def restart_chat_1(history):
global test_entry_1
test_entry_1["id"] = str(uuid.uuid4()) # Reinitialize test_entry with new ID
global handler_1
handler_1 = get_handler(model_dropdown_1.value, temperature_slider_1.value)
# print("test: entry", test_entry_1)
return [{"role": "user", "content": "Hi, can you help me with some tasks?"},
{"role": "assistant", "content": "Hello there! How can I assist you today?"}]
# Saves history before restarting chat,
def restart_chat_and_save_1(history):
save_1(history)
return restart_chat_1(history)
def restart_chat_2(history):
global test_entry_2
test_entry_2["id"] = str(uuid.uuid4()) # Reinitialize test_entry with new ID
global handler_2
handler_2 = get_handler(model_dropdown_2.value, temperature_slider_2.value)
# print("test: entry", test_entry_2)
return [{"role": "user", "content": "Hi, can you help me with some tasks?"},
{"role": "assistant", "content": "Hello there! How can I assist you today?"}]
# Saves history before restarting chat,
def restart_chat_and_save_2(history):
save_2(history)
return restart_chat_2(history)
# Function to report an issue
def report_issue():
return gr.Info("Thank you for reporting the issue. Our team will look into it.")
# Update handler 1 when model or temperature is changed
def update_handler_1(model, temp_slider, history):
global current_model_1
current_model_1 = model
global current_temperature_1
current_temperature_1 = temp_slider
print("update handler 1: ", model, temp_slider)
global handler_1
handler_1 = get_handler(model, temp_slider) # Reinitialize handler with new model and temperature
restart_history = restart_chat_1(history)
return model, restart_history
# Update handler 2 when model or temperature is changed
def update_handler_2(model, temp_slider, history):
global current_model_2
current_model_2 = model
global current_temperature_2
current_temperature_2 = temp_slider
print("update handler 2: ", model, temp_slider)
global handler_2
handler_2 = get_handler(model, temp_slider) # Reinitialize handler with new model and temperature
restart_history = restart_chat_2(history)
return model, restart_history
# Update involved_classes and load config based on category
def update_category_and_load_config(category):
global current_category
current_category = category
print("update category: ", category)
global test_entry_1, test_entry_2
# Update involved_classes
test_entry_1["initial_config"] = {category: {}}
test_entry_1["involved_classes"] = [category]
test_entry_2["initial_config"] = {category: {}}
test_entry_2["involved_classes"] = [category]
# Load the JSON file from the config folder corresponding to the category
config_path = os.path.join("config", f"{category}.json")
if os.path.exists(config_path):
with open(config_path, 'r') as config_file:
data = json.load(config_file)
test_entry_1["function"] = data.copy() # Load JSON content into test_entry["function"]
test_entry_2["function"] = data.copy()
return category
def load_example(example):
if example == "Example 1 - GFSFileSystem":
return models[0], 0.8, models[1], 0.3, categories[0], "Move final_report.pdf' within document directory to 'temp' directory in document. Make sure to create the directory"
elif example == "Example 2 - TradingBot":
return models[1], 0.9, models[2], 0.7, categories[5], "I'm contemplating enhancing my investment portfolio with some tech industry assets, and I've got my eye on Nvidia Corp. I'm keen to know its current stock price, and would appreciate if you could source this information for me."
elif example == "Example 3 - TravelAPI":
return models[2], 0.7, models[0], 0.2, categories[6], "As I plan a getaway, I'm curious about all the airports available for my travel. Would you share that information with me?"
return models[0], 0.7, models[2], 0.36, categories[0], "Move final_report.pdf' within document directory to 'temp' directory in document. Make sure to create the directory"
# Add logic to load examples when example buttons are clicked
def load_example_and_update(example, history_1, history_2):
save_1(history_1)
save_2(history_2)
# Load the example configuration
model_1, temp_1, model_2, temp_2, category, message = load_example(example)
update_category_and_load_config(category)
# Update the interface components
return model_1, temp_1, model_2, temp_2, category, message
# initialize test entry with default configurations
update_category_and_load_config(categories[0])
with gr.Blocks(css=custom_css) as demo:
gr.Markdown("# Multiturn LLM Chat Interface")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("## Configurations")
model_dropdown_1 = gr.Dropdown(choices=models, label="Select Model 1", value=DEFAULT_MODEL_1, interactive=True)
temperature_slider_1 = gr.Slider(0, 1, value=DEFAULT_TEMPERATURE_1, label="Temperature 1", interactive=True)
model_dropdown_2 = gr.Dropdown(choices=models, label="Select Model 2", value=DEFAULT_MODEL_2, interactive=True)
temperature_slider_2 = gr.Slider(0, 1, value=DEFAULT_TEMPERATURE_2, label="Temperature 2", interactive=True)
category_dropdown = gr.Dropdown(choices=categories, label="Select Category", value=categories[0], interactive=True)
with gr.Column(scale=3):
with gr.Row():
with gr.Column():
gr.Markdown("### Model 1")
chatbot1 = gr.Chatbot(elem_id="chatbot1", bubble_full_width=False, type="messages")
with gr.Row():
restart_btn_1 = gr.Button("Restart")
report_btn_1 = gr.Button("Report Issue")
with gr.Column():
gr.Markdown("### Model 2")
chatbot2 = gr.Chatbot(elem_id="chatbot2", bubble_full_width=False, type="messages")
with gr.Row():
restart_btn_2 = gr.Button("Restart")
report_btn_2 = gr.Button("Report Issue")
with gr.Row():
target_dropdown = gr.Dropdown(choices=["Model 1", "Model 2", "Both"], container=False, value="Both", interactive=True, scale=1)
chat_input = gr.MultimodalTextbox(
interactive=True,
file_count="multiple",
placeholder="Enter message or upload file...",
show_label=False,
scale=4
)
demo.load(lambda: get_initial_state(), outputs=chatbot1)
demo.load(lambda: get_initial_state(), outputs=chatbot2)
chat_msg = chat_input.submit(
add_message, [chatbot1, chatbot2, chat_input, target_dropdown], [chatbot1, chatbot2, chat_input]
)
bot_msg = chat_msg.then(bot, inputs=[chatbot1, chatbot2, target_dropdown], outputs=[chatbot1, chatbot2])
bot_msg.then(lambda: gr.MultimodalTextbox(interactive=True), None, [chat_input])
chatbot1.like(print_like_dislike, None, None, like_user_message=True)
chatbot2.like(print_like_dislike, None, None, like_user_message=True)
with gr.Row():
example_btn1 = gr.Button("Example 1 - GFSFileSystem")
example_btn2 = gr.Button("Example 2 - TradingBot")
example_btn3 = gr.Button("Example 3 - TravelAPI")
gr.Markdown("<br><br>")
for category in categories:
with gr.Tab(category):
with gr.Group():
category_info = api_info[api_info["Class Name"] == category]
with gr.Accordion("Function description", open=False):
with gr.Group():
for i in range(len(category_info)):
with gr.Accordion(category_info.iloc[i]["Function Name"], open=False):
gr.Markdown(category_info.iloc[i]["Description"])
# Sample demo, limit 5 per categories
samples = [[sample['question'], sample['ground_truth']] for _, sample in api_samples.iterrows() if category in sample['involved_classes']][:5]
gr.Dataset(
components=[gr.HTML(), gr.Markdown()],
headers= ["Prompt", "API Use"],
samples= samples
)
# Update handler when the model or temperature is changed
model_dropdown_1.change(
update_handler_1,
[model_dropdown_1, temperature_slider_1, chatbot1],
[model_dropdown_1, chatbot1]
)
# Update handler when the model or temperature is changed
model_dropdown_2.change(
update_handler_2,
[model_dropdown_2, temperature_slider_2, chatbot2],
[model_dropdown_2, chatbot2]
)
temperature_slider_1.change(
update_handler_1,
[model_dropdown_1, temperature_slider_1, chatbot1],
[model_dropdown_1, chatbot1]
)
temperature_slider_2.change(
update_handler_2,
[model_dropdown_2, temperature_slider_2, chatbot2],
[model_dropdown_2, chatbot2]
)
# Update category and load config when a category is selected
category_dropdown.change(
update_category_and_load_config,
inputs=category_dropdown,
outputs=category_dropdown
)
# Set up the event handler for the restart button to reset the chat and test_entry
restart_btn_1.click(restart_chat_and_save_1, [chatbot1], [chatbot1])
report_btn_1.click(report_issue, None, None)
restart_btn_2.click(restart_chat_and_save_2, [chatbot2], [chatbot2])
report_btn_2.click(report_issue, None, None)
example_btn1.click(load_example_and_update, inputs=[example_btn1, chatbot1, chatbot2],
outputs=[model_dropdown_1, temperature_slider_1, model_dropdown_2, temperature_slider_2, category_dropdown, chat_input])
example_btn2.click(load_example_and_update, inputs=[example_btn2, chatbot1, chatbot2],
outputs=[model_dropdown_1, temperature_slider_1, model_dropdown_2, temperature_slider_2, category_dropdown, chat_input])
example_btn3.click(load_example_and_update, inputs=[example_btn3, chatbot1, chatbot2],
outputs=[model_dropdown_1, temperature_slider_1, model_dropdown_2, temperature_slider_2, category_dropdown, chat_input])
demo.launch(share=False)
|