Update app.py
Browse files
app.py
CHANGED
@@ -8,44 +8,43 @@ openai.api_key = os.getenv("OPENAI_API_KEY")
|
|
8 |
def chat_with_openai(user_input, history):
|
9 |
if history is None:
|
10 |
history = []
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
messages.append({"role": "user", "content": human})
|
15 |
-
if assistant:
|
16 |
-
messages.append({"role": "assistant", "content": assistant})
|
17 |
-
messages.append({"role": "user", "content": user_input})
|
18 |
|
19 |
# OpenAI APIへのリクエスト
|
20 |
response = openai.ChatCompletion.create(
|
21 |
model="o1-preview",
|
22 |
-
messages=
|
23 |
)
|
|
|
24 |
assistant_message = response['choices'][0]['message']['content']
|
25 |
|
26 |
-
#
|
27 |
-
history.append(
|
28 |
|
29 |
-
|
|
|
|
|
|
|
|
|
|
|
30 |
|
31 |
with gr.Blocks() as demo:
|
32 |
chatbot = gr.Chatbot()
|
|
|
33 |
state = gr.State([])
|
34 |
|
35 |
with gr.Row():
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
def on_submit(user_input, chat_history):
|
47 |
-
updated_history, updated_state = chat_with_openai(user_input, chat_history)
|
48 |
-
return updated_history, updated_state, ""
|
49 |
|
50 |
txt.submit(on_submit, [txt, state], [chatbot, state, txt])
|
51 |
btn.click(on_submit, [txt, state], [chatbot, state, txt])
|
|
|
8 |
def chat_with_openai(user_input, history):
|
9 |
if history is None:
|
10 |
history = []
|
11 |
+
|
12 |
+
# ユーザーの入力を履歴に追加
|
13 |
+
history.append({"role": "user", "content": user_input})
|
|
|
|
|
|
|
|
|
14 |
|
15 |
# OpenAI APIへのリクエスト
|
16 |
response = openai.ChatCompletion.create(
|
17 |
model="o1-preview",
|
18 |
+
messages=history
|
19 |
)
|
20 |
+
|
21 |
assistant_message = response['choices'][0]['message']['content']
|
22 |
|
23 |
+
# アシスタントの応答を履歴に追加
|
24 |
+
history.append({"role": "assistant", "content": assistant_message})
|
25 |
|
26 |
+
# チャットボット用にメッセージを整形
|
27 |
+
messages = [
|
28 |
+
(history[i]["content"], history[i+1]["content"]) for i in range(0, len(history)-1, 2)
|
29 |
+
]
|
30 |
+
|
31 |
+
return messages, history
|
32 |
|
33 |
with gr.Blocks() as demo:
|
34 |
chatbot = gr.Chatbot()
|
35 |
+
|
36 |
state = gr.State([])
|
37 |
|
38 |
with gr.Row():
|
39 |
+
txt = gr.Textbox(
|
40 |
+
show_label=False,
|
41 |
+
placeholder="メッセージを入力してください..."
|
42 |
+
)
|
43 |
+
btn = gr.Button("送信")
|
44 |
+
|
45 |
+
def on_submit(user_input, history):
|
46 |
+
messages, updated_history = chat_with_openai(user_input, history)
|
47 |
+
return messages, updated_history, ""
|
|
|
|
|
|
|
|
|
48 |
|
49 |
txt.submit(on_submit, [txt, state], [chatbot, state, txt])
|
50 |
btn.click(on_submit, [txt, state], [chatbot, state, txt])
|