import os import openai import gradio as gr from gradio import ChatInterface # 設定 OpenAI API key - 從環境變數獲取 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 請求 response = openai.ChatCompletion.create( model='gpt-4', messages=messages, temperature=1.0, stream=True ) partial_message = "" for chunk in response: if 'choices' in chunk and len(chunk['choices']) > 0: if 'delta' in chunk['choices'][0] and 'content' in chunk['choices'][0]['delta']: 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()