Skip to content

Drop in a screenshot and convert it to clean code (HTML/Tailwind/React/Vue)

Python

Abort generations that exceed a $3 spend ceiling

Abi Rajaf6d8a827e089
diff --git a/backend/agent/engine.py b/backend/agent/engine.py
index 3044e647..9ad1655e 100644
--- a/backend/agent/engine.py
+++ b/backend/agent/engine.py
@@ -18,9 +18,23 @@ from agent.tools import (
summarize_text,
summarize_tool_input,
)
+from config import GENERATION_MAX_COST_USD
from fs_logging.agent_runs import AgentRunRecorder
+class BudgetExceededError(Exception):
+ """Raised when a single generation exceeds the spend ceiling.
+
+ The message is shown verbatim to end users (variantError), so it must
+ not contain cost figures; the exact spend is in the run record.
+ """
+
+ def __init__(self) -> None:
+ super().__init__(
+ "Generation stopped: this variant exceeded its resource limit."
+ )
+
+
class AgentEngine:
def __init__(
self,
@@ -237,6 +251,17 @@ class AgentEngine:
if not turn.tool_calls:
return await self._finalize_response(turn.assistant_text)
+ # Abort only when the run would otherwise continue: a run that
+ # just produced its final answer is already paid for. Unpriced
+ # models return None and are not bounded.
+ spent = session.total_cost_usd()
+ if spent is not None and spent > GENERATION_MAX_COST_USD:
+ print(
+ f"[BUDGET] Aborting variant {self.variant_index}: "
+ f"${spent:.2f} > ${GENERATION_MAX_COST_USD:.2f}"
+ )
+ raise BudgetExceededError()
+
executed_tool_calls: List[ExecutedToolCall] = []
for tool_call in turn.tool_calls:
tool_event_id = tool_call.id or self._next_event_id("tool")
diff --git a/backend/agent/providers/anthropic/provider.py b/backend/agent/providers/anthropic/provider.py
index 5c48ebcd..965e7c6b 100644
--- a/backend/agent/providers/anthropic/provider.py
+++ b/backend/agent/providers/anthropic/provider.py
@@ -397,6 +397,12 @@ class AnthropicProviderSession(ProviderSession):
assistant_turn=final_message,
)
+ def total_cost_usd(self) -> Optional[float]:
+ pricing = MODEL_PRICING.get(_get_anthropic_api_model_name(self._model))
+ if pricing is None:
+ return None
+ return self._total_usage.cost(pricing)
+
def _image_block(self, part: Any) -> Dict[str, Any] | None:
"""A public URL goes as a url source; local bytes go as base64."""
if part.image_url:
diff --git a/backend/agent/providers/base.py b/backend/agent/providers/base.py
index b6811fb9..83d883f0 100644
--- a/backend/agent/providers/base.py
+++ b/backend/agent/providers/base.py
@@ -48,5 +48,9 @@ class ProviderSession(Protocol):
) -> None:
...
+ def total_cost_usd(self) -> Optional[float]:
+ """USD spent so far this session; None when the model is unpriced."""
+ ...
+
async def close(self) -> None:
...
diff --git a/backend/agent/providers/gemini.py b/backend/agent/providers/gemini.py
index 354c7589..6d29b310 100644
--- a/backend/agent/providers/gemini.py
+++ b/backend/agent/providers/gemini.py
@@ -360,6 +360,12 @@ class GeminiProviderSession(ProviderSession):
assistant_turn=assistant_turn,
)
+ def total_cost_usd(self) -> Optional[float]:
+ pricing = MODEL_PRICING.get(_get_gemini_api_model_name(self._model))
+ if pricing is None:
+ return None
+ return self._total_usage.cost(pricing)
+
@staticmethod
async def _resolve_part_bytes(part: Any) -> tuple[bytes | None, str]:
"""Gemini only accepts inline bytes, so download public URLs."""
diff --git a/backend/agent/providers/openai.py b/backend/agent/providers/openai.py
index 340a693e..d1e2cdbe 100644
--- a/backend/agent/providers/openai.py
+++ b/backend/agent/providers/openai.py
@@ -477,6 +477,12 @@ class OpenAIProviderSession(ProviderSession):
)
return turn
+ def total_cost_usd(self) -> float | None:
+ pricing = MODEL_PRICING.get(get_openai_api_name(self._model))
+ if pricing is None:
+ return None
+ return self._total_usage.cost(pricing)
+
@staticmethod
def _image_ref(part: Any) -> str | None:
"""A public URL is sent as-is; local bytes become a base64 data URL."""
diff --git a/backend/config.py b/backend/config.py
index b3c8c60c..6631629a 100644
--- a/backend/config.py
+++ b/backend/config.py
@@ -18,6 +18,10 @@ DEBUG_DIR = os.environ.get("DEBUG_DIR", "")
# When enabled, every LLM request is written to run_logs/prompt_reports as a
# JSON report viewable at /evals/prompt-reports.
+# Hard per-generation spend ceiling; a run that would continue past this is
+# aborted. Applies per variant/eval run. Unpriced models are not bounded.
+GENERATION_MAX_COST_USD = 3.0
+
PROMPT_REPORTS_ENABLED = os.environ.get(
"PROMPT_REPORTS_ENABLED", ""
).strip().lower() in {"1", "true", "yes", "on"}
diff --git a/backend/evals/runner.py b/backend/evals/runner.py
index d7673831..9cbb655b 100644
--- a/backend/evals/runner.py
+++ b/backend/evals/runner.py
@@ -7,6 +7,7 @@ import inspect
from llm import Llm
from config import LOCAL_ASSET_BASE_URL
from prompts.prompt_types import Stack
+from agent.engine import BudgetExceededError
from .core import generate_code_for_image
from .sets import get_set_inputs_dir
from .utils import image_to_data_url
@@ -134,6 +135,21 @@ async def generate_code_and_time(
None,
retries_used,
)
+ except BudgetExceededError as e:
+ # Never retry budget aborts: each retry would spend the whole
+ # ceiling again.
+ print(
+ f"Budget exceeded for {original_input_filename} "
+ f"(attempt {attempt_idx}); not retrying."
+ )
+ return (
+ original_input_filename,
+ attempt_idx,
+ None,
+ None,
+ e,
+ retries_used,
+ )
except Exception as e:
if retries_used >= MAX_EVAL_RETRIES:
print(
diff --git a/backend/tests/test_agent_runs.py b/backend/tests/test_agent_runs.py
index 7f704dd9..813e5452 100644
--- a/backend/tests/test_agent_runs.py
+++ b/backend/tests/test_agent_runs.py
@@ -434,9 +434,13 @@ async def test_asset_snapshot_catches_urls_in_js_strings(
class _ToolThenDoneSession:
"""One create_file tool turn, then a final assistant turn."""
- def __init__(self) -> None:
+ def __init__(self, cost_usd: Optional[float] = None) -> None:
self.turns = 0
self.closed = False
+ self.cost_usd = cost_usd
+
+ def total_cost_usd(self) -> Optional[float]:
+ return self.cost_usd
async def stream_turn(self, on_event: Any) -> Any:
from agent.providers.base import ProviderTurn, StreamEvent
@@ -538,6 +542,91 @@ async def test_engine_records_full_run(
)
+async def test_engine_aborts_over_budget_run(
+ logs_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from agent.engine import BudgetExceededError
+
+ session = _ToolThenDoneSession(cost_usd=5.0)
+ monkeypatch.setattr(
+ "agent.engine.create_provider_session", lambda **kwargs: session
+ )
+
+ recorder = _make_recorder()
+ engine = _make_engine(recorder)
+ with pytest.raises(BudgetExceededError) as excinfo:
+ await engine.run(Llm.GPT_5_5_HIGH, [])
+
+ # User-facing message must not leak cost figures.
+ assert "$" not in str(excinfo.value)
+ events = _read_events(recorder)
+ assert events[-1]["status"] == "failed"
+ # Only the first turn ran; its tools were never executed.
+ assert session.turns == 1
+
+
+async def test_engine_allows_final_turn_over_budget(
+ logs_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # A run finishing naturally is returned even when over budget: aborting
+ # after the final turn would waste tokens already paid for.
+ session = _ToolThenDoneSession(cost_usd=0.5)
+ monkeypatch.setattr(
+ "agent.engine.create_provider_session", lambda **kwargs: session
+ )
+ recorder = _make_recorder()
+ engine = _make_engine(recorder)
+
+ async def creep_cost(*args: Any, **kwargs: Any) -> Any:
+ # Cost crosses the ceiling only on the final (no-tool) turn.
+ result = await _ToolThenDoneSession.stream_turn(session, *args, **kwargs)
+ if session.turns == 2:
+ session.cost_usd = 5.0
+ return result
+
+ monkeypatch.setattr(session, "stream_turn", creep_cost)
+ result = await engine.run(Llm.GPT_5_5_HIGH, [])
+ assert result == "<html>from tool</html>"
+
+
+async def test_eval_runner_does_not_retry_budget_abort(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from agent.engine import BudgetExceededError
+ from evals.runner import generate_code_and_time
+
+ calls = {"count": 0}
+
+ async def always_over_budget(**kwargs: Any) -> str:
+ calls["count"] += 1
+ raise BudgetExceededError()
+
+ monkeypatch.setattr(
+ "evals.runner.generate_code_for_image", always_over_budget
+ )
+ (
+ filename,
+ attempt,
+ content,
+ duration,
+ error,
+ retries_used,
+ ) = await generate_code_and_time(
+ image_url="data:image/png;base64,eA==",
+ stack="html_tailwind",
+ model=Llm.GPT_5_5_HIGH,
+ original_input_filename="x.png",
+ attempt_idx=0,
+ )
+ assert isinstance(error, BudgetExceededError)
+ assert content is None
+ assert retries_used == 0
+ assert calls["count"] == 1 # no retries
+
+
@pytest.mark.asyncio
async def test_engine_records_failed_run_and_reraises(
logs_path: Path, monkeypatch: pytest.MonkeyPatch