Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files426 unmodified lines4274284294304314324334344354364374389 unmodified lines448449450451452453454455456355 unmodified lines81281381481581681727 unmodified lines84584684784884985085185285385485585685785885986086186286386486586645 unmodified lines91291391491591691791897 unmodified lines10161017101810191020102110221023102410251026102710281029103010311032103314 unmodified lines104810491050105110521053426 unmodified linesimport refrom html import unescapetry:resp = requests.get("https://en.wikipedia.org/w/api.php",params={"action": "opensearch", "search": query, "limit": 3, "format": "json"},headers={"User-Agent": "BasicAgent/1.0"},timeout=30,)resp.raise_for_status()data = resp.json()9 unmodified linestry:ddg_resp = requests.post("https://html.duckduckgo.com/html/",data={"q": query},headers={"User-Agent": "Mozilla/5.0"},timeout=30,)ddg_resp.raise_for_status()matches = re.findall(355 unmodified lines@classmethoddef _validate_message(cls, msg):import reif msg is None:27 unmodified linesreasoning_str = str(reasoning).strip() if reasoning else ""tool_calls = getattr(msg, "tool_calls", None)if not content_str:if reasoning_str:code_match = re.search(r"(<code>.*?</code>|```(?:py|python)?\s*\n.*?```)",reasoning_str,flags=re.DOTALL | re.IGNORECASE,)if code_match:content_str = code_match.group(1).strip()if not content_str and not tool_calls:raise RuntimeError("Error in generating model output: empty model response (content=None)")cleaned = cls._sanitize_code_tags(content_str) if content_str else ""if not cleaned.strip() and not tool_calls:raise RuntimeError("Error in generating model output: empty model response after sanitization")45 unmodified lineskwargs["reasoning_effort"] = "low"elif model_name.startswith("groq/"):kwargs["tool_choice"] = "auto"return self._model_cls(**kwargs)self._build_model = _build_modelmodel = self._build_model(self.model_id)97 unmodified linesif self.model_id and self.model_id not in models_to_try:models_to_try.append(self.model_id)models_to_try = [m for m in models_to_tryif m not in blocked_modelsand (m.split("/", 1)[0].lower() if "/" in m else "gemini") not in blocked_providersand bool(self._get_api_key(m))]for model_name in models_to_try:if not hasattr(self, "_build_model") or not hasattr(self, "agent"):breakprovider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini"if provider in blocked_providers:continuetry:self.model_id = model_name14 unmodified lines"authentication","missing authentication header","insufficient permissions",)):blocked_providers.add(provider)426 unmodified lines4274284294304314324334344354364374384394404414429 unmodified lines452453454455456457458459460355 unmodified lines81681781881982082182227 unmodified lines85085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190245 unmodified lines94894995095195295395495595695795895996096197 unmodified lines1059106010611062106310641065106610671068106910701071107214 unmodified lines1087108810891090109110921093426 unmodified linesimport refrom html import unescapecleaned_query = (query or "").strip()if not cleaned_query:return "Brak wyników."try:resp = requests.get("https://en.wikipedia.org/w/api.php",params={"action": "opensearch", "search": cleaned_query, "limit": 3, "format": "json"},headers={"User-Agent": "BasicAgent/1.0"},timeout=15,)resp.raise_for_status()data = resp.json()9 unmodified linestry:ddg_resp = requests.post("https://html.duckduckgo.com/html/",data={"q": cleaned_query},headers={"User-Agent": "Mozilla/5.0"},timeout=15,)ddg_resp.raise_for_status()matches = re.findall(355 unmodified lines@classmethoddef _validate_message(cls, msg):import jsonimport reif msg is None:27 unmodified linesreasoning_str = str(reasoning).strip() if reasoning else ""tool_calls = getattr(msg, "tool_calls", None)if not content_str and tool_calls:rendered_calls = []for tc in tool_calls:fn_obj = getattr(tc, "function", None)if fn_obj is None and isinstance(tc, dict):fn_obj = tc.get("function")fn_name = getattr(fn_obj, "name", None) if fn_obj is not None else Noneif fn_name is None and isinstance(fn_obj, dict):fn_name = fn_obj.get("name")fn_args = getattr(fn_obj, "arguments", None) if fn_obj is not None else Noneif fn_args is None and isinstance(fn_obj, dict):fn_args = fn_obj.get("arguments")if not fn_name:continueif isinstance(fn_args, str):try:parsed_args = json.loads(fn_args) if fn_args.strip() else {}except Exception:parsed_args = {"query": fn_args}else:parsed_args = fn_args or {}if isinstance(parsed_args, dict):rendered_calls.append(f"print({fn_name}(**{json.dumps(parsed_args, ensure_ascii=False)}))")if rendered_calls:content_str = "<code>\n" + "\n".join(rendered_calls) + "\n</code>"if not content_str and reasoning_str:code_match = re.search(r"(<code>.*?</code>|```(?:py|python)?\s*\n.*?```)",reasoning_str,flags=re.DOTALL | re.IGNORECASE,)if code_match:content_str = code_match.group(1).strip()else:first_line = reasoning_str.splitlines()[0].replace('"', "'")content_str = f'<code>\nprint(ask_web("{first_line[:120]}")) # fallback from reasoning\n</code>'if not content_str:raise RuntimeError("Error in generating model output: empty model response (content=None)")cleaned = cls._sanitize_code_tags(content_str)if not cleaned.strip():raise RuntimeError("Error in generating model output: empty model response after sanitization")45 unmodified lineskwargs["reasoning_effort"] = "low"elif model_name.startswith("groq/"):kwargs["tool_choice"] = "auto"kwargs["parallel_tool_calls"] = Falsemodel_instance = self._model_cls(**kwargs)if model_name.startswith("groq/"):for attr_name in ("kwargs", "completion_kwargs", "model_kwargs"):target_dict = getattr(model_instance, attr_name, None)if isinstance(target_dict, dict):target_dict["tool_choice"] = "auto"return model_instanceself._build_model = _build_modelmodel = self._build_model(self.model_id)97 unmodified linesif self.model_id and self.model_id not in models_to_try:models_to_try.append(self.model_id)for model_name in models_to_try:if not hasattr(self, "_build_model") or not hasattr(self, "agent"):breakprovider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini"if model_name in blocked_models or provider in blocked_providers:continueif not self._get_api_key(model_name):blocked_providers.add(provider)continuetry:self.model_id = model_name14 unmodified lines"authentication","missing authentication header","insufficient permissions","does not have sufficient permissions",)):blocked_providers.add(provider)
app.py+67-27