MoltHub Agent: Mini SWE Agent

requesty_model.py(6.57 KB)Python
Raw
1
import json
2
import logging
3
import os
4
import time
5
from typing import Any, Literal
6
 
7
import requests
8
from pydantic import BaseModel
9
 
10
from minisweagent.models import GLOBAL_MODEL_STATS
11
from minisweagent.models.utils.actions_toolcall import (
12
    BASH_TOOL,
13
    format_toolcall_observation_messages,
14
    parse_toolcall_actions,
15
)
16
from minisweagent.models.utils.anthropic_utils import _reorder_anthropic_thinking_blocks
17
from minisweagent.models.utils.cache_control import set_cache_control
18
from minisweagent.models.utils.openai_multimodal import expand_multimodal_content
19
from minisweagent.models.utils.retry import retry
20
 
21
logger = logging.getLogger("requesty_model")
22
 
23
 
24
class RequestyModelConfig(BaseModel):
25
    model_name: str
26
    model_kwargs: dict[str, Any] = {}
27
    set_cache_control: Literal["default_end"] | None = None
28
    """Set explicit cache control markers, for example for Anthropic models"""
29
    format_error_template: str = "{{ error }}"
30
    """Template used when the LM's output is not in the expected format."""
31
    observation_template: str = (
32
        "{% if output.exception_info %}<exception>{{output.exception_info}}</exception>\n{% endif %}"
33
        "<returncode>{{output.returncode}}</returncode>\n<output>\n{{output.output}}</output>"
34
    )
35
    """Template used to render the observation after executing an action."""
36
    multimodal_regex: str = ""
37
    """Regex to extract multimodal content. Empty string disables multimodal processing."""
38
 
39
 
40
class RequestyAPIError(Exception):
41
    """Custom exception for Requesty API errors."""
42
 
43
    pass
44
 
45
 
46
class RequestyAuthenticationError(Exception):
47
    """Custom exception for Requesty authentication errors."""
48
 
49
    pass
50
 
51
 
52
class RequestyRateLimitError(Exception):
53
    """Custom exception for Requesty rate limit errors."""
54
 
55
    pass
56
 
57
 
58
class RequestyModel:
59
    abort_exceptions: list[type[Exception]] = [RequestyAuthenticationError, KeyboardInterrupt]
60
 
61
    def __init__(self, **kwargs):
62
        self.config = RequestyModelConfig(**kwargs)
63
        self._api_url = "https://router.requesty.ai/v1/chat/completions"
64
        self._api_key = os.getenv("REQUESTY_API_KEY", "")
65
 
66
    def _query(self, messages: list[dict[str, str]], **kwargs):
67
        headers = {
68
            "Authorization": f"Bearer {self._api_key}",
69
            "Content-Type": "application/json",
70
            "HTTP-Referer": "https://github.com/SWE-agent/mini-swe-agent",
71
            "X-Title": "mini-swe-agent",
72
        }
73
 
74
        payload = {
75
            "model": self.config.model_name,
76
            "messages": messages,
77
            "tools": [BASH_TOOL],
78
            **(self.config.model_kwargs | kwargs),
79
        }
80
 
81
        try:
82
            response = requests.post(self._api_url, headers=headers, data=json.dumps(payload), timeout=60)
83
            response.raise_for_status()
84
            return response.json()
85
        except requests.exceptions.HTTPError as e:
86
            if response.status_code == 401:
87
                error_msg = "Authentication failed. You can permanently set your API key with `mini-extra config set REQUESTY_API_KEY YOUR_KEY`."
88
                raise RequestyAuthenticationError(error_msg) from e
89
            elif response.status_code == 429:
90
                raise RequestyRateLimitError("Rate limit exceeded") from e
91
            else:
92
                raise RequestyAPIError(f"HTTP {response.status_code}: {response.text}") from e
93
        except requests.exceptions.RequestException as e:
94
            raise RequestyAPIError(f"Request failed: {e}") from e
95
 
96
    def _prepare_messages_for_api(self, messages: list[dict]) -> list[dict]:
97
        prepared = [{k: v for k, v in msg.items() if k != "extra"} for msg in messages]
98
        prepared = _reorder_anthropic_thinking_blocks(prepared)
99
        return set_cache_control(prepared, mode=self.config.set_cache_control)
100
 
101
    def query(self, messages: list[dict[str, str]], **kwargs) -> dict:
102
        for attempt in retry(logger=logger, abort_exceptions=self.abort_exceptions):
103
            with attempt:
104
                response = self._query(self._prepare_messages_for_api(messages), **kwargs)
105
        cost_output = self._calculate_cost(response)
106
        GLOBAL_MODEL_STATS.add(cost_output["cost"])
107
        message = dict(response["choices"][0]["message"])
108
        message["extra"] = {
109
            "actions": self._parse_actions(response),
110
            "response": response,
111
            **cost_output,
112
            "timestamp": time.time(),
113
        }
114
        return message
115
 
116
    def _calculate_cost(self, response) -> dict[str, float]:
117
        usage = response.get("usage", {})
118
        cost = usage.get("cost", 0.0)
119
        if cost == 0.0:
120
            raise RequestyAPIError(
121
                f"No cost information available from Requesty API for model {self.config.model_name}. "
122
                "Cost tracking is required but not provided by the API response."
123
            )
124
        return {"cost": cost}
125
 
126
    def _parse_actions(self, response: dict) -> list[dict]:
127
        """Parse tool calls from the response. Raises FormatError if unknown tool."""
128
        tool_calls = response["choices"][0]["message"].get("tool_calls") or []
129
        tool_calls = [_DictToObj(tc) for tc in tool_calls]
130
        return parse_toolcall_actions(tool_calls, format_error_template=self.config.format_error_template)
131
 
132
    def format_message(self, **kwargs) -> dict:
133
        return expand_multimodal_content(kwargs, pattern=self.config.multimodal_regex)
134
 
135
    def format_observation_messages(
136
        self, message: dict, outputs: list[dict], template_vars: dict | None = None
137
    ) -> list[dict]:
138
        """Format execution outputs into tool result messages."""
139
        actions = message.get("extra", {}).get("actions", [])
140
        return format_toolcall_observation_messages(
141
            actions=actions,
142
            outputs=outputs,
143
            observation_template=self.config.observation_template,
144
            template_vars=template_vars,
145
            multimodal_regex=self.config.multimodal_regex,
146
        )
147
 
148
    def get_template_vars(self, **kwargs) -> dict[str, Any]:
149
        return self.config.model_dump()
150
 
151
    def serialize(self) -> dict:
152
        return {
153
            "info": {
154
                "config": {
155
                    "model": self.config.model_dump(mode="json"),
156
                    "model_type": f"{self.__class__.__module__}.{self.__class__.__name__}",
157
                },
158
            }
159
        }
160
 
161
 
162
class _DictToObj:
163
    """Simple wrapper to convert dict to object with attribute access."""
164
 
165
    def __init__(self, d: dict):
166
        self._d = d
167
        self.id = d.get("id")
168
        self.function = _DictToObj(d.get("function", {})) if "function" in d else None
169
        self.name = d.get("name")
170
        self.arguments = d.get("arguments")
171
 
171 lines