youngtsai commited on
Commit
b90df65
1 Parent(s): bc52e2a

def extract_json_from_response(response_text):

Browse files
Files changed (1) hide show
  1. app.py +23 -18
app.py CHANGED
@@ -3,40 +3,45 @@ from gtts import gTTS
3
  import json
4
  import os
5
  import openai
 
 
6
 
7
  PASSWORD = os.environ['PASSWORD']
8
  OPEN_AI_KEY = os.environ['OPEN_AI_KEY']
9
 
10
 
 
 
 
 
 
 
 
 
 
11
 
12
  def create_chat_dialogue(rounds, role1, role2, theme="購物"):
13
  openai.api_key = os.environ["OPEN_AI_KEY"]
14
 
15
  # 初始化對話
16
- messages = [
17
- {"role": "system", "content": f"您將進行一場以{theme}為主題的對話。{role1}和{role2}將是參與者。"}
18
- ]
19
 
20
- # 呼叫API直到達到所需的對話輪數
21
- while len(messages) - 1 < 2 * rounds:
22
- response = openai.ChatCompletion.create(
23
- model="gpt-3.5-turbo",
24
- messages=messages
25
- )
26
 
27
- # 加入新消息
28
- messages.extend(response['choices'][0]['messages'])
29
-
30
- # 只保留role1和role2的消息
31
- dialogue = [{"role": message["role"], "content": message["content"]} for message in messages if message["role"] in [role1, role2]]
32
 
 
 
33
  return dialogue
34
 
35
 
36
-
37
-
38
-
39
-
40
  def generate_dialogue(rounds, method, role1, role2):
41
  if method == "auto":
42
  dialogue = create_chat_dialogue(rounds, role1, role2)
 
3
  import json
4
  import os
5
  import openai
6
+ import re
7
+
8
 
9
  PASSWORD = os.environ['PASSWORD']
10
  OPEN_AI_KEY = os.environ['OPEN_AI_KEY']
11
 
12
 
13
+ def extract_json_from_response(response_text):
14
+ # 使用正則表達式匹配 JSON 格式的對話
15
+ match = re.search(r'\[\s*\{.*?\}\s*\]', response_text, re.DOTALL)
16
+ if match:
17
+ json_str = match.group(0)
18
+ return json.loads(json_str)
19
+ else:
20
+ raise ValueError("JSON dialogue not found in the response.")
21
+
22
 
23
  def create_chat_dialogue(rounds, role1, role2, theme="購物"):
24
  openai.api_key = os.environ["OPEN_AI_KEY"]
25
 
26
  # 初始化對話
27
+ prompt = f"您將進行一場以{theme}為主題的對話。{role1}和{role2}將是參與者。請依次交談{rounds}輪。以json格式儲存對話。並回傳對話JSON文件。格式為:[{{role:\"A\", content: \".....\"}}, {{role:\"B\", content: \".....\"}}]"
 
 
28
 
29
+ response = openai.Completion.create(
30
+ model="gpt-3.5-turbo",
31
+ prompt=prompt,
32
+ max_tokens=500 # 設定一個較大的值,可根據需要調整
33
+ )
 
34
 
35
+ print(response)
36
+
37
+ response_text = response.choices[0].text.strip()
38
+ dialogue = extract_json_from_response(response_text)
 
39
 
40
+ print(dialogue)
41
+ # 這裡直接返回JSON格式的對話,但考慮到這可能只是一個字符串,您可能還需要將它解析為一個Python對象
42
  return dialogue
43
 
44
 
 
 
 
 
45
  def generate_dialogue(rounds, method, role1, role2):
46
  if method == "auto":
47
  dialogue = create_chat_dialogue(rounds, role1, role2)