Spaces:
Sleeping
Sleeping
| import os | |
| from openai import OpenAI | |
| import gradio as gr | |
| from gradio import ChatInterface | |
| # 設定 OpenAI API key - 從環境變數獲取 | |
| client = OpenAI(api_key=os.environ['OPENAI_API_KEY']) | |
| def predict(inputs, chatbot): | |
| messages = [] | |
| # 建立對話歷史 | |
| for conv in chatbot: | |
| messages.append({"role": "user", "content": conv[0]}) | |
| messages.append({"role": "assistant", "content": conv[1]}) | |
| # 加入新的用戶輸入 | |
| messages.append({"role": "user", "content": inputs}) | |
| try: | |
| # 建立 ChatCompletion 請求 | |
| stream = client.chat.completions.create( | |
| model='gpt-4', # 確保您有權限使用 gpt-4 | |
| messages=messages, | |
| temperature=1.0, | |
| stream=True, | |
| ) | |
| partial_message = "" | |
| for chunk in stream: | |
| if chunk.choices[0].delta.content is not None: | |
| content = chunk.choices[0].delta.content | |
| partial_message += content | |
| yield partial_message | |
| except Exception as e: | |
| yield f"發生錯誤: {str(e)}" | |
| # 創建和啟動聊天界面 | |
| chat_interface = gr.ChatInterface( | |
| predict, | |
| chatbot=gr.Chatbot(), | |
| title="AI 聊天助手", | |
| description="請輸入您的問題", | |
| ) | |
| if __name__ == "__main__": | |
| chat_interface.launch() |