|
import os |
|
import time |
|
import datetime |
|
import gradio as gr |
|
from openai.types.beta.threads.runs import ToolCallsStepDetails |
|
from openai import ( |
|
OpenAI, AuthenticationError, NotFoundError, BadRequestError |
|
) |
|
|
|
|
|
|
|
|
|
|
|
DF_MODEL = "gpt-3.5-turbo-1106" |
|
ASSIST_NAME = "Code Interpreter Assistant for O3" |
|
AST_SYS_PROMPT = "あなたは優秀なアシスタントです。質問をされた場合は、質問に答えるコードを作成して実行します。回答は日本語でお願いします。" |
|
|
|
|
|
|
|
file_format = {".txt", ".csv", ".jpg", ".jpeg", ".png", ".xlsx", ".pdf", ".zip"} |
|
|
|
|
|
FONT_FILE_PATH = "for_assistants/NotoSansJP-Bold.zip" |
|
|
|
|
|
|
|
|
|
PLACEHOLDER = "これは東京都の年別人口データです、折れ線グラフでデータの可視化をお願いします… など" |
|
IMG_MSG = "(画像ファイルを追加しました。リセットボタンの上に表示されています。)" |
|
ANT_MSG = "(下部の[出力ファイル]にファイルを追加しました。)" |
|
|
|
|
|
MAX_TRIAL = int(os.environ["MAX_TRIAL"]) |
|
INTER_SEC = int(os.environ["INTER_SEC"]) |
|
|
|
|
|
|
|
examples = ["sample_data/東京都男女別人口_y23.csv","sample_data/東京都年齢別人口_y23.csv"] |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
code_mode = {'ON': True, 'OFF': False} |
|
|
|
|
|
|
|
def set_state(openai_key, sys_prompt, code_output, state): |
|
""" 設定タブの情報をセッションに保存する関数 """ |
|
|
|
state["openai_key"] = openai_key |
|
state["system_prompt"] = sys_prompt |
|
state["code_mode"] = code_mode[code_output] |
|
|
|
return state |
|
|
|
|
|
def init(state, text, file): |
|
""" 入力チェックを行う関数 |
|
※ここで例外を起こすと入力できなくなるので次の関数でエラーにする """ |
|
|
|
err_msg = "" |
|
file_id = None |
|
|
|
if state["openai_key"] == "": |
|
|
|
|
|
err_msg = "OpenAI API Keyを入力してください。(設定タブ)" |
|
|
|
return state, file_id, err_msg |
|
|
|
if not text: |
|
|
|
|
|
err_msg = "テキストを入力して下さい。" |
|
|
|
return state, file_id, err_msg |
|
|
|
elif file: |
|
|
|
|
|
root, ext = os.path.splitext(file) |
|
|
|
if ext not in file_format: |
|
|
|
|
|
err_msg = "指定した形式のファイルをアップしてください。(注意事項タブに記載)" |
|
|
|
return state, file_id, err_msg |
|
|
|
try: |
|
|
|
if state["client"] is None: |
|
|
|
|
|
|
|
os.environ["OPENAI_API_KEY"] = state["openai_key"] |
|
|
|
|
|
client = OpenAI() |
|
|
|
|
|
os.environ["OPENAI_API_KEY"] = "" |
|
|
|
|
|
state["client"] = client |
|
|
|
else: |
|
|
|
|
|
client = state["client"] |
|
|
|
if state["thread_id"] == "": |
|
|
|
|
|
thread = client.beta.threads.create() |
|
|
|
state["thread_id"] = thread.id |
|
|
|
|
|
if state["assistant_id"] == "": |
|
|
|
|
|
assistant_id = get_assist_id(client, ASSIST_NAME) |
|
|
|
if assistant_id == "": |
|
|
|
|
|
font_file_response = client.files.create( |
|
purpose="assistants", |
|
file=open(FONT_FILE_PATH,"rb"), |
|
) |
|
|
|
|
|
font_file_id = font_file_response.id |
|
|
|
|
|
assistant = client.beta.assistants.create( |
|
name=ASSIST_NAME, |
|
instructions=AST_SYS_PROMPT, |
|
model=DF_MODEL, |
|
file_ids=[font_file_id], |
|
tools=[{"type": "code_interpreter"}] |
|
) |
|
|
|
assistant_id = assistant.id |
|
|
|
state["assistant_id"] = assistant_id |
|
|
|
|
|
os.makedirs(state["assistant_id"], exist_ok=True) |
|
|
|
if file: |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
file_response = client.files.create( |
|
purpose="assistants", |
|
file=open(file,"rb"), |
|
) |
|
|
|
if file_response.status != "processed": |
|
|
|
|
|
err_msg = "ファイルのアップロードに失敗しました" |
|
|
|
else: |
|
|
|
file_id = file_response.id |
|
|
|
|
|
except NotFoundError as e: |
|
err_msg = "アシスタントIDが間違っています。新しく作成する場合はアシスタントIDを空欄にして下さい。" |
|
except AuthenticationError as e: |
|
err_msg = "認証エラーとなりました。OpenAPIKeyが正しいか、支払い方法などが設定されているか確認して下さい。" |
|
except Exception as e: |
|
err_msg = "その他のエラーが発生しました。" |
|
print(e) |
|
finally: |
|
return state, file_id, err_msg |
|
|
|
def get_assist_id(client, assist_name): |
|
|
|
assist_id = "" |
|
|
|
assist_list = client.beta.assistants.list() |
|
|
|
if len(assist_list.data) == 0: |
|
|
|
return assist_id |
|
|
|
for assist in assist_list: |
|
|
|
if assist.name == assist_name: |
|
|
|
assist_id = assist.id |
|
|
|
break |
|
|
|
return assist_id |
|
|
|
def raise_exception(err_msg): |
|
""" エラーの場合例外を起こす関数 """ |
|
|
|
if err_msg != "": |
|
raise Exception("これは入力チェックでの例外です。") |
|
|
|
return |
|
|
|
|
|
def add_history(history, text, file_id): |
|
""" Chat履歴"history"に追加を行う関数 """ |
|
|
|
err_msg = "" |
|
|
|
|
|
history = history + [(text, None)] |
|
|
|
|
|
update_text = gr.update(value="", placeholder = "",interactive=False) |
|
update_file = gr.update(value=None, interactive=False) |
|
|
|
return history, update_text, update_file, err_msg |
|
|
|
|
|
def bot(state, history, file_id): |
|
|
|
err_msg = "" |
|
image_file = None |
|
ant_file = None |
|
|
|
|
|
system_prompt = state["system_prompt"] |
|
client = state["client"] |
|
assistant_id = state["assistant_id"] |
|
thread_id = state["thread_id"] |
|
last_msg_id = state["last_msg_id"] |
|
code_mode = state["code_mode"] |
|
|
|
if file_id is None or file_id == "": |
|
|
|
|
|
message = client.beta.threads.messages.create( |
|
thread_id=thread_id, |
|
role="user", |
|
content=history[-1][0], |
|
) |
|
else: |
|
|
|
|
|
message = client.beta.threads.messages.create( |
|
thread_id=thread_id, |
|
role="user", |
|
content=history[-1][0], |
|
file_ids=[file_id] |
|
) |
|
|
|
print(message) |
|
|
|
|
|
run = client.beta.threads.runs.create( |
|
thread_id=thread_id, |
|
assistant_id=assistant_id, |
|
|
|
) |
|
|
|
|
|
for i in range(0, MAX_TRIAL, 1): |
|
|
|
if i > 0: |
|
time.sleep(INTER_SEC) |
|
|
|
|
|
run = client.beta.threads.runs.retrieve( |
|
thread_id=thread_id, |
|
run_id=run.id |
|
) |
|
|
|
|
|
messages = client.beta.threads.messages.list( |
|
thread_id=thread_id, |
|
after=last_msg_id, |
|
order="asc" |
|
) |
|
|
|
|
|
print(run.status) |
|
print(messages) |
|
|
|
|
|
for msg in messages: |
|
|
|
if msg.role == "assistant": |
|
|
|
for content in msg.content: |
|
|
|
res_text = "" |
|
file_id = "" |
|
ant_file = None |
|
|
|
cont_dict = content.model_dump() |
|
|
|
ct_image_file = cont_dict.get("image_file") |
|
|
|
if ct_image_file: |
|
|
|
|
|
res_file_id = ct_image_file.get("file_id") |
|
|
|
|
|
image_file = file_download(client, res_file_id, assistant_id, ".png") |
|
|
|
if image_file is None: |
|
|
|
err_msg = "ファイルのダウンロードに失敗しました。" |
|
|
|
else: |
|
|
|
res_text = IMG_MSG |
|
|
|
history = history + [[None, res_text]] |
|
|
|
|
|
last_msg_id = msg.id |
|
|
|
else: |
|
|
|
|
|
res_text = cont_dict["text"].get("value") |
|
|
|
|
|
if len(cont_dict.get("text").get("annotations")) > 0: |
|
|
|
ct_ant = cont_dict.get("text").get("annotations") |
|
|
|
if ct_ant[0].get("file_path") is not None: |
|
|
|
|
|
ant_file_id = ct_ant[0].get("file_path").get("file_id") |
|
|
|
if ct_ant[0].get("text") is not None: |
|
|
|
|
|
ext = "." + ct_ant[0].get("text")[ct_ant[0].get("text").rfind('.') + 1:] |
|
|
|
|
|
ant_file = file_download(client, ant_file_id, assistant_id, ext) |
|
|
|
if ant_file is None: |
|
|
|
err_msg = "参照ファイルのダウンロードに失敗しました。" |
|
|
|
else: |
|
|
|
|
|
res_text = res_text + "\n\n" + ANT_MSG |
|
|
|
if res_text != "": |
|
|
|
|
|
if history[-1][1] is not None: |
|
|
|
|
|
history = history + [[None, res_text]] |
|
else: |
|
|
|
history[-1][1] = res_text |
|
|
|
|
|
last_msg_id = msg.id |
|
|
|
|
|
yield gr.Chatbot(label=run.status, value=history), image_file, ant_file, err_msg |
|
|
|
|
|
state["last_msg_id"] = last_msg_id |
|
|
|
|
|
if run.status == "completed": |
|
|
|
if not code_mode: |
|
|
|
|
|
|
|
break |
|
else: |
|
|
|
|
|
run_steps = client.beta.threads.runs.steps.list( |
|
thread_id=thread_id, run_id=run.id |
|
) |
|
|
|
|
|
input_code = get_code(run_steps) |
|
|
|
if len(input_code) > 0: |
|
|
|
for code in input_code: |
|
|
|
code = "[input_code]\n\n" + code |
|
|
|
|
|
history = history + [[None, code]] |
|
|
|
yield gr.Chatbot(label=run.status ,value=history), image_file, ant_file, err_msg |
|
|
|
break |
|
|
|
elif run.status == "failed": |
|
|
|
|
|
err_msg = "※メッセージ取得に失敗しました。" |
|
yield gr.Chatbot(label=run.status ,value=history), image_file, ant_file, err_msg |
|
break |
|
|
|
elif i == MAX_TRIAL: |
|
|
|
|
|
err_msg = "※メッセージ取得の際にタイムアウトしました。" |
|
yield gr.Chatbot(label=run.status ,value=history), image_file, ant_file, err_msg |
|
break |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_code(run_steps): |
|
""" 生成過程のコードを全てを返す """ |
|
|
|
input_code = [] |
|
|
|
for data in run_steps.data: |
|
|
|
if isinstance(data.step_details, ToolCallsStepDetails): |
|
|
|
|
|
for tool_call in data.step_details.tool_calls: |
|
|
|
input_code.append(tool_call.code_interpreter.input) |
|
|
|
return input_code |
|
|
|
|
|
def file_download(client, file_id, folder, ext): |
|
""" OpenAIからファイルをダウンロードしてパスを返す """ |
|
|
|
api_response = client.files.with_raw_response.retrieve_content(file_id) |
|
|
|
if api_response.status_code == 200: |
|
|
|
content = api_response.content |
|
|
|
file_path = folder + "/" + file_id + ext |
|
|
|
with open(file_path, 'wb') as f: |
|
f.write(content) |
|
|
|
return file_path |
|
|
|
else: |
|
return None |
|
|
|
|
|
def finally_proc(): |
|
""" 最終処理用関数 """ |
|
|
|
|
|
interactive = gr.update(interactive = True) |
|
|
|
|
|
new_file_id = gr.Textbox(value="") |
|
|
|
return interactive, interactive, new_file_id |
|
|
|
|
|
def clear_click(state): |
|
""" クリアボタンクリック時 """ |
|
|
|
|
|
|
|
state["thread_id"] = "" |
|
state["last_msg_id"] = "" |
|
|
|
return state |
|
|
|
|
|
with gr.Blocks() as demo: |
|
|
|
title = "<h2>GPT Code Interpreter対応チャット</h2>" |
|
message = "・設定タブからAPIKEYを入力してください<br>" |
|
message += "・こういうときにエラーになるなどフィードバックあればお待ちしています。<br>" |
|
message += "・コードインタープリターAPIの解説動画はこちらです→" |
|
message += "https://www.youtube.com/watch?v=tFmedAM1FM8<br>" |
|
message += '※動いているかわかりづらいですが、左上の"in_progress(Request:XX)"が止まっていなければ回答の生成中となります。<br>' |
|
message += "※グラフの日本語文字化けの対応方法を注意事項に記載しました。<br>" |
|
|
|
|
|
|
|
|
|
|
|
gr.Markdown(title + "<h3>" + message + "</h3>") |
|
|
|
|
|
state = gr.State({ |
|
"system_prompt": "", |
|
"openai_key" : "", |
|
"code_mode" : False, |
|
"client" : None, |
|
"assistant_id" : "", |
|
"thread_id" : "", |
|
"last_msg_id" : "" |
|
}) |
|
|
|
with gr.Tab("Chat画面") as chat: |
|
|
|
|
|
chatbot = gr.Chatbot(label="チャット画面") |
|
text_msg = gr.Textbox(label="テキスト", placeholder = PLACEHOLDER) |
|
with gr.Row(): |
|
up_file = gr.File(label="ファイルアップロード", type="filepath",interactive = True) |
|
result_image = gr.Image(label="出力画像", type="filepath", interactive = False) |
|
gr.Examples(label="サンプルデータ", examples=examples, inputs=[up_file]) |
|
with gr.Row(): |
|
btn = gr.Button(value="送信") |
|
|
|
|
|
btn_clear = gr.ClearButton(value="リセット", components=[chatbot, text_msg, up_file, result_image]) |
|
sys_msg = gr.Textbox(label="システムメッセージ", interactive = False) |
|
result_file = gr.File(label="出力ファイル", type="filepath",interactive = False) |
|
|
|
|
|
file_id = gr.Textbox(visible=False) |
|
|
|
|
|
bc = btn.click(init, [state, text_msg, up_file], [state, file_id, sys_msg], queue=False).success( |
|
raise_exception, sys_msg, None).success( |
|
add_history, [chatbot, text_msg, file_id], [chatbot, text_msg, up_file, sys_msg], queue=False).success( |
|
bot, [state, chatbot, file_id],[chatbot, result_image, result_file, sys_msg]).then( |
|
finally_proc, None, [text_msg, up_file, file_id], queue=False |
|
) |
|
|
|
|
|
btn_clear.click(clear_click, state, state) |
|
|
|
|
|
|
|
|
|
with gr.Tab("設定") as set: |
|
openai_key = gr.Textbox(label="OpenAI API Key", visible=True) |
|
|
|
system_prompt = gr.Textbox(value = "",lines = 5, label="Custom instructions", interactive = True, visible=False) |
|
code_output = gr.Dropdown(label="コード出力", choices=["OFF", "ON"], value = "OFF", interactive = True) |
|
|
|
|
|
chat.select(set_state, [openai_key, system_prompt, code_output, state], state) |
|
|
|
with gr.Tab("注意事項") as notes: |
|
caution = "現在Assistant APIはβ版でのリリースとなっています。<br>" |
|
|
|
|
|
|
|
caution += "文字化けする場合「NotoSansJP-Bold.zipを解凍してフォントを取得して下さい。」と指示し<br>" |
|
caution += "グラフ作成時に「フォントはNotoSansJP-Boldを使用して下さい。」と指示して下さい。<br>" |
|
caution += "※NotoSansJP-Bold.zipをアップする必要はありません。<br>" |
|
caution += "詳細はこちら→https://github.com/nekoniii3/openai_multi_chat/tree/main/Code_Interpreter/docs/%E6%97%A5%E6%9C%AC%E8%AA%9E%E3%83%95%E3%82%A9%E3%83%B3%E3%83%88%E5%88%A9%E7%94%A8" |
|
gr.Markdown("<h3>" + caution + "</h3>") |
|
|
|
|
|
if __name__ == "__main__": |
|
|
|
demo.queue() |
|
demo.launch(debug=True) |