Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,26 +1,37 @@
|
|
1 |
-
#app.py
|
2 |
import time
|
3 |
import gradio as gr
|
4 |
-
import
|
5 |
import os
|
|
|
|
|
6 |
|
7 |
-
# 從 Hugging Face secrets 中讀取 API
|
8 |
-
api_key = os.getenv('
|
9 |
if not api_key:
|
10 |
-
raise ValueError("請設置 '
|
11 |
|
12 |
-
#
|
13 |
-
|
14 |
|
15 |
-
#
|
16 |
-
|
17 |
-
|
18 |
-
chat
|
19 |
-
|
20 |
-
|
21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
|
23 |
-
|
|
|
|
|
|
|
24 |
def transform_history(history):
|
25 |
new_history = []
|
26 |
for chat in history:
|
|
|
|
|
1 |
import time
|
2 |
import gradio as gr
|
3 |
+
import openai
|
4 |
import os
|
5 |
+
import requests
|
6 |
+
import json
|
7 |
|
8 |
+
# 從 Hugging Face secrets 中讀取 OpenAI API 金鑰
|
9 |
+
api_key = os.getenv('OPENAI_API_KEY')
|
10 |
if not api_key:
|
11 |
+
raise ValueError("請設置 'OPENAI_API_KEY' 環境變數")
|
12 |
|
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 |
+
# 回應生成函數,使用 requests 來呼叫 OpenAI API
|
25 |
+
def response(message, history):
|
26 |
+
global conversation_history
|
27 |
+
|
28 |
+
# 將 Gradio 的歷史紀錄轉換為 OpenAI 的格式
|
29 |
+
conversation_history = transform_history(history)
|
30 |
|
31 |
+
url = "https://api.openai.com/v1/chat/completions"
|
32 |
+
headers = {
|
33 |
+
"Content-Type": "application/json",
|
34 |
+
"Authorization": f"Bearer {openai_api_key}"
|
35 |
def transform_history(history):
|
36 |
new_history = []
|
37 |
for chat in history:
|