Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files2224 unmodified lines2225222622272228222922302231223222332234223522362237223822392240281 unmodified lines25222523252425152525252625272528704 unmodified lines323332343235322632363237323832394 unmodified lines32443245324632373247324832393240324132423243324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281180 unmodified lines346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335142224 unmodified lines continue
plain = "\n".join(src_lines).strip() # Jeśli model zwrócił bezpośrednio krótki wynik (np. 'right', '42', 'Rd5') zamiast kodu Python: if ( plain and "\n" not in plain and len(plain) <= 80 and not plain.endswith((".", "?", ":")) and not re.match(r"^(?:thoughts?|thinking|invalid|error)\b", plain, re.IGNORECASE) ): safe_direct = json.dumps(plain.strip("\"'` "), ensure_ascii=False) return f"final_answer({safe_direct})" fa_match = re.findall( r"(?im)^\s*(?:final\s*answer|answer)\s*:\s*(.+)$", plain,281 unmodified lines if isinstance(getattr(self, "kwargs", None), dict): self.kwargs["api_key"] = key
default_cap = 15.0 default_cap = 28.0 timeout = min(float(getattr(self, "timeout", None) or default_cap), default_cap) task_deadline = getattr(self, "deadline", None) if task_deadline is not None:704 unmodified lines rem_now = deadline - step_t0 if rem_now <= 6.0: break call_timeout = max(6.0, min(14.0, rem_now - 2.0)) call_timeout = max(8.0, min(28.0, rem_now - 2.0)) print( f"[TRACE] task_id={task_id} model={model_name} provider={provider} " f"rem={rem_now:.1f}s timeout={call_timeout:.1f}s start",4 unmodified lines built_model.timeout = call_timeout built_model.deadline = deadline run_agent = self._create_code_agent(built_model) run_agent.max_steps = 6 if rem_now > 60.0 else (4 if rem_now > 25.0 else 3) run_agent.max_steps = 7 if rem_now > 60.0 else (5 if rem_now > 25.0 else 4) result = run_agent.run(prompt) print( f"[TRACE] task_id={task_id} model={model_name} " f"elapsed={time.monotonic() - step_t0:.1f}s returned={type(result).__name__}", flush=True, ) raw_result = "" if result is None else str(result).strip() if raw_result.lower().startswith("error in generating"): raise RuntimeError(raw_result) cleaned = self._clean_exact_match_answer(raw_result) if cleaned and len(cleaned) <= 2000 and not cleaned.startswith("AGENT ERROR:"): return cleaned
# Fallback: wyciągnij zebrane obserwacje z kroków agenta i poproś model o samą odpowiedź collected_obs = [] mem_steps = getattr(getattr(run_agent, "memory", None), "steps", None) or [] for st in mem_steps: obs_txt = getattr(st, "observations", None) if isinstance(obs_txt, str) and obs_txt.strip(): if "Invalid non-code output" not in obs_txt: collected_obs.append(obs_txt.strip()[:4500])
if collected_obs or raw_result: context_blob = "\n---\n".join(collected_obs[-3:]) if raw_result and "max steps" not in raw_result.lower(): context_blob += f"\n---\nAgent draft: {raw_result[:1500]}" if context_blob.strip(): direct_ans = self._direct_extract_answer( model_name=model_name, question=question.strip(), evidence=context_blob[:12000], deadline=deadline, ) if direct_ans: return direct_ans
blocked_models.add(model_name) break except Exception as exc:180 unmodified lines
return ""
def _direct_extract_answer(self, model_name: str, question: str, evidence: str, deadline: float) -> str: import time import litellm
rem = deadline - time.monotonic() if rem <= 5.0: return "" api_key = self._get_api_key(model_name) if not api_key: return "" kw = {"model": model_name, "api_key": api_key} if model_name.startswith("huggingface/"): kw = { "model": "openai/" + model_name[len("huggingface/"):], "api_base": "https://router.huggingface.co/v1", "api_key": api_key, } try: resp = litellm.completion( **kw, messages=[ { "role": "system", "content": ( "Extract ONLY the exact final answer to the user's question from the provided evidence. " "Output ONLY the exact requested value (number, single word/name, SAN chess move, or comma-separated list). " "NO sentences, NO explanations, NO markdown, NO units unless requested." ), }, { "role": "user", "content": f"Question:\n{question}\n\nEvidence:\n{evidence}", }, ], max_tokens=256, timeout=max(6.0, min(15.0, rem - 2.0)), num_retries=0, max_retries=0, ) txt = (resp.choices[0].message.content or "").strip() cleaned = self._clean_exact_match_answer(txt) if cleaned and len(cleaned) <= 300 and not cleaned.startswith("AGENT ERROR:"): return cleaned except Exception as exc: print(f"[DIRECT EXTRACT ERR] model={model_name}: {exc}", flush=True) return ""
def _trim_tool_output(text: str, max_chars: int = 4000) -> str: if not isinstance(text, str): return str(text)app.py+84-8