EduTechTeam commited on
Commit
fa4b132
·
verified ·
1 Parent(s): 157bb8f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -0
app.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from openai import OpenAI
3
+ import gradio as gr
4
+ from gradio import ChatInterface
5
+
6
+ # 設定 OpenAI API key - 從環境變數獲取
7
+ client = OpenAI(api_key=os.environ['OPENAI_API_KEY'])
8
+
9
+ def predict(inputs, chatbot):
10
+ messages = []
11
+
12
+ # 建立對話歷史
13
+ for conv in chatbot:
14
+ messages.append({"role": "user", "content": conv[0]})
15
+ messages.append({"role": "assistant", "content": conv[1]})
16
+
17
+ # 加入新的用戶輸入
18
+ messages.append({"role": "user", "content": inputs})
19
+
20
+ try:
21
+ # 建立 ChatCompletion 請求
22
+ stream = client.chat.completions.create(
23
+ model='gpt-4', # 確保您有權限使用 gpt-4
24
+ messages=messages,
25
+ temperature=1.0,
26
+ stream=True,
27
+ )
28
+
29
+ partial_message = ""
30
+ for chunk in stream:
31
+ if chunk.choices[0].delta.content is not None:
32
+ content = chunk.choices[0].delta.content
33
+ partial_message += content
34
+ yield partial_message
35
+
36
+ except Exception as e:
37
+ yield f"發生錯誤: {str(e)}"
38
+
39
+
40
+ # 創建和啟動聊天界面
41
+ chat_interface = gr.ChatInterface(
42
+ predict,
43
+ chatbot=gr.Chatbot(),
44
+ title="AI 聊天助手",
45
+ description="請輸入您的問題",
46
+ )
47
+
48
+ if __name__ == "__main__":
49
+ chat_interface.launch()