# Reference:
#
# https://vimeo.com/990334325/56b552bc7a
# https://platform.openai.com/playground/assistants
# https://cookbook.openai.com/examples/assistants_api_overview_python
# https://platform.openai.com/docs/api-reference/assistants/createAssistant
# https://platform.openai.com/docs/assistants/tools
import gradio as gr
import os, threading
from assistants import (
set_openai_client,
get_assistant,
set_assistant,
get_thread,
set_thread,
create_assistant,
load_assistant,
create_thread,
create_message,
create_run,
wait_on_run,
get_run_steps,
recurse_execute_tool_calls,
get_messages,
extract_content_values,
)
lock = threading.Lock()
def chat(message, history, openai_api_key):
if not openai_api_key:
raise gr.Error("OpenAI API Key is required (see additional inputs below).")
if not message:
raise gr.Error("Message is required.")
with lock:
text_value, image_value = "", ""
try:
if os.environ["OPENAI_API_KEY"] != openai_api_key:
os.environ["OPENAI_API_KEY"] = openai_api_key
set_openai_client()
#set_assistant(create_assistant()) # first run
set_assistant(load_assistant()) # subsequent runs
if get_thread() == None or len(history) == 0:
set_thread(create_thread())
create_message(get_thread(), message)
run = create_run(get_assistant(), get_thread())
run = wait_on_run(get_thread(), run)
run_steps = get_run_steps(get_thread(), run)
recurse_execute_tool_calls(get_thread(), run, run_steps, 0)
messages = get_messages(get_thread())
text_values, image_values = extract_content_values(messages)
if len(image_values) > 0:
image_value = f"[https://platform.openai.com/storage/files/{image_values[0]}](https://platform.openai.com/storage/files/{image_values[0]})
"
for text_value in list(reversed(text_values)):
text_value += f"{text_value}
"
except Exception as e:
raise gr.Error(e)
return f"{image_value}{text_value}"
#return f"{'