Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files- app.py +36 -22
- requirements.txt +2 -1
app.py
CHANGED
|
@@ -32,29 +32,43 @@ def response(message, history):
|
|
| 32 |
headers = {
|
| 33 |
"Content-Type": "application/json",
|
| 34 |
"Authorization": f"Bearer {openai_api_key}"
|
| 35 |
-
|
| 36 |
-
new_history = []
|
| 37 |
-
for chat in history:
|
| 38 |
-
new_history.append({"parts": [{"text": chat[0]}], "role": "user"})
|
| 39 |
-
new_history.append({"parts": [{"text": chat[1]}], "role": "model"})
|
| 40 |
-
return new_history
|
| 41 |
|
| 42 |
-
#
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
#
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
# 建立 Gradio 聊天界面
|
| 58 |
gr.ChatInterface(response,
|
| 59 |
-
title='
|
| 60 |
-
textbox=gr.Textbox(placeholder="Question to
|
|
|
|
| 32 |
headers = {
|
| 33 |
"Content-Type": "application/json",
|
| 34 |
"Authorization": f"Bearer {openai_api_key}"
|
| 35 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
+
# 設置初始的 prompt_instruction
|
| 38 |
+
prompt_instruction = """
|
| 39 |
+
你是廖老師的專業小助教,名字叫做 '小確' ,要以專業、熱情、善解人意且非常有禮貌,親切的的口氣,與用戶互動並解答問題:
|
| 40 |
+
"""
|
| 41 |
+
prompt_to_gpt = prompt_instruction + message
|
| 42 |
+
|
| 43 |
+
# 新增至 conversation_history
|
| 44 |
+
conversation_history.append({"role": "system", "content": prompt_to_gpt})
|
| 45 |
+
|
| 46 |
+
# 設置請求的數據
|
| 47 |
+
data = {
|
| 48 |
+
"model": "gpt-4o", # 確認使用的模型是 gpt-4 或 gpt-3.5-turbo
|
| 49 |
+
"messages": conversation_history,
|
| 50 |
+
"max_tokens": 200 # 控制生成的最大令牌數
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
# 發送請求到 OpenAI API
|
| 54 |
+
response = requests.post(url, headers=headers, data=json.dumps(data))
|
| 55 |
+
|
| 56 |
+
# 處理回應
|
| 57 |
+
response_json = response.json()
|
| 58 |
+
|
| 59 |
+
# 提取模型的回應並加入歷史紀錄
|
| 60 |
+
if 'choices' in response_json and len(response_json['choices']) > 0:
|
| 61 |
+
model_response = response_json['choices'][0]['message']['content']
|
| 62 |
+
conversation_history.append({"role": "assistant", "content": model_response})
|
| 63 |
+
|
| 64 |
+
# 逐字回傳生成的文字,實現打字機效果
|
| 65 |
+
for i in range(len(model_response)):
|
| 66 |
+
time.sleep(0.05) # 每個字符間隔 0.05 秒
|
| 67 |
+
yield model_response[: i+1]
|
| 68 |
+
else:
|
| 69 |
+
yield "Error: No response from the model."
|
| 70 |
|
| 71 |
# 建立 Gradio 聊天界面
|
| 72 |
gr.ChatInterface(response,
|
| 73 |
+
title='OpenAI Chat',
|
| 74 |
+
textbox=gr.Textbox(placeholder="Question to OpenAI")).launch(share=True)
|
requirements.txt
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
|
|
| 1 |
gradio
|
| 2 |
-
|
|
|
|
| 1 |
+
#requirements.txt
|
| 2 |
gradio
|
| 3 |
+
openai
|