ochyai commited on
Commit
23a7cbb
·
verified ·
1 Parent(s): 1338dd1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -24
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
- # OpenAI APIに送信するメッセージの構築
12
- messages = []
13
- for human, assistant in history:
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=messages
23
  )
 
24
  assistant_message = response['choices'][0]['message']['content']
25
 
26
- # 履歴に新しいメッセージを追加
27
- history.append((user_input, assistant_message))
28
 
29
- return history, history
 
 
 
 
 
30
 
31
  with gr.Blocks() as demo:
32
  chatbot = gr.Chatbot()
 
33
  state = gr.State([])
34
 
35
  with gr.Row():
36
- with gr.Column(scale=8):
37
- txt = gr.Textbox(
38
- show_label=False,
39
- placeholder="メッセージを入力してください...",
40
- lines=1,
41
- container=False
42
- )
43
- with gr.Column(scale=2, min_width=0):
44
- btn = gr.Button("送信")
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])