Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files901 unmodified lines902903904905906907908909910911912913914915916917918919920474 unmodified lines13951396139713981399140014011402140314041405140614078 unmodified lines14161417141814191420142114221423142414251426142714281429143014311432143314 unmodified lines144814491450145114521453145434 unmodified lines148914901491149214931494149548 unmodified lines15441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915 unmodified lines15951596159715981599160016011602160316041605160616071608160916101611161216131614161522 unmodified lines1638163916401641164216431644164541 unmodified lines1687168816891690169116926 unmodified lines169917001701170217031704170517061372 unmodified lines3079308030813082308330843085308630873088407 unmodified lines349634973498349935003501350235033504901 unmodified linesif self.provider_keys.get("groq") or self.provider_key_pools.get("groq"):vision_candidates.extend(["groq/meta-llama/llama-4-scout-17b-16e-instruct","groq/meta-llama/llama-4-maverick-17b-128e-instruct",])if self.provider_keys.get("gemini"):vision_candidates.extend(self.gemini_flash_modelsor ["gemini/gemini-3-flash-preview","gemini/gemini-2.5-flash","gemini/gemini-flash-latest",])if self.provider_keys.get("openrouter"):vision_candidates.extend(["openrouter/google/gemma-4-26b-a4b-it:free",474 unmodified lines) -> str:"""Transcribes or analyzes a local audio file (.mp3, .wav, .m4a, .ogg) using available audio/multimodal models.Args:audio_path: Local path to the downloaded audio file.question: Specific transcription or analysis instruction for the audio."""try:if not os.path.isfile(audio_path):return f"Audio file not found: '{audio_path}'"ext = os.path.splitext(audio_path)[1].lower().lstrip(".")mime_map = {"mp3": "audio/mp3","wav": "audio/wav",8 unmodified linesif not groq_key:breaktry:with open(audio_path, "rb") as audio_f:groq_resp = requests.post("https://api.groq.com/openai/v1/audio/transcriptions",headers={"Authorization": f"Bearer {groq_key}"},files={"file": (os.path.basename(audio_path), audio_f, mime_type)},data={"model": "whisper-large-v3-turbo", "response_format": "text"},timeout=_tool_timeout(20.0),)if groq_resp.status_code == 200:transcript = groq_resp.text.strip()if transcript:return transcriptbreakerr_body = groq_resp.text.lower()if groq_resp.status_code in (401, 402, 403):14 unmodified linesraisebreakwith open(audio_path, "rb") as f:b64_data = base64.b64encode(f.read()).decode("utf-8")audio_models = []34 unmodified lines],"generationConfig": {"maxOutputTokens": 2048,"thinkingConfig": {"thinkingBudget": 0},},},timeout=_tool_timeout(30.0),48 unmodified linesself._transcribe_audio = transcribe_audiocandidate_models = []priority_openrouter_models = ["openrouter/meta-llama/llama-3.3-70b-instruct:free","openrouter/qwen/qwen3-next-80b-a3b-instruct:free","openrouter/google/gemma-3-27b-it:free","openrouter/mistralai/mistral-small-3.1-24b-instruct:free","openrouter/openrouter/free",]if self.provider_keys.get("openrouter"):live_free_models = set()try:or_resp = requests.get("https://openrouter.ai/api/v1/models",timeout=10,headers={"User-Agent": "HF-Agents-Course-Bot/1.0"},)if or_resp.status_code == 200:for item in or_resp.json().get("data", []):m_id = str(item.get("id", "")).strip()if m_id == "openrouter/free" or m_id.endswith(":free"):live_free_models.add(f"openrouter/{m_id}")except Exception as or_exc:print(f"Warning: could not list OpenRouter models: {or_exc}")if live_free_models:curated_live = [m for m in priority_openrouter_models if m in live_free_models]candidate_models.extend(curated_live[:2] or ["openrouter/openrouter/free"])else:candidate_models.extend(priority_openrouter_models[:2])if self.provider_keys.get("gemini"):available_api_models = set()for g_key in self.provider_key_pools.get("gemini") or [gemini_key]:15 unmodified linesif not any(bad in low_idfor bad in ("tts","image","imagen","veo","embedding","aqa","audio","robotics","computer-use","deep-research","omni","exp","thinking","gemma","flash-lite",)):available_api_models.add(full_id)22 unmodified linescandidate_models.extend(self.gemini_flash_models)print(f"[GEMINI MODELS] {self.gemini_flash_models}", flush=True)if self.provider_keys.get("groq"):# Wykluczono gpt-oss-* z CodeAgent (zawsze wywołują natywne narzędzia i wywalają tool_choice=none)preferred_groq = ["groq/llama-3.3-70b-versatile","groq/moonshotai/kimi-k2-instruct",41 unmodified lineselse:candidate_models.extend(preferred_groq[:4])if self.provider_keys.get("huggingface"):candidate_models.extend(["huggingface/Qwen/Qwen2.5-72B-Instruct",6 unmodified lines"nvidia_nim/deepseek-ai/deepseek-v3.2","nvidia_nim/meta/llama-3.3-70b-instruct",])priority_rank = {name: idx for idx, name in enumerate(priority_openrouter_models)}def _model_priority(model_name: str) -> tuple[int, int, int, tuple[int, int], str]:provider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini"1372 unmodified linesprompt_lower = prompt.lower()if "chess" in prompt_lower or "algebraic notation" in prompt_lower:prompt += ("\n\nIMPORTANT for chess tasks: First call inspect_image (if an image is attached) to read the exact ""board orientation (files a-h, ranks 1-8) and every piece square. Verify legality and tactical outcome, ""then output ONLY the single move in Standard Algebraic Notation (SAN, e.g. Rd5, Nf6+, O-O) ""without move numbers (no '1.' or '1...') or commentary.")if ("|*|" in prompt407 unmodified linesraw_cached = c_ans.strip()if (not raw_cachedor raw_cached.startswith("AGENT ERROR:")or "</code>" in raw_cached.lower()or "without access to" in raw_cached.lower()):continueclean_cached = agent._clean_exact_match_answer(raw_cached)901 unmodified lines902903904905906907908909910911912913914915916917918919920921474 unmodified lines1396139713981399140014011402140314041405140614071408140914101411141214131414141514168 unmodified lines14251426142714281429143014311432143314341435143614371438143914401441144214 unmodified lines145714581459146014611462146334 unmodified lines149814991500150115021503150448 unmodified lines1553155415551556155715581559156015 unmodified lines157615771578157915801581158215831584158522 unmodified lines1608160916101611161216131614161541 unmodified lines16571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216936 unmodified lines170017011702170317041705170617071372 unmodified lines308030813082308330843085308630873088308930903091407 unmodified lines34993500350135023503350435053506350735083509901 unmodified linesif self.provider_keys.get("groq") or self.provider_key_pools.get("groq"):vision_candidates.extend(["groq/meta-llama/llama-4-maverick-17b-128e-instruct","groq/meta-llama/llama-4-scout-17b-16e-instruct",])if self.provider_keys.get("gemini"):vision_candidates.extend(self.gemini_flash_modelsor ["gemini/gemini-2.5-flash","gemini/gemini-3-flash-preview","gemini/gemini-flash-latest",])if self.provider_keys.get("openrouter"):vision_candidates.extend(["openrouter/google/gemma-4-26b-a4b-it:free",474 unmodified lines) -> str:"""Transcribes or analyzes a local audio file (.mp3, .wav, .m4a, .ogg) using available audio/multimodal models.Args:audio_path: Local path or filename of the downloaded audio file.question: Specific transcription or analysis instruction for the audio."""try:resolved_path = audio_pathif not os.path.isfile(resolved_path):target_name = os.path.basename(audio_path)for root, _, files in os.walk("."):if target_name in files:resolved_path = os.path.join(root, target_name)breakif not os.path.isfile(resolved_path):return f"Audio file not found: '{audio_path}'"ext = os.path.splitext(resolved_path)[1].lower().lstrip(".")mime_map = {"mp3": "audio/mp3","wav": "audio/wav",8 unmodified linesif not groq_key:breaktry:with open(resolved_path, "rb") as audio_f:groq_resp = requests.post("https://api.groq.com/openai/v1/audio/transcriptions",headers={"Authorization": f"Bearer {groq_key}"},files={"file": (os.path.basename(resolved_path), audio_f, mime_type)},data={"model": "whisper-large-v3-turbo", "response_format": "text"},timeout=_tool_timeout(20.0),)if groq_resp.status_code == 200:transcript = groq_resp.text.strip()if transcript:return f"[Whisper Transcript]: {transcript}"breakerr_body = groq_resp.text.lower()if groq_resp.status_code in (401, 402, 403):14 unmodified linesraisebreakwith open(resolved_path, "rb") as f:b64_data = base64.b64encode(f.read()).decode("utf-8")audio_models = []34 unmodified lines],"generationConfig": {"maxOutputTokens": 2048,"thinkingConfig": {"thinkingBudget": 512},},},timeout=_tool_timeout(30.0),48 unmodified linesself._transcribe_audio = transcribe_audiocandidate_models = []# 1. Gemini Flash jako główny model (najlepsza stabilność z CodeAgent)if self.provider_keys.get("gemini"):available_api_models = set()for g_key in self.provider_key_pools.get("gemini") or [gemini_key]:15 unmodified linesif not any(bad in low_idfor bad in ("tts", "image", "imagen", "veo", "embedding","aqa", "audio", "robotics", "computer-use","deep-research", "omni", "exp", "thinking","gemma", "flash-lite",)):available_api_models.add(full_id)22 unmodified linescandidate_models.extend(self.gemini_flash_models)print(f"[GEMINI MODELS] {self.gemini_flash_models}", flush=True)# 2. Groq jako szybki fallbackif self.provider_keys.get("groq"):preferred_groq = ["groq/llama-3.3-70b-versatile","groq/moonshotai/kimi-k2-instruct",41 unmodified lineselse:candidate_models.extend(preferred_groq[:4])# 3. OpenRouter darmowe modele dopiero po Gemini i Groqpriority_openrouter_models = ["openrouter/meta-llama/llama-3.3-70b-instruct:free","openrouter/qwen/qwen3-next-80b-a3b-instruct:free","openrouter/google/gemma-3-27b-it:free","openrouter/mistralai/mistral-small-3.1-24b-instruct:free","openrouter/openrouter/free",]if self.provider_keys.get("openrouter"):live_free_models = set()try:or_resp = requests.get("https://openrouter.ai/api/v1/models",timeout=10,headers={"User-Agent": "HF-Agents-Course-Bot/1.0"},)if or_resp.status_code == 200:for item in or_resp.json().get("data", []):m_id = str(item.get("id", "")).strip()if m_id == "openrouter/free" or m_id.endswith(":free"):live_free_models.add(f"openrouter/{m_id}")except Exception as or_exc:print(f"Warning: could not list OpenRouter models: {or_exc}")if live_free_models:curated_live = [m for m in priority_openrouter_models if m in live_free_models]candidate_models.extend(curated_live[:2] or ["openrouter/openrouter/free"])else:candidate_models.extend(priority_openrouter_models[:2])if self.provider_keys.get("huggingface"):candidate_models.extend(["huggingface/Qwen/Qwen2.5-72B-Instruct",6 unmodified lines"nvidia_nim/deepseek-ai/deepseek-v3.2","nvidia_nim/meta/llama-3.3-70b-instruct",])priority_rank = {name: idx for idx, name in enumerate(candidate_models)}def _model_priority(model_name: str) -> tuple[int, int, int, tuple[int, int], str]:provider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini"1372 unmodified linesprompt_lower = prompt.lower()if "chess" in prompt_lower or "algebraic notation" in prompt_lower:prompt += ("\n\nIMPORTANT for chess tasks:\n""1. Call inspect_image(image_path=..., question='List the exact board orientation (which side is at the bottom, rank 1 or rank 8), ""every single piece with its exact square (e.g., White King on g1, Black Queen on d8), whose turn it is, and the exact FEN string.').\n""2. In Python, verify the board state from that exact piece list, check all legal moves for Black (especially checks, forks, pins, and mate threats), ""and pick the winning move.\n""3. Output ONLY the single move in Standard Algebraic Notation (SAN, e.g. Rd5, Nf6+, Qxd4) with NO move numbers ('1...' or '1.') and NO commentary.")if ("|*|" in prompt407 unmodified linesraw_cached = c_ans.strip()if (not raw_cachedor len(raw_cached) > 120or raw_cached.startswith("AGENT ERROR:")or "</code>" in raw_cached.lower()or "without access to" in raw_cached.lower()or "gaia_questions.json" in raw_cached.lower()):continueclean_cached = agent._clean_exact_match_answer(raw_cached)
app.py+66-61