Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files103 unmodified lines10410510610710810911011111269 unmodified lines1821831841851861871881891901911921931941952 unmodified lines198199200201202203204205206145 unmodified lines3523533543553563573583593603613623633643653663673683693703713723733743753762 unmodified lines37938038138238338438510 unmodified lines39639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847958 unmodified lines53853954054154254344 unmodified lines58858959059159259359459559659731 unmodified lines62963063163263363463525 unmodified lines66166266366466566666789 unmodified lines7577587597607617627637647657667674 unmodified lines772773774775776777778103 unmodified linescleaned = re.sub(r"\s+", " ", unescape(plain_text)).strip()if not cleaned:return "Empty text response."if len(cleaned) <= 6000:return cleanedreturn cleaned[:3000] + "\n...\n" + cleaned[-3000:]except Exception as e:return f"Error fetching URL '{url}': {str(e)}"69 unmodified lines@tooldef read_local_file(file_path: str) -> str:"""Reads text or spreadsheet content from a local file downloaded by download_task_file.Args:file_path: Local path to the downloaded file."""try:if not os.path.isfile(file_path):return f"File not found: '{file_path}'"ext = os.path.splitext(file_path)[1].lower()if ext in {".xlsx", ".xls"}:sheets = pd.read_excel(file_path, sheet_name=None)if not sheets:2 unmodified linesf"=== Sheet: {sheet_name} ===\n{df.to_csv(index=False)}"for sheet_name, df in sheets.items()]return "\n\n".join(parts)[:16000]with open(file_path, "r", encoding="utf-8", errors="replace") as f:return f.read()[:16000]except Exception as e:return f"Error reading file '{file_path}': {str(e)}"145 unmodified lineswith open(image_path, "rb") as f:b64_data = base64.b64encode(f.read()).decode("utf-8")response = litellm.completion(model=self.model_id,api_key=gemini_key,messages=[{"role": "user","content": [{"type": "text", "text": question},{"type": "image_url","image_url": {"url": f"data:{mime_type};base64,{b64_data}"},},],}],max_tokens=2048,timeout=30,)return (response.choices[0].message.content or "").strip()except Exception as e:return f"Error inspecting image '{image_path}': {str(e)}"2 unmodified linesaudio_path: str,question: str = "Transcribe all spoken words verbatim and answer any question about the audio.",) -> str:"""Transcribes or analyzes a local audio file (.mp3, .wav, .m4a, .ogg) using Gemini.Args:audio_path: Local path to the downloaded audio file.question: Specific transcription or analysis instruction for the audio.10 unmodified lines"flac": "audio/flac",}mime_type = mime_map.get(ext, "audio/mp3")with open(audio_path, "rb") as f:b64_data = base64.b64encode(f.read()).decode("utf-8")data_uri = f"data:{mime_type};base64,{b64_data}"try:response = litellm.completion(model=self.model_id,api_key=gemini_key,messages=[{"role": "user","content": [{"type": "text", "text": question},{"type": "image_url", "image_url": {"url": data_uri}},],}],max_tokens=2048,timeout=45,)except Exception:response = litellm.completion(model=self.model_id,api_key=gemini_key,messages=[{"role": "user","content": [{"type": "text", "text": question},{"type": "file", "file": {"file_data": data_uri}},],}],max_tokens=2048,timeout=45,)return (response.choices[0].message.content or "").strip()except Exception as e:return f"Error transcribing audio '{audio_path}': {str(e)}"preferred_models = ["gemini/gemini-3.8-flash","gemini/gemini-3.7-flash","gemini/gemini-3.6-flash","gemini/gemini-3.5-flash","gemini/gemini-3-flash-preview","gemini/gemini-3.1-flash-lite-preview","gemini/gemini-flash-latest",]available_api_models = set()try:models_resp = requests.get("https://generativelanguage.googleapis.com/v1beta/models",params={"key": gemini_key},timeout=15,)if models_resp.status_code == 200:for m in models_resp.json().get("models", []):if "generateContent" in m.get("supportedGenerationMethods", []):raw_name = m.get("name", "")if raw_name.startswith("models/"):available_api_models.add("gemini/" + raw_name[len("models/"):])except Exception as list_exc:print(f"Warning: could not list Gemini models via REST: {list_exc}")excluded_tokens = ("embedding","image","tts","lyria","nano-banana","customtools","omni","2.0","2.5",)candidate_models = []if self.provider_keys.get("openrouter"):58 unmodified linesforced_model = "gemini/" + forced_modelself.working_models = [forced_model] + [m for m in self.working_models if m != forced_model]if not self.working_models:raise RuntimeError("No models available for the configured API keys.")44 unmodified linesreturn msgdef _prepare_call_kwargs(self, kwargs: dict) -> dict:key = kwargs.get("api_key") or getattr(self, "_explicit_api_key", None)model_name = str(getattr(self, "model_id", "") or "")if key:kwargs["api_key"] = keyif model_name.startswith("openrouter/"):os.environ["OPENROUTER_API_KEY"] = keyelif model_name.startswith("groq/"):31 unmodified linesexact_match_rule = ("CRITICAL OUTPUT RULES FOR EXACT MATCH EVALUATION:\n""- Always write valid Python code inside ```py and ``` fences. NEVER put 'Thought:' or HTML tags like <code> inside the Python block.\n""- Never call built-in open(); use read_local_file(file_path) for text/spreadsheet files, ""inspect_image(image_path, question) for images, and transcribe_audio(audio_path, question) for audio files (.mp3, .wav).\n""- If web_search returns no results, use search_wikipedia(query) or fetch_url_text(url).\n""- Return ONLY the concise exact answer value itself "25 unmodified lines"string",],instructions=exact_match_rule,max_steps=10,verbosity_level=0,)print("CodeAgent initialized with LiteLLMModel.")89 unmodified linesreturn f"AGENT ERROR: {exc}"if len(models_to_try) > 1:try:idx = models_to_try.index(self.model_id)next_model = models_to_try[(idx + 1) % len(models_to_try)]except ValueError:next_model = models_to_try[0]self.model_id = next_modelself.agent.model = model_cls(model_id=self.model_id,4 unmodified linestimeout=25,)print(f"Switched model to {self.model_id}.")wait_sec = 3 if any(m in err_lower for m in fast_retry_markers) else 25print(f"Sleeping {wait_sec}s before next attempt...")time.sleep(wait_sec)103 unmodified lines10410510610710810911011111269 unmodified lines1821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702 unmodified lines273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308145 unmodified lines4544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055062 unmodified lines50951051151251351451510 unmodified lines52652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659758 unmodified lines65665765865966066166266366466566644 unmodified lines71171271371471571671771871972031 unmodified lines75275375475575675775825 unmodified lines78478578678778878979089 unmodified lines8808818828838848858868878888898908918928938948958968978988994 unmodified lines904905906907908909910103 unmodified linescleaned = re.sub(r"\s+", " ", unescape(plain_text)).strip()if not cleaned:return "Empty text response."if len(cleaned) <= 24000:return cleanedreturn cleaned[:12000] + "\n...\n" + cleaned[-12000:]except Exception as e:return f"Error fetching URL '{url}': {str(e)}"69 unmodified lines@tooldef read_local_file(file_path: str) -> str:"""Reads text, PDF, ZIP archive, or spreadsheet content from a local file downloaded by download_task_file.Args:file_path: Local path to the downloaded file."""import zipfiletry:if not os.path.isfile(file_path):return f"File not found: '{file_path}'"ext = os.path.splitext(file_path)[1].lower()if ext == ".zip" or zipfile.is_zipfile(file_path):extract_dir = os.path.join(os.path.dirname(file_path),f"extracted_{os.path.basename(file_path)}",)os.makedirs(extract_dir, exist_ok=True)base_extract = os.path.realpath(extract_dir)sections = []with zipfile.ZipFile(file_path, "r") as zf:members = [m for m in zf.namelist() if not m.endswith("/")]sections.append(f"=== ZIP Archive ({len(members)} files) ===\nFiles: {', '.join(members)}")for member in members:target_path = os.path.realpath(os.path.join(extract_dir, member))if not (target_path == base_extract or target_path.startswith(base_extract + os.sep)):sections.append(f"=== {member} ===\nSkipped unsafe path.")continueos.makedirs(os.path.dirname(target_path), exist_ok=True)with zf.open(member, "r") as src, open(target_path, "wb") as dst:dst.write(src.read())m_ext = os.path.splitext(member)[1].lower()try:if m_ext in {".xlsx", ".xls"}:sheets = pd.read_excel(target_path, sheet_name=None)sheet_parts = [f"-- Sheet {s_name} --\n{df.to_csv(index=False)}"for s_name, df in sheets.items()]sections.append(f"=== {member} (extracted to {target_path}) ===\n"+ "\n".join(sheet_parts))elif m_ext == ".pdf":try:from pypdf import PdfReaderreader = PdfReader(target_path)p_texts = [f"-- Page {i + 1} --\n{(p.extract_text() or '').strip()}"for i, p in enumerate(reader.pages)]sections.append(f"=== {member} (extracted to {target_path}) ===\n"+ "\n".join(p_texts))except Exception as p_exc:sections.append(f"=== {member} (extracted to {target_path}) ===\nPDF error: {p_exc}")elif m_ext in {".png", ".jpg", ".jpeg", ".webp", ".gif"}:sections.append(f"=== {member} (extracted to {target_path}) ===\n"f"Binary image file. Use inspect_image(image_path='{target_path}', question=...).")elif m_ext in {".mp3", ".wav", ".m4a", ".ogg", ".flac"}:sections.append(f"=== {member} (extracted to {target_path}) ===\n"f"Binary audio file. Use transcribe_audio(audio_path='{target_path}', question=...).")else:with open(target_path, "r", encoding="utf-8", errors="replace") as mf:sections.append(f"=== {member} (extracted to {target_path}) ===\n" + mf.read())except Exception as m_exc:sections.append(f"=== {member} (extracted to {target_path}) ===\nRead error: {m_exc}")joined_zip = "\n\n".join(sections)if len(joined_zip) <= 48000:return joined_zipreturn joined_zip[:24000] + "\n...\n" + joined_zip[-24000:]if ext in {".xlsx", ".xls"}:sheets = pd.read_excel(file_path, sheet_name=None)if not sheets:2 unmodified linesf"=== Sheet: {sheet_name} ===\n{df.to_csv(index=False)}"for sheet_name, df in sheets.items()]joined_xls = "\n\n".join(parts)if len(joined_xls) <= 48000:return joined_xlsreturn joined_xls[:24000] + "\n...\n" + joined_xls[-24000:]if ext == ".pdf":try:from pypdf import PdfReaderreader = PdfReader(file_path)pages_text = [f"=== Page {i + 1} ===\n{(page.extract_text() or '').strip()}"for i, page in enumerate(reader.pages)]joined = "\n\n".join(p for p in pages_text if p.strip())if not joined:return "Empty PDF text."if len(joined) <= 48000:return joinedreturn joined[:24000] + "\n...\n" + joined[-24000:]except Exception as pdf_exc:return f"Error reading PDF '{file_path}': {str(pdf_exc)}"if ext in {".png", ".jpg", ".jpeg", ".webp", ".gif"}:return f"Binary image file '{file_path}'. Use inspect_image(image_path='{file_path}', question=...)."if ext in {".mp3", ".wav", ".m4a", ".ogg", ".flac"}:return f"Binary audio file '{file_path}'. Use transcribe_audio(audio_path='{file_path}', question=...)."with open(file_path, "r", encoding="utf-8", errors="replace") as f:content = f.read()if len(content) <= 48000:return contentreturn content[:24000] + "\n...\n" + content[-24000:]except Exception as e:return f"Error reading file '{file_path}': {str(e)}"145 unmodified lineswith open(image_path, "rb") as f:b64_data = base64.b64encode(f.read()).decode("utf-8")vision_candidates = []if "gemma-3" in self.model_id.lower() or "gemini" in self.model_id.lower():vision_candidates.append(self.model_id)if self.provider_keys.get("openrouter"):vision_candidates.extend(["openrouter/google/gemma-3-27b-it:free","openrouter/meta-llama/llama-3.2-11b-vision-instruct:free",])if self.provider_keys.get("gemini"):vision_candidates.extend(["gemini/gemini-flash-latest","gemini/gemini-3.1-flash-lite",])if self.model_id not in vision_candidates:vision_candidates.append(self.model_id)last_err = Nonefor v_model in dict.fromkeys(vision_candidates):v_key = self._get_api_key(v_model)if not v_key:continuetry:response = litellm.completion(model=v_model,api_key=v_key,messages=[{"role": "user","content": [{"type": "text", "text": question},{"type": "image_url","image_url": {"url": f"data:{mime_type};base64,{b64_data}"},},],}],max_tokens=2048,timeout=30,)out = (response.choices[0].message.content or "").strip()if out:return outexcept Exception as exc:last_err = excraise RuntimeError(str(last_err) if last_err else "No vision model available.")except Exception as e:return f"Error inspecting image '{image_path}': {str(e)}"2 unmodified linesaudio_path: str,question: str = "Transcribe all spoken words verbatim and answer any question about the audio.",) -> 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.10 unmodified lines"flac": "audio/flac",}mime_type = mime_map.get(ext, "audio/mp3")if self.provider_keys.get("groq"):try:with open(audio_path, "rb") as audio_f:groq_resp = requests.post("https://api.groq.com/openai/v1/audio/transcriptions",headers={"Authorization": f"Bearer {self.provider_keys['groq']}"},files={"file": (os.path.basename(audio_path), audio_f, mime_type)},data={"model": "whisper-large-v3-turbo", "response_format": "text"},timeout=45,)groq_resp.raise_for_status()transcript = groq_resp.text.strip()if transcript:return transcriptexcept Exception:passwith open(audio_path, "rb") as f:b64_data = base64.b64encode(f.read()).decode("utf-8")data_uri = f"data:{mime_type};base64,{b64_data}"audio_models = []if self.provider_keys.get("gemini"):audio_models.extend(["gemini/gemini-flash-latest","gemini/gemini-3.1-flash-lite",])if "gemini/" in self.model_id and self.model_id not in audio_models:audio_models.insert(0, self.model_id)last_err = Nonefor a_model in audio_models:a_key = self._get_api_key(a_model)if not a_key:continuefor part in ({"type": "image_url", "image_url": {"url": data_uri}},{"type": "file", "file": {"file_data": data_uri}},):try:response = litellm.completion(model=a_model,api_key=a_key,messages=[{"role": "user","content": [{"type": "text", "text": question},part,],}],max_tokens=2048,timeout=45,)out = (response.choices[0].message.content or "").strip()if out:return outexcept Exception as exc:last_err = excraise RuntimeError(str(last_err) if last_err else "No audio transcription model available.")except Exception as e:return f"Error transcribing audio '{audio_path}': {str(e)}"candidate_models = []if self.provider_keys.get("openrouter"):58 unmodified linesforced_model = "gemini/" + forced_modelself.working_models = [forced_model] + [m for m in self.working_models if m != forced_model]self.working_models = [m for m in dict.fromkeys(self.working_models)if self._get_api_key(m)]if not self.working_models:raise RuntimeError("No models available for the configured API keys.")44 unmodified linesreturn msgdef _prepare_call_kwargs(self, kwargs: dict) -> dict:key = getattr(self, "_explicit_api_key", None) or kwargs.get("api_key")model_name = str(getattr(self, "model_id", "") or "")kwargs.pop("api_key", None)if key:if model_name.startswith("openrouter/"):os.environ["OPENROUTER_API_KEY"] = keyelif model_name.startswith("groq/"):31 unmodified linesexact_match_rule = ("CRITICAL OUTPUT RULES FOR EXACT MATCH EVALUATION:\n""- Always write valid Python code inside ```py and ``` fences. NEVER put 'Thought:' or HTML tags like <code> inside the Python block.\n""- Never call built-in open(); use read_local_file(file_path) for text/PDF/ZIP/spreadsheet files, ""inspect_image(image_path, question) for images, and transcribe_audio(audio_path, question) for audio files (.mp3, .wav).\n""- If web_search returns no results, use search_wikipedia(query) or fetch_url_text(url).\n""- Return ONLY the concise exact answer value itself "25 unmodified lines"string",],instructions=exact_match_rule,max_steps=14,verbosity_level=0,)print("CodeAgent initialized with LiteLLMModel.")89 unmodified linesreturn f"AGENT ERROR: {exc}"if len(models_to_try) > 1:current_provider = self.model_id.split("/", 1)[0].lower() if "/" in self.model_id else "gemini"other_provider_models = [m for m in models_to_tryif m != self.model_idand ((m.split("/", 1)[0].lower() if "/" in m else "gemini") != current_provider)]if other_provider_models and any(m in err_lower for m in ("401", "402", "404", "authenticationerror", "notfounderror")):next_model = other_provider_models[0]else:try:idx = models_to_try.index(self.model_id)next_model = models_to_try[(idx + 1) % len(models_to_try)]except ValueError:next_model = models_to_try[0]self.model_id = next_modelself.agent.model = model_cls(model_id=self.model_id,4 unmodified linestimeout=25,)print(f"Switched model to {self.model_id}.")wait_sec = 3 if any(m in err_lower for m in fast_retry_markers) else 25print(f"Sleeping {wait_sec}s before next attempt...")time.sleep(wait_sec)
app.py+236-104