Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 30 additions & 4 deletions src/minisweagent/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import importlib
import os
import threading
from collections.abc import Callable, Iterator
from contextlib import contextmanager

from minisweagent import Model

Expand All @@ -16,6 +18,7 @@ class GlobalModelStats:
def __init__(self):
self._cost = 0.0
self._n_calls = 0
self._in_flight = 0
self._lock = threading.Lock()
self.cost_limit = float(os.getenv("MSWEA_GLOBAL_COST_LIMIT", "0"))
self.call_limit = int(os.getenv("MSWEA_GLOBAL_CALL_LIMIT", "0"))
Expand All @@ -24,11 +27,34 @@ def __init__(self):

def add(self, cost: float) -> None:
"""Add a model call with its cost, checking limits."""
with self.track_call() as record_cost:
record_cost(cost)

@contextmanager
def track_call(self) -> Iterator[Callable[[float], None]]:
"""Reserve a slot before a model query, then record its completed cost."""
with self._lock:
self._cost += cost
self._n_calls += 1
if 0 < self.cost_limit < self._cost or 0 < self.call_limit < self._n_calls + 1:
raise RuntimeError(f"Global cost/call limit exceeded: ${self._cost:.4f} / {self._n_calls}")
occupied = self._n_calls + self._in_flight
if 0 < self.call_limit <= occupied:
raise RuntimeError(f"Global cost/call limit exceeded: ${self._cost:.4f} / {occupied}")
self._in_flight += 1

cost: float | None = None

def record_cost(amount: float) -> None:
nonlocal cost
cost = amount

try:
yield record_cost
finally:
with self._lock:
self._in_flight -= 1
if cost is not None:
self._cost += cost
self._n_calls += 1
if 0 < self.cost_limit < self._cost:
raise RuntimeError(f"Global cost/call limit exceeded: ${self._cost:.4f} / {self._n_calls}")

@property
def cost(self) -> float:
Expand Down
11 changes: 6 additions & 5 deletions src/minisweagent/models/litellm_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,12 @@ def _prepare_messages_for_api(self, messages: list[dict]) -> list[dict]:
return set_cache_control(prepared, mode=self.config.set_cache_control)

def query(self, messages: list[dict[str, str]], **kwargs) -> dict:
for attempt in retry(logger=logger, abort_exceptions=self.abort_exceptions):
with attempt:
response = self._query(self._prepare_messages_for_api(messages), **kwargs)
cost_output = self._calculate_cost(response)
GLOBAL_MODEL_STATS.add(cost_output["cost"])
with GLOBAL_MODEL_STATS.track_call() as record_cost:
for attempt in retry(logger=logger, abort_exceptions=self.abort_exceptions):
with attempt:
response = self._query(self._prepare_messages_for_api(messages), **kwargs)
cost_output = self._calculate_cost(response)
record_cost(cost_output["cost"])
# Note: all model.query() implementations must persist the response and cost on FormatError.
try:
actions = self._parse_actions(response)
Expand Down
11 changes: 6 additions & 5 deletions src/minisweagent/models/litellm_response_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,12 @@ def _query(self, messages: list[dict[str, str]], **kwargs):
raise e

def query(self, messages: list[dict[str, str]], **kwargs) -> dict:
for attempt in retry(logger=logger, abort_exceptions=self.abort_exceptions):
with attempt:
response = self._query(self._prepare_messages_for_api(messages), **kwargs)
cost_output = self._calculate_cost(response)
GLOBAL_MODEL_STATS.add(cost_output["cost"])
with GLOBAL_MODEL_STATS.track_call() as record_cost:
for attempt in retry(logger=logger, abort_exceptions=self.abort_exceptions):
with attempt:
response = self._query(self._prepare_messages_for_api(messages), **kwargs)
cost_output = self._calculate_cost(response)
record_cost(cost_output["cost"])
try:
actions = self._parse_actions(response)
except FormatError as e:
Expand Down
11 changes: 6 additions & 5 deletions src/minisweagent/models/openrouter_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,11 +95,12 @@ def _prepare_messages_for_api(self, messages: list[dict]) -> list[dict]:
return set_cache_control(prepared, mode=self.config.set_cache_control)

def query(self, messages: list[dict[str, str]], **kwargs) -> dict:
for attempt in retry(logger=logger, abort_exceptions=self.abort_exceptions):
with attempt:
response = self._query(self._prepare_messages_for_api(messages), **kwargs)
cost_output = self._calculate_cost(response)
GLOBAL_MODEL_STATS.add(cost_output["cost"])
with GLOBAL_MODEL_STATS.track_call() as record_cost:
for attempt in retry(logger=logger, abort_exceptions=self.abort_exceptions):
with attempt:
response = self._query(self._prepare_messages_for_api(messages), **kwargs)
cost_output = self._calculate_cost(response)
record_cost(cost_output["cost"])
try:
actions = self._parse_actions(response)
except FormatError as e:
Expand Down
11 changes: 6 additions & 5 deletions src/minisweagent/models/openrouter_response_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,12 @@ def _prepare_messages_for_api(self, messages: list[dict]) -> list[dict]:
return result

