Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,44 +1,61 @@
|
|
| 1 |
-
|
| 2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
import datetime
|
| 5 |
-
|
| 6 |
from openai import OpenAI
|
| 7 |
-
|
| 8 |
-
from openai.types.beta.threads.runs import (
|
| 9 |
-
ToolCallsStepDetails,
|
| 10 |
-
)
|
| 11 |
|
| 12 |
# GPT用設定
|
| 13 |
SYS_PROMPT_DEFAULT = "あなたは優秀なアシスタントです。質問をされた場合は、質問に答えるコードを作成して実行します。回答は日本語でお願いします。"
|
| 14 |
DUMMY = "********************"
|
| 15 |
-
file_format = {".txt", ".csv", ".pdf"}
|
|
|
|
| 16 |
|
| 17 |
# 各種出力フォルダ
|
| 18 |
-
IMG_FOLDER = "
|
| 19 |
-
ANT_FOLDER = "
|
| 20 |
|
| 21 |
# 各種メッセージ
|
| 22 |
-
|
|
|
|
| 23 |
ANT_MSG = "(下部の[出力ファイル]にファイルを追加しました。)"
|
| 24 |
|
| 25 |
# 各種設定値
|
| 26 |
-
MAX_TRIAL =
|
| 27 |
-
INTER_SEC =
|
| 28 |
|
| 29 |
# サンプル用情報
|
| 30 |
-
examples = ["sample_data/東京都年別人口.csv", "sample_data/練馬区年齢別人口.csv", "sample_data/桃太郎あらすじ.txt"]
|
|
|
|
| 31 |
example_toid = {"東京都年別人口.csv" : "file-GOEk4X4WpU5gBJAuHCMtiJrn"
|
|
|
|
| 32 |
, "練馬区年齢別人口.csv" : "file-YAFPMMqG3Zl5DRx5hTLjCfFa"
|
| 33 |
, "桃太郎あらすじ.txt" : "file-oDjAzL3G4ktwAUEkcGDCQMuQ"}
|
| 34 |
|
| 35 |
-
# file_id = "file-0Ly64DA2jzE9mOFYayOKJJK0"
|
| 36 |
-
# file_id = "file-aVnVcpEVpsy77xQ8SlTp1WoX" # ライ麦
|
| 37 |
-
# file_id = "file-HFCaJbf3k7j0fhBqh1Rwf2VV" # 練馬区
|
| 38 |
-
|
| 39 |
# コード出力用
|
| 40 |
code_mode = {'ON': True, 'OFF': False}
|
| 41 |
|
|
|
|
|
|
|
| 42 |
def set_state(openai_key, sys_prompt, code_output, state):
|
| 43 |
""" 設定タブの情報をセッションに保存する関数 """
|
| 44 |
|
|
@@ -53,6 +70,8 @@ def init(state, text, file):
|
|
| 53 |
""" 入力チェックを行う関数
|
| 54 |
※ここで例外を起こすと入力できなくなるので次の関数でエラーにする """
|
| 55 |
|
|
|
|
|
|
|
| 56 |
err_msg = ""
|
| 57 |
file_id = None
|
| 58 |
|
|
@@ -66,7 +85,7 @@ def init(state, text, file):
|
|
| 66 |
# テキスト未入力
|
| 67 |
err_msg = "テキストを入力して下さい。"
|
| 68 |
|
| 69 |
-
return state,
|
| 70 |
|
| 71 |
elif file:
|
| 72 |
|
|
@@ -78,20 +97,40 @@ def init(state, text, file):
|
|
| 78 |
# ファイル形式チェック
|
| 79 |
err_msg = "指定した形式のファイルをアップしてください。(注意事項タブに記載)"
|
| 80 |
|
| 81 |
-
return state,
|
|
|
|
| 82 |
|
| 83 |
if state["client"] is None:
|
| 84 |
|
| 85 |
# 初回起動時は初期処理をする
|
| 86 |
os.environ["OPENAI_API_KEY"] = os.environ["TEST_OPENAI_KEY"] # テスト時
|
| 87 |
-
|
| 88 |
# os.environ["OPENAI_API_KEY"] = state["openai_key"]
|
| 89 |
|
|
|
|
| 90 |
client = OpenAI()
|
| 91 |
|
| 92 |
# client作成後は消す
|
| 93 |
os.environ["OPENAI_API_KEY"] = ""
|
| 94 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
# アシスタント作成
|
| 96 |
# assistant = client.beta.assistants.create(
|
| 97 |
# name="codeinter_test",
|
|
@@ -100,17 +139,10 @@ def init(state, text, file):
|
|
| 100 |
# model="gpt-3.5-turbo-1106",
|
| 101 |
# tools=[{"type": "code_interpreter"}]
|
| 102 |
# )
|
| 103 |
-
|
| 104 |
-
# print(assistant.id)
|
| 105 |
-
|
| 106 |
-
# スレッド作��
|
| 107 |
-
thread = client.beta.threads.create()
|
| 108 |
-
|
| 109 |
-
# セッションにセット
|
| 110 |
-
state["client"] = client
|
| 111 |
# state["assistant_id"] = assistant.id
|
|
|
|
| 112 |
state["assistant_id"] = os.environ["ASSIST_ID"] # テスト中アシスタントは固定
|
| 113 |
-
|
| 114 |
|
| 115 |
if file:
|
| 116 |
|
|
@@ -119,35 +151,30 @@ def init(state, text, file):
|
|
| 119 |
|
| 120 |
if example_toid.get(basename):
|
| 121 |
|
| 122 |
-
|
| 123 |
-
|
| 124 |
|
| 125 |
else:
|
| 126 |
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
# if file_response.status != 'processed':
|
| 134 |
|
| 135 |
-
|
| 136 |
-
# err_msg = "ファイルのアップロードに失敗しました"
|
| 137 |
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
# file_id = file_response.id
|
| 141 |
|
| 142 |
-
|
| 143 |
-
|
|
|
|
| 144 |
|
| 145 |
-
|
| 146 |
-
file_id = ""
|
| 147 |
|
| 148 |
-
|
| 149 |
|
| 150 |
-
return state, text, file, file_id, err_msg
|
| 151 |
|
| 152 |
def raise_exception(err_msg):
|
| 153 |
""" エラーの場合例外を起こす関数 """
|
|
@@ -161,51 +188,24 @@ def raise_exception(err_msg):
|
|
| 161 |
def add_history(history, text, file_id):
|
| 162 |
""" Chat履歴"history"に追加を行う関数 """
|
| 163 |
|
| 164 |
-
# print("前:")
|
| 165 |
-
# print(history)
|
| 166 |
-
|
| 167 |
err_msg = ""
|
| 168 |
-
new_row_flg = False
|
| 169 |
-
|
| 170 |
-
# 新しい行を追加するか判定
|
| 171 |
-
# if len(history) == 0:
|
| 172 |
-
|
| 173 |
-
# new_row_flg = True
|
| 174 |
-
|
| 175 |
-
# elif history[-1][0] is not None:
|
| 176 |
-
|
| 177 |
-
# # 前回がアシスタントでない場合も追加
|
| 178 |
-
# new_row_flg = True
|
| 179 |
-
|
| 180 |
-
new_row_flg = True
|
| 181 |
|
| 182 |
if file_id is None or file_id == "":
|
| 183 |
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
# テキストだけの場合そのまま追加
|
| 187 |
-
history = history + [(text, None)]
|
| 188 |
-
else:
|
| 189 |
-
history[-1][0] = text
|
| 190 |
|
| 191 |
elif file_id is not None:
|
| 192 |
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
history = history + [("file:" + file_id, DUMMY)]
|
| 197 |
-
history = history + [(text, None)]
|
| 198 |
-
|
| 199 |
-
else:
|
| 200 |
-
history[-1][0] = "file:" + file_id
|
| 201 |
-
history = history + [(text, None)]
|
| 202 |
|
| 203 |
-
|
|
|
|
|
|
|
| 204 |
|
| 205 |
-
|
| 206 |
-
new_text = gr.Textbox(value="", interactive=True)
|
| 207 |
-
|
| 208 |
-
return history, new_text, err_msg
|
| 209 |
|
| 210 |
|
| 211 |
def bot(state, history, file_id):
|
|
@@ -213,7 +213,6 @@ def bot(state, history, file_id):
|
|
| 213 |
err_msg = ""
|
| 214 |
image_file = None
|
| 215 |
ant_file = None
|
| 216 |
-
# new_row_flg = False
|
| 217 |
|
| 218 |
# セッション情報取得
|
| 219 |
system_prompt = state["system_prompt"]
|
|
@@ -223,8 +222,6 @@ def bot(state, history, file_id):
|
|
| 223 |
last_msg_id = state["last_msg_id"]
|
| 224 |
code_mode = state["code_mode"]
|
| 225 |
|
| 226 |
-
print("system_prompt")
|
| 227 |
-
|
| 228 |
if file_id is None or file_id == "":
|
| 229 |
|
| 230 |
# ファイルがない場合
|
|
@@ -271,22 +268,19 @@ def bot(state, history, file_id):
|
|
| 271 |
order="asc"
|
| 272 |
)
|
| 273 |
|
| 274 |
-
print(last_msg_id)
|
| 275 |
-
# print(messages.data)
|
| 276 |
-
|
| 277 |
msg_log = client.beta.threads.messages.list(
|
| 278 |
thread_id=thread_id,
|
| 279 |
# after=last_msg_id,
|
| 280 |
order="asc"
|
| 281 |
)
|
| 282 |
|
|
|
|
|
|
|
| 283 |
print(msg_log)
|
| 284 |
|
| 285 |
# messageを取り出す
|
| 286 |
for msg in messages:
|
| 287 |
|
| 288 |
-
# msg_id = msg.id
|
| 289 |
-
|
| 290 |
if msg.role == "assistant":
|
| 291 |
|
| 292 |
for content in msg.content:
|
|
@@ -354,8 +348,6 @@ def bot(state, history, file_id):
|
|
| 354 |
# 参照ファイルがある旨のメッセージを追加
|
| 355 |
res_text = res_text + "\n\n" + ANT_MSG
|
| 356 |
|
| 357 |
-
print(res_text)
|
| 358 |
-
|
| 359 |
if res_text != "":
|
| 360 |
|
| 361 |
# Chat画面更新
|
|
@@ -370,9 +362,10 @@ def bot(state, history, file_id):
|
|
| 370 |
# 最終メッセージID更新
|
| 371 |
last_msg_id = msg.id
|
| 372 |
|
| 373 |
-
|
|
|
|
| 374 |
|
| 375 |
-
|
| 376 |
state["last_msg_id"] = last_msg_id
|
| 377 |
|
| 378 |
# 完了なら終了
|
|
@@ -410,23 +403,25 @@ def bot(state, history, file_id):
|
|
| 410 |
|
| 411 |
# エラーとして終了
|
| 412 |
err_msg = "※メッセージ取得に失敗しました。"
|
| 413 |
-
|
|
|
|
| 414 |
|
| 415 |
elif i == MAX_TRIAL:
|
| 416 |
|
| 417 |
# エラーとして終了
|
| 418 |
err_msg = "※メッセージ取得の際にタイムアウトしました。"
|
| 419 |
-
|
|
|
|
| 420 |
|
| 421 |
else:
|
| 422 |
if i > 3:
|
| 423 |
|
| 424 |
# 作業中とわかるようにする
|
| 425 |
-
# history = history + [[None, "………"]]
|
| 426 |
yield gr.Chatbot(label=run.status + " (Request:" + str(i) + ")" ,value=history), image_file, ant_file, err_msg
|
| 427 |
|
| 428 |
|
| 429 |
def get_code(run_steps):
|
|
|
|
| 430 |
|
| 431 |
input_code = []
|
| 432 |
|
|
@@ -434,6 +429,7 @@ def get_code(run_steps):
|
|
| 434 |
|
| 435 |
if isinstance(data.step_details, ToolCallsStepDetails):
|
| 436 |
|
|
|
|
| 437 |
for tool_call in data.step_details.tool_calls:
|
| 438 |
|
| 439 |
input_code.append(tool_call.code_interpreter.input)
|
|
@@ -443,6 +439,7 @@ def get_code(run_steps):
|
|
| 443 |
|
| 444 |
def file_download(client, file_id, folder, ext):
|
| 445 |
""" OpenAIからファイルをダウンロードしてパスを返す """
|
|
|
|
| 446 |
api_response = client.files.with_raw_response.retrieve_content(file_id)
|
| 447 |
|
| 448 |
if api_response.status_code == 200:
|
|
@@ -463,24 +460,43 @@ def file_download(client, file_id, folder, ext):
|
|
| 463 |
def finally_proc():
|
| 464 |
""" 最終処理用関数 """
|
| 465 |
|
| 466 |
-
|
|
|
|
|
|
|
|
|
|
| 467 |
new_file_id = gr.Textbox(value="")
|
| 468 |
|
| 469 |
-
return
|
| 470 |
|
| 471 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 472 |
with gr.Blocks() as demo:
|
| 473 |
|
| 474 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 475 |
|
| 476 |
# セッションの宣言
|
| 477 |
state = gr.State({
|
| 478 |
"system_prompt": SYS_PROMPT_DEFAULT,
|
| 479 |
-
"openai_key" :
|
| 480 |
"code_mode" : False,
|
| 481 |
"client" : None,
|
| 482 |
-
"assistant_id" :
|
| 483 |
-
"thread_id" :
|
| 484 |
"last_msg_id" : ""
|
| 485 |
})
|
| 486 |
|
|
@@ -488,7 +504,7 @@ with gr.Blocks() as demo:
|
|
| 488 |
|
| 489 |
# 各コンポーネント定義
|
| 490 |
chatbot = gr.Chatbot(label="チャット画面")
|
| 491 |
-
text_msg = gr.Textbox(label="テキスト")
|
| 492 |
with gr.Row():
|
| 493 |
up_file = gr.File(label="ファイルアップロード", type="filepath",interactive = True)
|
| 494 |
result_image = gr.Image(label="出力画像", type="filepath", interactive = False)
|
|
@@ -496,7 +512,8 @@ with gr.Blocks() as demo:
|
|
| 496 |
with gr.Row():
|
| 497 |
btn = gr.Button(value="送信")
|
| 498 |
# btn_download = gr.Button(value="画像のダウンロード") # 保留中
|
| 499 |
-
btn_clear = gr.ClearButton(value="リセット", components=[chatbot, text_msg, up_file,
|
|
|
|
| 500 |
sys_msg = gr.Textbox(label="システムメッセージ", interactive = False)
|
| 501 |
result_file = gr.File(label="出力ファイル", type="filepath",interactive = False)
|
| 502 |
|
|
@@ -504,30 +521,37 @@ with gr.Blocks() as demo:
|
|
| 504 |
file_id = gr.Textbox(visible=False)
|
| 505 |
|
| 506 |
# 送信ボタンクリック時の処理
|
| 507 |
-
bc = btn.click(init, [state, text_msg, up_file], [state,
|
| 508 |
raise_exception, sys_msg, None).success(
|
| 509 |
-
add_history, [chatbot, text_msg, file_id], [chatbot, text_msg, sys_msg], queue=False).success(
|
| 510 |
bot, [state, chatbot, file_id],[chatbot, result_image, result_file, sys_msg]).then(
|
| 511 |
-
finally_proc, None, [up_file, file_id], queue=False
|
| 512 |
)
|
| 513 |
|
| 514 |
-
#
|
| 515 |
-
|
| 516 |
|
| 517 |
# テキスト入力Enter時の処理
|
| 518 |
# txt_msg = text_msg.submit(respond, inputs=[text_msg, image, chatbot], outputs=[text_msg, image, chatbot])
|
| 519 |
|
| 520 |
with gr.Tab("設定") as set:
|
| 521 |
-
openai_key = gr.Textbox(label="OpenAI API Key")
|
| 522 |
# language = gr.Dropdown(choices=["Japanese", "English"], value = "Japanese", label="Language", interactive = True)
|
| 523 |
system_prompt = gr.Textbox(value = SYS_PROMPT_DEFAULT,lines = 5, label="Custom instructions", interactive = True)
|
| 524 |
-
# Enter不使用
|
| 525 |
code_output = gr.Dropdown(label="コード出力", choices=["OFF", "ON"], value = "OFF", interactive = True)
|
| 526 |
|
| 527 |
# 設定タブからChatタブに戻った時の処理
|
| 528 |
chat.select(set_state, [openai_key, system_prompt, code_output, state], state)
|
| 529 |
|
| 530 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 531 |
|
|
|
|
|
|
|
| 532 |
demo.launch(debug=True)
|
| 533 |
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""gradio_chat_codeinter4.ipynb
|
| 3 |
+
|
| 4 |
+
Automatically generated by Colaboratory.
|
| 5 |
+
|
| 6 |
+
Original file is located at
|
| 7 |
+
https://colab.research.google.com/drive/1wcp7vIMxSn44xLuI49FtY9kUYGvnS8yv
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
!pip install gradio
|
| 11 |
+
!pip install openai
|
| 12 |
+
|
| 13 |
import os
|
| 14 |
+
|
| 15 |
+
os.environ["TEST_OPENAI_KEY"] = "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"
|
| 16 |
+
os.environ["ASSIST_ID"] = "asst_KHpzJRBEgONhDf6cIpxr1Avt"
|
| 17 |
+
os.environ["MAX_TRIAL"] = "50"
|
| 18 |
+
os.environ["INTER_SEC"] = "3"
|
| 19 |
+
|
| 20 |
+
import os
|
| 21 |
+
import time
|
| 22 |
import datetime
|
| 23 |
+
import gradio as gr
|
| 24 |
from openai import OpenAI
|
| 25 |
+
from openai.types.beta.threads.runs import ToolCallsStepDetails
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
# GPT用設定
|
| 28 |
SYS_PROMPT_DEFAULT = "あなたは優秀なアシスタントです。質問をされた場合は、質問に答えるコードを作成して実行します。回答は日本語でお願いします。"
|
| 29 |
DUMMY = "********************"
|
| 30 |
+
# file_format = {".txt", ".csv", ".pdf"}
|
| 31 |
+
file_format = {".txt", ".csv"}
|
| 32 |
|
| 33 |
# 各種出力フォルダ
|
| 34 |
+
IMG_FOLDER = "images"
|
| 35 |
+
ANT_FOLDER = "annotations"
|
| 36 |
|
| 37 |
# 各種メッセージ
|
| 38 |
+
PLACEHOLDER = "これは東京都の年別人口データです、折れ線グラフでデータの可視化をお願いします… など"
|
| 39 |
+
IMG_MSG = "(画像ファイルを追加しました。リセットボタンの上に表示されています。)"
|
| 40 |
ANT_MSG = "(下部の[出力ファイル]にファイルを追加しました。)"
|
| 41 |
|
| 42 |
# 各種設定値
|
| 43 |
+
MAX_TRIAL = int(os.environ["MAX_TRIAL"]) # メッセージ取得最大試行数
|
| 44 |
+
INTER_SEC = int(os.environ["INTER_SEC"]) # 試行間隔(秒)
|
| 45 |
|
| 46 |
# サンプル用情報
|
| 47 |
+
examples = ["sample_data/東京都年別人口.csv", "sample_data/世界の人口2023年.csv", "sample_data/練馬区年齢別人口.csv", "sample_data/桃太郎あらすじ.txt"]
|
| 48 |
+
|
| 49 |
example_toid = {"東京都年別人口.csv" : "file-GOEk4X4WpU5gBJAuHCMtiJrn"
|
| 50 |
+
,"世界の人口2023年.csv" : "file-t0GurmfZixyDKZw2y14yfgbN"
|
| 51 |
, "練馬区年齢別人口.csv" : "file-YAFPMMqG3Zl5DRx5hTLjCfFa"
|
| 52 |
, "桃太郎あらすじ.txt" : "file-oDjAzL3G4ktwAUEkcGDCQMuQ"}
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
# コード出力用
|
| 55 |
code_mode = {'ON': True, 'OFF': False}
|
| 56 |
|
| 57 |
+
|
| 58 |
+
# 各関数
|
| 59 |
def set_state(openai_key, sys_prompt, code_output, state):
|
| 60 |
""" 設定タブの情報をセッションに保存する関数 """
|
| 61 |
|
|
|
|
| 70 |
""" 入力チェックを行う関数
|
| 71 |
※ここで例外を起こすと入力できなくなるので次の関数でエラーにする """
|
| 72 |
|
| 73 |
+
print(state)
|
| 74 |
+
|
| 75 |
err_msg = ""
|
| 76 |
file_id = None
|
| 77 |
|
|
|
|
| 85 |
# テキスト未入力
|
| 86 |
err_msg = "テキストを入力して下さい。"
|
| 87 |
|
| 88 |
+
return state, file_id, err_msg
|
| 89 |
|
| 90 |
elif file:
|
| 91 |
|
|
|
|
| 97 |
# ファイル形式チェック
|
| 98 |
err_msg = "指定した形式のファイルをアップしてください。(注意事項タブに記載)"
|
| 99 |
|
| 100 |
+
return state, file_id, err_msg
|
| 101 |
+
|
| 102 |
|
| 103 |
if state["client"] is None:
|
| 104 |
|
| 105 |
# 初回起動時は初期処理をする
|
| 106 |
os.environ["OPENAI_API_KEY"] = os.environ["TEST_OPENAI_KEY"] # テスト時
|
|
|
|
| 107 |
# os.environ["OPENAI_API_KEY"] = state["openai_key"]
|
| 108 |
|
| 109 |
+
# クライアント新規作成
|
| 110 |
client = OpenAI()
|
| 111 |
|
| 112 |
# client作成後は消す
|
| 113 |
os.environ["OPENAI_API_KEY"] = ""
|
| 114 |
|
| 115 |
+
# セッションにセット
|
| 116 |
+
state["client"] = client
|
| 117 |
+
|
| 118 |
+
else:
|
| 119 |
+
|
| 120 |
+
# 既存のクライアントをセット
|
| 121 |
+
client = state["client"]
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
if state["thread_id"] == "":
|
| 125 |
+
|
| 126 |
+
# スレッド作成
|
| 127 |
+
thread = client.beta.threads.create()
|
| 128 |
+
|
| 129 |
+
state["thread_id"] = thread.id
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
if state["assistant_id"] == "":
|
| 133 |
+
|
| 134 |
# アシスタント作成
|
| 135 |
# assistant = client.beta.assistants.create(
|
| 136 |
# name="codeinter_test",
|
|
|
|
| 139 |
# model="gpt-3.5-turbo-1106",
|
| 140 |
# tools=[{"type": "code_interpreter"}]
|
| 141 |
# )
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
# state["assistant_id"] = assistant.id
|
| 143 |
+
|
| 144 |
state["assistant_id"] = os.environ["ASSIST_ID"] # テスト中アシスタントは固定
|
| 145 |
+
|
| 146 |
|
| 147 |
if file:
|
| 148 |
|
|
|
|
| 151 |
|
| 152 |
if example_toid.get(basename):
|
| 153 |
|
| 154 |
+
# サンプルの場合は用意したIDをセット
|
| 155 |
+
file_id = example_toid.get(basename)
|
| 156 |
|
| 157 |
else:
|
| 158 |
|
| 159 |
+
# ファイルのアップ
|
| 160 |
+
file_response = client.files.create(
|
| 161 |
+
purpose="assistants",
|
| 162 |
+
file=open(file,"rb"),
|
| 163 |
+
)
|
|
|
|
|
|
|
| 164 |
|
| 165 |
+
if file_response.status != "processed":
|
|
|
|
| 166 |
|
| 167 |
+
# 失敗時
|
| 168 |
+
err_msg = "ファイルのアップロードに失敗しました"
|
|
|
|
| 169 |
|
| 170 |
+
else:
|
| 171 |
+
# ファイルのIDをセット
|
| 172 |
+
file_id = file_response.id
|
| 173 |
|
| 174 |
+
print(file_id)
|
|
|
|
| 175 |
|
| 176 |
+
return state, file_id, err_msg
|
| 177 |
|
|
|
|
| 178 |
|
| 179 |
def raise_exception(err_msg):
|
| 180 |
""" エラーの場合例外を起こす関数 """
|
|
|
|
| 188 |
def add_history(history, text, file_id):
|
| 189 |
""" Chat履歴"history"に追加を行う関数 """
|
| 190 |
|
|
|
|
|
|
|
|
|
|
| 191 |
err_msg = ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
|
| 193 |
if file_id is None or file_id == "":
|
| 194 |
|
| 195 |
+
# テキストだけの場合そのまま追加
|
| 196 |
+
history = history + [(text, None)]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
|
| 198 |
elif file_id is not None:
|
| 199 |
|
| 200 |
+
# ファイルがあればファイルIDとテキストを追加
|
| 201 |
+
history = history + [("file:" + file_id, DUMMY)]
|
| 202 |
+
history = history + [(text, None)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
|
| 204 |
+
# テキスト・ファイルを初期化し利用不可に
|
| 205 |
+
update_text = gr.update(value="", placeholder = "",interactive=False)
|
| 206 |
+
update_file = gr.update(value=None, interactive=False)
|
| 207 |
|
| 208 |
+
return history, update_text, update_file, err_msg
|
|
|
|
|
|
|
|
|
|
| 209 |
|
| 210 |
|
| 211 |
def bot(state, history, file_id):
|
|
|
|
| 213 |
err_msg = ""
|
| 214 |
image_file = None
|
| 215 |
ant_file = None
|
|
|
|
| 216 |
|
| 217 |
# セッション情報取得
|
| 218 |
system_prompt = state["system_prompt"]
|
|
|
|
| 222 |
last_msg_id = state["last_msg_id"]
|
| 223 |
code_mode = state["code_mode"]
|
| 224 |
|
|
|
|
|
|
|
| 225 |
if file_id is None or file_id == "":
|
| 226 |
|
| 227 |
# ファイルがない場合
|
|
|
|
| 268 |
order="asc"
|
| 269 |
)
|
| 270 |
|
|
|
|
|
|
|
|
|
|
| 271 |
msg_log = client.beta.threads.messages.list(
|
| 272 |
thread_id=thread_id,
|
| 273 |
# after=last_msg_id,
|
| 274 |
order="asc"
|
| 275 |
)
|
| 276 |
|
| 277 |
+
# デバッグ用
|
| 278 |
+
print(run.status)
|
| 279 |
print(msg_log)
|
| 280 |
|
| 281 |
# messageを取り出す
|
| 282 |
for msg in messages:
|
| 283 |
|
|
|
|
|
|
|
| 284 |
if msg.role == "assistant":
|
| 285 |
|
| 286 |
for content in msg.content:
|
|
|
|
| 348 |
# 参照ファイルがある旨のメッセージを追加
|
| 349 |
res_text = res_text + "\n\n" + ANT_MSG
|
| 350 |
|
|
|
|
|
|
|
| 351 |
if res_text != "":
|
| 352 |
|
| 353 |
# Chat画面更新
|
|
|
|
| 362 |
# 最終メッセージID更新
|
| 363 |
last_msg_id = msg.id
|
| 364 |
|
| 365 |
+
# Chatbotを返す(labelとhistoryを更新)
|
| 366 |
+
yield gr.Chatbot(label=run.status ,value=history), image_file, ant_file, err_msg
|
| 367 |
|
| 368 |
+
# メッセージIDを保存
|
| 369 |
state["last_msg_id"] = last_msg_id
|
| 370 |
|
| 371 |
# 完了なら終了
|
|
|
|
| 403 |
|
| 404 |
# エラーとして終了
|
| 405 |
err_msg = "※メッセージ取得に失敗しました。"
|
| 406 |
+
yield gr.Chatbot(label=run.status ,value=history), image_file, ant_file, err_msg
|
| 407 |
+
break
|
| 408 |
|
| 409 |
elif i == MAX_TRIAL:
|
| 410 |
|
| 411 |
# エラーとして終了
|
| 412 |
err_msg = "※メッセージ取得の際にタイムアウトしました。"
|
| 413 |
+
yield gr.Chatbot(label=run.status ,value=history), image_file, ant_file, err_msg
|
| 414 |
+
break
|
| 415 |
|
| 416 |
else:
|
| 417 |
if i > 3:
|
| 418 |
|
| 419 |
# 作業中とわかるようにする
|
|
|
|
| 420 |
yield gr.Chatbot(label=run.status + " (Request:" + str(i) + ")" ,value=history), image_file, ant_file, err_msg
|
| 421 |
|
| 422 |
|
| 423 |
def get_code(run_steps):
|
| 424 |
+
""" 生成過程のコードを全てを返す """
|
| 425 |
|
| 426 |
input_code = []
|
| 427 |
|
|
|
|
| 429 |
|
| 430 |
if isinstance(data.step_details, ToolCallsStepDetails):
|
| 431 |
|
| 432 |
+
# コードが存在するときだけ取得
|
| 433 |
for tool_call in data.step_details.tool_calls:
|
| 434 |
|
| 435 |
input_code.append(tool_call.code_interpreter.input)
|
|
|
|
| 439 |
|
| 440 |
def file_download(client, file_id, folder, ext):
|
| 441 |
""" OpenAIからファイルをダウンロードしてパスを返す """
|
| 442 |
+
|
| 443 |
api_response = client.files.with_raw_response.retrieve_content(file_id)
|
| 444 |
|
| 445 |
if api_response.status_code == 200:
|
|
|
|
| 460 |
def finally_proc():
|
| 461 |
""" 最終処理用関数 """
|
| 462 |
|
| 463 |
+
# テキスト・ファイルを使えるように
|
| 464 |
+
interactive = gr.update(interactive = True)
|
| 465 |
+
|
| 466 |
+
# ファイルIDはリセット
|
| 467 |
new_file_id = gr.Textbox(value="")
|
| 468 |
|
| 469 |
+
return interactive, interactive, new_file_id
|
| 470 |
|
| 471 |
|
| 472 |
+
def clear_click(state):
|
| 473 |
+
""" クリアボタンクリック時 """
|
| 474 |
+
|
| 475 |
+
# セッションの一部をリセット()
|
| 476 |
+
# state["assistant_id"] = ""
|
| 477 |
+
state["thread_id"] = ""
|
| 478 |
+
state["last_msg_id"] = ""
|
| 479 |
+
|
| 480 |
+
return state
|
| 481 |
+
|
| 482 |
+
# 画面構成
|
| 483 |
with gr.Blocks() as demo:
|
| 484 |
|
| 485 |
+
title = "<h2>GPT Code Interpreter対応チャット</h2>"
|
| 486 |
+
message = "<h3>・テスト中でAPIKEY無しで動きます ※機密ファイルはアップしないでください<br>"
|
| 487 |
+
message += "・こういうときにエラーになるなどフィードバックあればお待ちしています。<br>"
|
| 488 |
+
message += "※動いているかわかりづらいですが、左上の""in_progress(Request:XX)が止まっていなければ回答の生成中となります。""<br></h3>"
|
| 489 |
+
|
| 490 |
+
gr.Markdown(title + message)
|
| 491 |
|
| 492 |
# セッションの宣言
|
| 493 |
state = gr.State({
|
| 494 |
"system_prompt": SYS_PROMPT_DEFAULT,
|
| 495 |
+
"openai_key" : "",
|
| 496 |
"code_mode" : False,
|
| 497 |
"client" : None,
|
| 498 |
+
"assistant_id" : "",
|
| 499 |
+
"thread_id" : "",
|
| 500 |
"last_msg_id" : ""
|
| 501 |
})
|
| 502 |
|
|
|
|
| 504 |
|
| 505 |
# 各コンポーネント定義
|
| 506 |
chatbot = gr.Chatbot(label="チャット画面")
|
| 507 |
+
text_msg = gr.Textbox(label="テキスト", placeholder = PLACEHOLDER)
|
| 508 |
with gr.Row():
|
| 509 |
up_file = gr.File(label="ファイルアップロード", type="filepath",interactive = True)
|
| 510 |
result_image = gr.Image(label="出力画像", type="filepath", interactive = False)
|
|
|
|
| 512 |
with gr.Row():
|
| 513 |
btn = gr.Button(value="送信")
|
| 514 |
# btn_download = gr.Button(value="画像のダウンロード") # 保留中
|
| 515 |
+
# btn_clear = gr.ClearButton(value="リセット", components=[chatbot, text_msg, up_file, file_id, result_image, sys_msg, result_file])
|
| 516 |
+
btn_clear = gr.ClearButton(value="リセット", components=[chatbot, text_msg, up_file])
|
| 517 |
sys_msg = gr.Textbox(label="システムメッセージ", interactive = False)
|
| 518 |
result_file = gr.File(label="出力ファイル", type="filepath",interactive = False)
|
| 519 |
|
|
|
|
| 521 |
file_id = gr.Textbox(visible=False)
|
| 522 |
|
| 523 |
# 送信ボタンクリック時の処理
|
| 524 |
+
bc = btn.click(init, [state, text_msg, up_file], [state, file_id, sys_msg], queue=False).success(
|
| 525 |
raise_exception, sys_msg, None).success(
|
| 526 |
+
add_history, [chatbot, text_msg, file_id], [chatbot, text_msg, up_file, sys_msg], queue=False).success(
|
| 527 |
bot, [state, chatbot, file_id],[chatbot, result_image, result_file, sys_msg]).then(
|
| 528 |
+
finally_proc, None, [text_msg, up_file, file_id], queue=False
|
| 529 |
)
|
| 530 |
|
| 531 |
+
# クリア時でもセッションの設定(OpenAIKeyなどは残す)
|
| 532 |
+
btn_clear.click(clear_click, state, state)
|
| 533 |
|
| 534 |
# テキスト入力Enter時の処理
|
| 535 |
# txt_msg = text_msg.submit(respond, inputs=[text_msg, image, chatbot], outputs=[text_msg, image, chatbot])
|
| 536 |
|
| 537 |
with gr.Tab("設定") as set:
|
| 538 |
+
openai_key = gr.Textbox(label="OpenAI API Key", visible=False) # テスト中は表示せず
|
| 539 |
# language = gr.Dropdown(choices=["Japanese", "English"], value = "Japanese", label="Language", interactive = True)
|
| 540 |
system_prompt = gr.Textbox(value = SYS_PROMPT_DEFAULT,lines = 5, label="Custom instructions", interactive = True)
|
|
|
|
| 541 |
code_output = gr.Dropdown(label="コード出力", choices=["OFF", "ON"], value = "OFF", interactive = True)
|
| 542 |
|
| 543 |
# 設定タブからChatタブに戻った時の処理
|
| 544 |
chat.select(set_state, [openai_key, system_prompt, code_output, state], state)
|
| 545 |
|
| 546 |
+
with gr.Tab("注意事項") as notes:
|
| 547 |
+
caution = "現在Assistant APIはβ版でのリリースとなっています。<br>"
|
| 548 |
+
caution += "そのためか一部のファイルのアップロードが上手くいかないため、制限をかけています。<br>"
|
| 549 |
+
caution += "(現在アップできるファイル形式は.txtと.csvのみ)<br>"
|
| 550 |
+
caution += "本来はPDFなども利用できるはずなので、今後更新したいと思います。また日本語文字化けも調査中です。"
|
| 551 |
+
|
| 552 |
+
gr.Markdown("<h3>" + caution + "</h3>")
|
| 553 |
|
| 554 |
+
|
| 555 |
+
demo.queue()
|
| 556 |
demo.launch(debug=True)
|
| 557 |
|