import time import gradio as gr # 確認已正確導入 gradio import os import requests import json # 從 Hugging Face secrets 中讀取 OpenAI API 金鑰 api_key = os.getenv('OPENAI_API_KEY') if not api_key: raise ValueError("請設置 'OPENAI_API_KEY' 環境變數") # OpenAI API key openai_api_key = api_key # 檢查是否為與調酒相關的問題 def is_related_to_bars(message): keywords = [ '調酒', '酒吧', '酒類', 'cocktail', 'bartending', 'bar', 'alcohol', 'drink', # 調酒相關的關鍵字 '風味', '口味', '酸', '甜', '苦', '辣', 'flavor', 'taste', 'sour', 'sweet', 'bitter', 'spicy' # 風味和口味相關的關鍵字 ] return any(keyword in message.lower() for keyword in keywords) # 回應生成函數,使用 requests 來呼叫 OpenAI API def response(message, history): global conversation_history # 檢查問題是否與調酒相關 if not is_related_to_bars(message): print(f"問題與調酒無關: {message}") return "抱歉,我只能回答與調酒、酒吧、酒類相關的問題。" # In Traditional Chinese # 呼叫 OpenAI API 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 # 設置請求的數據 data = { "model": "gpt-4o", # 使用 GPT-4 或 gpt-3.5-turbo "messages": [{"role": "system", "content": prompt_to_gpt}], "max_tokens": 200 # 控制生成的最大令牌數 } try: response = requests.post(url, headers=headers, data=json.dumps(data)) response.raise_for_status() # 檢查是否有錯誤 response_json = response.json() # Debugging: 打印 API 回應 print("API Response:", response_json) if 'choices' in response_json and len(response_json['choices']) > 0: model_response = response_json['choices'][0]['message']['content'] return model_response else: return "Error: No response from the model." except Exception as e: print(f"API Error: {e}") return f"API Error: {e}" # 初始訊息 def initial_message(): return "我是你的專業調酒助理 小李子,我只能回答關於調酒的問題。" # In Traditional Chinese # 建立 Gradio 聊天界面,並展示初始訊息 def create_demo(): with gr.Blocks() as demo: chatbot = gr.ChatInterface(response, title='Lee Bartender Assistant', textbox=gr.Textbox(placeholder="Ask me about cocktails, bars, or drinks")) gr.Markdown(initial_message()) # 初始訊息 return demo demo = create_demo() demo.launch(share=True)