def query(self, messages: list[dict[str, str]], **kwargs) -> dict:
for attempt in retry(logger=logger, abort_exceptions=self.abort_exceptions):
with attempt:
response = self._query(self._prepare_messages_for_api(messages), **kwargs)
cost_output = self._calculate_cost(response)
GLOBAL_MODEL_STATS.add(cost_output["cost"])
with GLOBAL_MODEL_STATS.track_call() as record_cost:
for attempt in retry(logger=logger, abort_exceptions=self.abort_exceptions):
with attempt:
response = self._query(self._prepare_messages_for_api(messages), **kwargs)
cost_output = self._calculate_cost(response)
record_cost(cost_output["cost"])
try:
actions = self._parse_actions(response)
except FormatError as e:
Expand Down
11 changes: 6 additions & 5 deletions src/minisweagent/models/portkey_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,11 +102,12 @@ def _prepare_messages_for_api(self, messages: list[dict]) -> list[dict]:
return set_cache_control(prepared, mode=self.config.set_cache_control)

def query(self, messages: list[dict[str, str]], **kwargs) -> dict:
for attempt in retry(logger=logger, abort_exceptions=self.abort_exceptions):
with attempt:
response = self._query(self._prepare_messages_for_api(messages), **kwargs)
cost_output = self._calculate_cost(response)
GLOBAL_MODEL_STATS.add(cost_output["cost"])
with GLOBAL_MODEL_STATS.track_call() as record_cost:
for attempt in retry(logger=logger, abort_exceptions=self.abort_exceptions):
with attempt:
response = self._query(self._prepare_messages_for_api(messages), **kwargs)
cost_output = self._calculate_cost(response)
record_cost(cost_output["cost"])
try:
actions = self._parse_actions(response)
except FormatError as e:
Expand Down
11 changes: 6 additions & 5 deletions src/minisweagent/models/portkey_response_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,12 @@ def _prepare_messages_for_api(self, messages: list[dict]) -> list[dict]:
return result

def query(self, messages: list[dict[str, str]], **kwargs) -> dict:
for attempt in retry(logger=logger, abort_exceptions=self.abort_exceptions):
with attempt:
response = self._query(self._prepare_messages_for_api(messages), **kwargs)
cost_output = self._calculate_cost(response)
GLOBAL_MODEL_STATS.add(cost_output["cost"])
with GLOBAL_MODEL_STATS.track_call() as record_cost:
for attempt in retry(logger=logger, abort_exceptions=self.abort_exceptions):
with attempt:
response = self._query(self._prepare_messages_for_api(messages), **kwargs)
cost_output = self._calculate_cost(response)
record_cost(cost_output["cost"])
try:
actions = self._parse_actions(response)
except FormatError as e:
Expand Down
11 changes: 6 additions & 5 deletions src/minisweagent/models/requesty_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,12 @@ def _prepare_messages_for_api(self, messages: list[dict]) -> list[dict]:
return set_cache_control(prepared, mode=self.config.set_cache_control)

def query(self, messages: list[dict[str, str]], **kwargs) -> dict:
for attempt in retry(logger=logger, abort_exceptions=self.abort_exceptions):
with attempt:
response = self._query(self._prepare_messages_for_api(messages), **kwargs)
cost_output = self._calculate_cost(response)
GLOBAL_MODEL_STATS.add(cost_output["cost"])
with GLOBAL_MODEL_STATS.track_call() as record_cost:
for attempt in retry(logger=logger, abort_exceptions=self.abort_exceptions):
with attempt:
response = self._query(self._prepare_messages_for_api(messages), **kwargs)
cost_output = self._calculate_cost(response)
record_cost(cost_output["cost"])
try:
actions = self._parse_actions(response)
except FormatError as e:
Expand Down
137 changes: 137 additions & 0 deletions tests/models/test_global_call_limit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor
from threading import Event

import pytest
from litellm import ModelResponse

from minisweagent.exceptions import FormatError
from minisweagent.models import GLOBAL_MODEL_STATS, GlobalModelStats
from minisweagent.models.litellm_model import LitellmModel


class SyntheticLitellmModel(LitellmModel):
def __init__(self, on_call: Callable[[], None] | None = None, *, include_tool: bool = True):
super().__init__(model_name="gpt-4", litellm_model_registry=None)
self.on_call = on_call
self.include_tool = include_tool
self.provider_calls = 0

