Spaces:
Runtime error
Runtime error
| #app.py | |
| import time | |
| import gradio as gr | |
| import google.generativeai as genai | |
| import os | |
| # 從 Hugging Face secrets 中讀取 API 金鑰(如果需要) | |
| api_key = os.getenv('GOOGLE_API_KEY') | |
| if not api_key: | |
| raise ValueError("請設置 'GOOGLE_API_KEY' 環境變數") | |
| # 設定 API 金鑰 | |
| genai.configure(api_key=api_key) | |
| # 初始化模型 | |
| try: | |
| model = genai.GenerativeModel('gemini-1.5-pro') | |
| chat = model.start_chat(history=[]) | |
| print("模型載入成功。") | |
| except Exception as e: | |
| raise ValueError(f"無法載入模型:{e}") | |
| # 將 Gradio 的歷史紀錄轉換為 Gemini 格式 | |
| def transform_history(history): | |
| new_history = [] | |
| for chat in history: | |
| new_history.append({"parts": [{"text": chat[0]}], "role": "user"}) | |
| new_history.append({"parts": [{"text": chat[1]}], "role": "model"}) | |
| return new_history | |
| # 回應生成函數 | |
| def response(message, history): | |
| global chat | |
| # 將 Gradio 的歷史紀錄轉換為 Gemini 的格式 | |
| chat.history = transform_history(history) | |
| # 自訂 Prompt:限縮為與半導體智慧製造相關的回答 | |
| prompt = "你是一位半導體智慧製造。你負責協助回答先進封裝半導體智慧製造相關,請只回答與半導體相關的問題,回答語氣需要溫柔且有耐心,且所有回答一律使用繁體中文。" | |
| # 合併Prompt與使用者訊息 | |
| final_message = prompt + "\n" + message | |
| # 發送訊息到 Gemini API | |
| response = chat.send_message(final_message) | |
| response.resolve() | |
| # 逐字回傳生成的文字,實現打字機效果 | |
| for i in range(len(response.text)): | |
| time.sleep(0.05) # 每個字符間隔 0.05 秒 | |
| yield response.text[: i+1] | |
| # 建立 Gradio 聊天界面 | |
| gr.ChatInterface(response, | |
| title='智慧小助手', | |
| textbox=gr.Textbox(placeholder="請輸入與半導體相關的問題")).launch(share=True) | |