Spaces:
Runtime error
Runtime error
Upload 2 files
Browse filesFiles changed (2)
- app.pyAdded+74
- requirements.txtAdded+3
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374import timeimport gradio as grimport openaiimport osimport requestsimport json
# 從 Hugging Face secrets 中讀取 OpenAI API 金鑰api_key = os.getenv('OPENAI_API_KEY')if not api_key: raise ValueError("請設置 'OPENAI_API_KEY' 環境變數")
# OpenAI API keyopenai_api_key = api_key
# 將 Gradio 的歷史紀錄轉換為 OpenAI 格式def transform_history(history): new_history = [] for chat in history: new_history.append({"role": "user", "content": chat[0]}) new_history.append({"role": "assistant", "content": chat[1]}) return new_history
# 回應生成函數,使用 requests 來呼叫 OpenAI APIdef response(message, history): global conversation_history
# 將 Gradio 的歷史紀錄轉換為 OpenAI 的格式 conversation_history = transform_history(history)
url = "https://api.openai.com/v1/chat/completions" headers = { "Content-Type": "application/json", "Authorization": f"Bearer {openai_api_key}" }
# 設置初始的 prompt_instruction prompt_instruction = """ 你是廖老師的專業小助教,名字叫做 '小確' ,要以專業、熱情、善解人意且非常有禮貌,親切的的口氣,與用戶互動並解答問題: """ prompt_to_gpt = prompt_instruction + message
# 新增至 conversation_history conversation_history.append({"role": "system", "content": prompt_to_gpt})
# 設置請求的數據 data = { "model": "gpt-4o", # 確認使用的模型是 gpt-4 或 gpt-3.5-turbo "messages": conversation_history, "max_tokens": 200 # 控制生成的最大令牌數 }
# 發送請求到 OpenAI API response = requests.post(url, headers=headers, data=json.dumps(data))
# 處理回應 response_json = response.json()
# 提取模型的回應並加入歷史紀錄 if 'choices' in response_json and len(response_json['choices']) > 0: model_response = response_json['choices'][0]['message']['content'] conversation_history.append({"role": "assistant", "content": model_response})
# 逐字回傳生成的文字,實現打字機效果 for i in range(len(model_response)): time.sleep(0.05) # 每個字符間隔 0.05 秒 yield model_response[: i+1] else: yield "Error: No response from the model."
# 建立 Gradio 聊天界面gr.ChatInterface(response, title='OpenAI Chat', textbox=gr.Textbox(placeholder="Question to OpenAI")).launch(share=True)123#requirements.txtgradioopenaiapp.pyAdded+74
requirements.txtAdded+3