def _query(self, messages: list[dict[str, str]], **kwargs) -> ModelResponse:
self.provider_calls += 1
if self.on_call is not None:
self.on_call()
tool_call = {
"id": "call-fixture",
"type": "function",
"function": {"name": "bash", "arguments": '{"command": "echo fixture"}'},
}
return ModelResponse(
model=self.config.model_name,
choices=[
{
"index": 0,
"finish_reason": "tool_calls",
"message": {
"role": "assistant",
"content": "fixture response",
"tool_calls": [tool_call] if self.include_tool else [],
},
},
],
usage={"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
)


@pytest.mark.parametrize(("limit", "allowed_calls"), [(1, 1), (2, 2), (0, 3)])
def test_last_allowed_response_is_available(reset_global_stats, monkeypatch, limit, allowed_calls):
monkeypatch.setattr(GLOBAL_MODEL_STATS, "call_limit", limit)
model = SyntheticLitellmModel()

for _ in range(allowed_calls):
assert model.query([])["extra"]["actions"] == [{"command": "echo fixture", "tool_call_id": "call-fixture"}]
if limit:
with pytest.raises(RuntimeError, match="Global cost/call limit exceeded"):
model.query([])

assert model.provider_calls == GLOBAL_MODEL_STATS.n_calls == allowed_calls


def test_concurrent_queries_share_the_last_slot(reset_global_stats, monkeypatch):
monkeypatch.setattr(GLOBAL_MODEL_STATS, "call_limit", 1)
started = Event()
release = Event()

def wait_for_other_query():
started.set()
assert release.wait(timeout=10)

first = SyntheticLitellmModel(on_call=wait_for_other_query)
second = SyntheticLitellmModel()
with ThreadPoolExecutor(max_workers=2) as executor:
pending = executor.submit(first.query, [])
try:
assert started.wait(timeout=10)
with pytest.raises(RuntimeError, match="Global cost/call limit exceeded"):
second.query([])
assert second.provider_calls == 0
finally:
release.set()
assert pending.result(timeout=10)["content"] == "fixture response"

assert first.provider_calls == GLOBAL_MODEL_STATS.n_calls == 1


def test_failed_query_releases_its_slot(reset_global_stats, monkeypatch):
monkeypatch.setattr(GLOBAL_MODEL_STATS, "call_limit", 1)
monkeypatch.setenv("MSWEA_MODEL_RETRY_STOP_AFTER_ATTEMPT", "1")

def fail():
raise RuntimeError("synthetic provider failure")

with pytest.raises(RuntimeError, match="synthetic provider failure"):
SyntheticLitellmModel(on_call=fail).query([])
assert GLOBAL_MODEL_STATS.n_calls == 0
assert GLOBAL_MODEL_STATS.cost == 0.0
assert SyntheticLitellmModel().query([])["content"] == "fixture response"
assert GLOBAL_MODEL_STATS.n_calls == 1


def test_transport_retry_uses_the_same_slot(reset_global_stats, monkeypatch):
monkeypatch.setattr(GLOBAL_MODEL_STATS, "call_limit", 1)
monkeypatch.setenv("MSWEA_MODEL_RETRY_STOP_AFTER_ATTEMPT", "2")
failures = iter([True, False])

def fail_once():
if next(failures):
raise RuntimeError("synthetic retryable error")

model = SyntheticLitellmModel(on_call=fail_once)
assert model.query([])["content"] == "fixture response"
assert model.provider_calls == 2
assert GLOBAL_MODEL_STATS.n_calls == 1


def test_last_response_format_error_retains_cost_and_payload(reset_global_stats, monkeypatch):
monkeypatch.setattr(GLOBAL_MODEL_STATS, "call_limit", 1)
model = SyntheticLitellmModel(include_tool=False)

with pytest.raises(FormatError) as error:
model.query([])
extra = error.value.messages[0]["extra"]
assert extra["response"]["choices"][0]["message"]["content"] == "fixture response"
assert extra["cost"] == GLOBAL_MODEL_STATS.cost > 0
assert model.provider_calls == GLOBAL_MODEL_STATS.n_calls == 1


def test_direct_add_enforces_call_and_cost_boundaries(monkeypatch):
monkeypatch.setenv("MSWEA_GLOBAL_CALL_LIMIT", "2")
monkeypatch.setenv("MSWEA_GLOBAL_COST_LIMIT", "0.25")
stats = GlobalModelStats()

stats.add(0.25)
with pytest.raises(RuntimeError, match=r"\$0\.5000 / 2"):
stats.add(0.25)
with pytest.raises(RuntimeError, match=r"\$0\.5000 / 2"):
stats.add(0.25)
assert (stats.n_calls, stats.cost) == (2, 0.5)