File size: 1,852 Bytes
8507a20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
"""The comparison model for the agent harness, reached through the laptop relay (tools/or_proxy.py).

Same request the harness's own OpenRouter class sends (one bash tool, cost reported per call); only the address
differs, and the key stays on the laptop.
"""
import json
import os

import requests
from minisweagent.models.openrouter_model import (BASH_TOOL, OpenRouterAPIError, OpenRouterAuthenticationError,
                                                   OpenRouterModel, OpenRouterRateLimitError)


class RelayOpenRouterModel(OpenRouterModel):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._api_url = os.environ.get("RELAY_URL", "http://127.0.0.1:18811/v1/chat/completions")
        self._api_key = "relay"

    def _query(self, messages, **kwargs):
        payload = {"model": self.config.model_name, "messages": messages, "tools": [BASH_TOOL],
                   "usage": {"include": True}, **(self.config.model_kwargs | kwargs)}
        try:
            response = requests.post(self._api_url, headers={"Content-Type": "application/json"},
                                     data=json.dumps(payload), timeout=600)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.HTTPError as e:
            if response.status_code in (401, 402):          # 402: the relay's spend cap
                raise OpenRouterAuthenticationError(f"relay refused: HTTP {response.status_code} {response.text[:200]}") from e
            if response.status_code == 429:
                raise OpenRouterRateLimitError("Rate limit exceeded") from e
            raise OpenRouterAPIError(f"HTTP {response.status_code}: {response.text[:300]}") from e
        except requests.exceptions.RequestException as e:
            raise OpenRouterAPIError(f"Request failed: {e}") from e