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