Marathon23 commited on
Commit
e706192
·
verified ·
1 Parent(s): f20e6a2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +11 -41
app.py CHANGED
@@ -1,6 +1,5 @@
1
  import time
2
  import gradio as gr # 確認已正確導入 gradio
3
- import openai
4
  import os
5
  import requests
6
  import json
@@ -13,14 +12,6 @@ if not api_key:
13
  # OpenAI API key
14
  openai_api_key = api_key
15
 
16
- # 將 Gradio 的歷史紀錄轉換為 OpenAI 格式
17
- def transform_history(history):
18
- new_history = []
19
- for chat in history:
20
- new_history.append({"role": "user", "content": chat[0]})
21
- new_history.append({"role": "assistant", "content": chat[1]})
22
- return new_history
23
-
24
  # 檢查是否為與調酒相關的問題
25
  def is_related_to_bars(message):
26
  keywords = [
@@ -38,9 +29,7 @@ def response(message, history):
38
  print(f"問題與調酒無關: {message}")
39
  return "抱歉,我只能回答與調酒、酒吧、酒類相關的問題。" # In Traditional Chinese
40
 
41
- # 如果問題相關,將歷史紀錄轉換為 OpenAI 格式
42
- conversation_history = transform_history(history)
43
-
44
  url = "https://api.openai.com/v1/chat/completions"
45
  headers = {
46
  "Content-Type": "application/json",
@@ -49,52 +38,33 @@ def response(message, history):
49
 
50
  # 設置初始的 prompt_instruction
51
  prompt_instruction = """
52
- 你是酒吧的專業助理,名字叫做 '小李子',要以專業、冷淡但是非常有禮貌的口氣,與用戶互動並解答問題:
53
  """
54
  prompt_to_gpt = prompt_instruction + message
55
 
56
- # 新增至 conversation_history
57
- conversation_history.append({"role": "system", "content": prompt_to_gpt})
58
-
59
  # 設置請求的數據
60
  data = {
61
- "model": "gpt-4", # 確認使用的模型是 gpt-4 或 gpt-3.5-turbo
62
- "messages": conversation_history,
63
  "max_tokens": 200 # 控制生成的最大令牌數
64
  }
65
 
66
- # 發送請求到 OpenAI API
67
  try:
68
  response = requests.post(url, headers=headers, data=json.dumps(data))
69
- response.raise_for_status() # 檢查 API 是否返回錯誤
70
  response_json = response.json()
71
 
72
- # Debugging: Print the response to ensure we can see what comes back from the API
73
  print("API Response:", response_json)
74
 
75
- # 提取模型的回應並加入歷史紀錄
76
  if 'choices' in response_json and len(response_json['choices']) > 0:
77
  model_response = response_json['choices'][0]['message']['content']
78
- conversation_history.append({"role": "assistant", "content": model_response})
79
-
80
- # 逐字回傳生成的文字,實現打字機效果
81
- for i in range(len(model_response)):
82
- time.sleep(0.05) # 每個字符間隔 0.05 秒
83
- yield model_response[: i+1]
84
  else:
85
- yield "Error: No response from the model."
86
- except requests.exceptions.HTTPError as errh:
87
- print(f"HTTP Error: {errh}")
88
- yield f"HTTP Error: {errh}"
89
- except requests.exceptions.ConnectionError as errc:
90
- print(f"Error Connecting: {errc}")
91
- yield f"Error Connecting: {errc}"
92
- except requests.exceptions.Timeout as errt:
93
- print(f"Timeout Error: {errt}")
94
- yield f"Timeout Error: {errt}"
95
- except requests.exceptions.RequestException as err:
96
- print(f"Request Exception: {err}")
97
- yield f"Request Exception: {err}"
98
 
99
  # 初始訊息
100
  def initial_message():
 
1
  import time
2
  import gradio as gr # 確認已正確導入 gradio
 
3
  import os
4
  import requests
5
  import json
 
12
  # OpenAI API key
13
  openai_api_key = api_key
14
 
 
 
 
 
 
 
 
 
15
  # 檢查是否為與調酒相關的問題
16
  def is_related_to_bars(message):
17
  keywords = [
 
29
  print(f"問題與調酒無關: {message}")
30
  return "抱歉,我只能回答與調酒、酒吧、酒類相關的問題。" # In Traditional Chinese
31
 
32
+ # 呼叫 OpenAI API
 
 
33
  url = "https://api.openai.com/v1/chat/completions"
34
  headers = {
35
  "Content-Type": "application/json",
 
38
 
39
  # 設置初始的 prompt_instruction
40
  prompt_instruction = """
41
+ 你是李宗諺的專業小助教,名字叫做 '小李子',要以專業、冷淡但是非常有禮貌的口氣,與用戶互動並解答問題:
42
  """
43
  prompt_to_gpt = prompt_instruction + message
44
 
 
 
 
45
  # 設置請求的數據
46
  data = {
47
+ "model": "gpt-4o", # 使用 GPT-4 或 gpt-3.5-turbo
48
+ "messages": [{"role": "system", "content": prompt_to_gpt}],
49
  "max_tokens": 200 # 控制生成的最大令牌數
50
  }
51
 
 
52
  try:
53
  response = requests.post(url, headers=headers, data=json.dumps(data))
54
+ response.raise_for_status() # 檢查是否有錯誤
55
  response_json = response.json()
56
 
57
+ # Debugging: 打印 API 回應
58
  print("API Response:", response_json)
59
 
 
60
  if 'choices' in response_json and len(response_json['choices']) > 0:
61
  model_response = response_json['choices'][0]['message']['content']
62
+ return model_response
 
 
 
 
 
63
  else:
64
+ return "Error: No response from the model."
65
+ except Exception as e:
66
+ print(f"API Error: {e}")
67
+ return f"API Error: {e}"
 
 
 
 
 
 
 
 
 
68
 
69
  # 初始訊息
70
  def initial_message():