Spaces:
Sleeping
Sleeping
chen commited on
Update ai_service.py
Browse files112345 unmodified lines10111213141513141518162021222317181925202122232431253326273637282940414230444531464732333451523536373811 unmodified lines505152707153545556575877597960616263846465668867686970717273747576777879809394959697989981828384# ai_service.py (Implements robust API key validation and rotation)# ai_service.py (Instructs AI to execute tool calls without asking for confirmation)import jsonimport osimport random5 unmodified lines# 從設定檔匯入金鑰和 URLfrom config import MCP_SERVER_URL
# --- 1. [核心修改] API 金鑰健康檢查與輪替機制 ---
# 從環境變數讀取您設定的兩組金鑰# --- 1. API 金鑰健康檢查與輪替機制 ---key1 = os.getenv("GEMINI_API_KEY")key2 = os.getenv("GEMINI_API_KEY2")
all_keys = []if key1 and "YOUR_GEMINI_API_KEY" not in key1: all_keys.append(key1)if key2 and "YOUR_GEMINI_API_KEY" not in key2: all_keys.append(key2)if key1 and "YOUR_GEMINI_API_KEY" not in key1: all_keys.append(key1)if key2 and "YOUR_GEMINI_API_KEY" not in key2: all_keys.append(key2)
# 建立一個存放 "健康" (有效) 金鑰的列表healthy_keys = []if all_keys: print(f"--- Found {len(all_keys)} Gemini API Key(s). Starting validation... ---") for key in all_keys: try: # 嘗試用每個 key 來設定並初始化一個模型,以驗證其有效性 genai.configure(api_key=key) # 嘗試發送一個非常簡單的測試請求 test_model = genai.GenerativeModel('gemini-1.5-flash') test_model.generate_content("test", request_options={'timeout': 10}) # 如果成功,將此 key 加入健康列表 healthy_keys.append(key) print(f"--- Key ending in ...{key[-4:]} is VALID and added to the pool. ---") except google_exceptions.PermissionDenied as e: print(f"--- Key ending in ...{key[-4:]} is INVALID (Permission Denied). Skipping. ---") print(f" Error details: {e}") except Exception as e: # 捕捉其他可能的錯誤,例如超時、額度用盡等 print(f"--- Key ending in ...{key[-4:]} failed validation. Skipping. ---") print(f"--- Key ending in ...{key[-4:]} failed validation. Skipping. Error: {e} ---") print(f" Error details: {e}")
if not healthy_keys: print("--- CRITICAL: No valid Gemini API Keys found. AI Service will be disabled. ---")
# --- 2. 工具函式 (Tool Functions) --- (此區塊維持不變)
# --- 2. 工具函式 (Tool Functions) ---def call_mcp_earthquake_search(start_date: str, end_date: str, min_magnitude: float = 4.0, max_magnitude: float = 9.0) -> str: try: client = Client(src=MCP_SERVER_URL)11 unmodified lines return result[0] if isinstance(result, tuple) and len(result) > 0 else str(result) except Exception as e: return f"工具執行失敗,錯誤訊息: {e}"
# --- 3. 向 Gemini 定義工具 (Tool Declarations) --- (此區塊維持不變)# ... (此處省略與上一版相同的工具定義程式碼)# --- 3. 向 Gemini 定義工具 (Tool Declarations) ---earthquake_search_tool_declaration = { "name": "call_earthquake_search_tool", "description": "從台灣中央氣象署的資料庫中搜尋地震事件。", "parameters": { "type": "OBJECT", "properties": { "start_date": { "type": "STRING", "description": "搜尋的開始日期 (格式 'YYYY-MM-DD')。模型應根據使用者問題中的相對時間(例如:昨天、上個月、去年)或絕對時間(例如:2024年)來主動推斷此日期。" }, "end_date": { "type": "STRING", "description": "搜尋的結束日期 (格式 'YYYY-MM-DD')。模型應根據使用者問題中的相對時間或絕對時間來主動推斷此日期。" }, }, "required": ["start_date", "end_date"] } }pws_search_tool_declaration = { "name": "call_mcp_pws_search", "description": "查詢最新的 PWS (Public Weather Service) 公共天氣服務發布情形。", "parameters": { "type": "OBJECT", "properties": {} } }available_tools = { "call_earthquake_search_tool": call_mcp_earthquake_search, "call_mcp_pws_search": call_mcp_pws_search }
# --- 4. 主要的 AI 文字生成函式 ---
def generate_ai_text(user_prompt: str) -> str: # [核心修改] 每次呼叫時,都從健康的金鑰池中隨機選取 if not healthy_keys: return "🤖 AI (Gemini) 服務錯誤:沒有任何有效的 API 金鑰可供使用。" try: # 從健康池中隨機選擇一個 key selected_key = random.choice(healthy_keys) print(f"--- Handling request with key ending in: ...{selected_key[-4:]} ---") # 使用選定的 key 建立模型實例 genai.configure(api_key=selected_key) # [*** 核心修正 ***] # 在系統指令中,明確要求 AI 在推斷出參數後「不要提問,直接執行」 system_instruction = ( "You are a helpful AI assistant. You must answer in Traditional Chinese." "When a user's query can be answered by a tool, you MUST infer the parameters from the query and call the tool immediately without asking for confirmation. Do not ask the user to confirm the parameters you have inferred." "When the user asks for the 'largest' or 'strongest' earthquake, you MUST assume they mean by magnitude. You should then analyze the JSON data returned by the tool, " "find the single entry with the highest 'magnitude' value, and present that specific earthquake's details as the answer." ) model = genai.GenerativeModel( model_name="gemini-1.5-flash", tools=[earthquake_search_tool_declaration, pws_search_tool_declaration], system_instruction=( "You are a helpful AI assistant. You must answer in Traditional Chinese." "When the user asks for the 'largest' or 'strongest' earthquake, " "you MUST assume they mean by magnitude. You should then analyze the JSON data returned by the tool, " "find the single entry with the highest 'magnitude' value, and present that specific earthquake's details as the answer." "Do not simply show all the data; find the maximum and answer the question directly." ) system_instruction=system_instruction ) chat = model.start_chat()ai_service.py+18-36