Skip to content

Commit 1870e58

Browse files
OnlyTerplxinfeiThibaultjaigudevin-ai-integration[bot]
authored
Merge pull request #32 from OnlyTerp/devin/integrate-open-items
* fix: close upstream HTTP responses to prevent FD exhaustion All five urllib.request.urlopen() call sites in the proxy now close the HTTPResponse object after use (via try/finally), preventing file-descriptor leaks that crash the proxy under UltraCode concurrency, surfacing as 'ConnectionRefused' in Claude Code mid-session. Affected call sites: - _relay_response: wrap body in try/finally resp.close() - _mk_events (openai_compat): close resp in finally - _classifier_complete: close resp after read (both openai_compat and Anthropic passthrough backends) - _handle_models: close resp after /v1/models fetch 27/27 offline self-tests pass. * docs: add Requesty as an OpenAI-compatible backend example * fix: ensure providers/*.py are importable in zipped/embedded Python builds --------- Co-authored-by: xinfeili <lxinfei5@gmail.com> Co-authored-by: Thibault Jaigu <thibault.jaigu@gmail.com> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2 parents dc0c4eb + 42b38b2 commit 1870e58

4 files changed

Lines changed: 118 additions & 60 deletions

File tree

‎README.md‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ left untouched.
2020

2121
The example config ships ready-to-use entries for **GPT‑5.5 (Codex login)**,
2222
**MiniMax‑M3**, **MiMo v2.5 Pro**, **DeepSeek V4 Pro/Flash**, **Step Flash**,
23-
**Ollama Cloud**, **OpenCode Go**, **OpenRouter**, and **local models** — keep
23+
**Ollama Cloud**, **OpenCode Go**, **OpenRouter**, **Requesty**, and **local models** — keep
2424
the ones you have a plan for, delete the rest. (Cursor's Composer needs the
2525
`cursor-agent` CLI and isn't HTTP-based — see
2626
[docs/ADD_A_MODEL.md](docs/ADD_A_MODEL.md).)
@@ -283,12 +283,16 @@ Example — MiMo and an OpenRouter model:
283283
Put your key right in `config.json` (it's gitignored) or use `${ENV_VAR}` and
284284
export it — or drop keys into a gitignored `ultracode.env` the launchers load.
285285

286+
[Requesty](https://requesty.ai) works the same way — another `openai_compat`
287+
gateway with `upstream` `https://router.requesty.ai/v1`, `provider/model` naming
288+
(e.g. `openai/gpt-4o-mini`), and `auth` `Bearer ${REQUESTY_API_KEY}`.
289+
286290
Route types:
287291

288292
| `type` | Use for | Needs |
289293
|-----------------|----------------------------------------------------|-------|
290294
| *(omit)* | Real Claude or any Anthropic-compatible endpoint | nothing, or `auth`/`upstream` |
291-
| `openai_compat` | MiMo, DeepSeek, OpenRouter, OpenAI, Ollama, local llama.cpp — anything that speaks OpenAI Chat Completions (tools included) | an API key |
295+
| `openai_compat` | MiMo, DeepSeek, OpenRouter, Requesty, OpenAI, Ollama, local llama.cpp — anything that speaks OpenAI Chat Completions (tools included) | an API key |
292296
| `codex_oauth` | GPT‑5.5 via a ChatGPT/Codex login (no API key) | `codex login` once |
293297
| `cursor_agent` | Cursor Composer (experimental) | `cursor-agent login` |
294298
| `auto` | The [Auto Router](docs/AUTO_ROUTER.md) — score candidates per task and route to the cheapest that's good enough | a `router` block + a classifier model |

‎config.example.json‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
{ "id": "claude-ollama-cloud", "display_name": "Ollama Cloud" },
2929
{ "id": "claude-opencode", "display_name": "DeepSeek V4 Pro (OpenCode Go)" },
3030
{ "id": "claude-openrouter", "display_name": "Llama 3.3 70B (OpenRouter)" },
31+
{ "id": "claude-requesty", "display_name": "GPT-4o mini (Requesty)" },
3132
{ "id": "claude-local", "display_name": "Local model" },
3233
{ "id": "claude-composer", "display_name": "Composer 2.5 (Cursor, experimental)" }
3334
],
@@ -103,6 +104,13 @@
103104
"model": "meta-llama/llama-3.3-70b-instruct",
104105
"auth": "Bearer REPLACE_WITH_YOUR_OPENROUTER_KEY"
105106
},
107+
"claude-requesty": {
108+
"_": "Requesty (https://requesty.ai) - an OpenAI-compatible LLM gateway. Models use provider/model naming (e.g. openai/gpt-4o-mini); swap model for any slug Requesty lists. Get a key at https://app.requesty.ai/api-keys.",
109+
"type": "openai_compat",
110+
"upstream": "https://router.requesty.ai/v1",
111+
"model": "openai/gpt-4o-mini",
112+
"auth": "Bearer ${REQUESTY_API_KEY}"
113+
},
106114
"claude-local": {
107115
"_": "A local OpenAI-compatible server (Ollama :11434, llama.cpp :8080, LM Studio :1234). The key is usually ignored.",
108116
"type": "openai_compat",

‎docs/ADD_A_MODEL.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,21 @@ llama.cpp / LM Studio server, etc. Tool calls are translated both ways.
7070
}
7171
```
7272

73+
[Requesty](https://requesty.ai) is another OpenAI-compatible gateway — same
74+
shape, just a different `upstream` and `provider/model` naming
75+
([docs](https://docs.requesty.ai), keys at
76+
[app.requesty.ai/api-keys](https://app.requesty.ai/api-keys)):
77+
78+
```json
79+
"claude-requesty": {
80+
"type": "openai_compat",
81+
"upstream": "https://router.requesty.ai/v1",
82+
"model": "openai/gpt-4o-mini",
83+
"auth": "Bearer ${REQUESTY_API_KEY}"
84+
}
85+
```
86+
87+
7388
- `upstream` is the OpenAI **base URL exactly as the provider documents it**
7489
(usually ends in `/v1`). The proxy appends `/chat/completions`.
7590
- `model` is the backend's real model id, **not** the `claude-…` alias.
@@ -204,6 +219,7 @@ plan/key for and delete the rest:
204219
| Ollama Cloud | `claude-ollama-cloud` | `openai_compat` | Ollama Cloud |
205220
| DeepSeek V4 Pro (OpenCode Go) | `claude-opencode` | `openai_compat` | OpenCode Zen (Go subscription) |
206221
| Llama 3.3 70B (OpenRouter) | `claude-openrouter` | `openai_compat` | OpenRouter |
222+
| GPT-4o mini (Requesty) | `claude-requesty` | `openai_compat` | Requesty |
207223
| Local model | `claude-local` | `openai_compat` | local server |
208224
| Composer 2.5 (experimental) | `claude-composer` | `cursor_agent` | cursor-agent |
209225
| Auto (smart routing) | `claude-auto` | `auto` | picks among your backends per task |

‎proxy.py‎

Lines changed: 88 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,13 @@ def _context_length_hint(detail):
286286
except Exception:
287287
UC_MODEL_MAP = {}
288288

289+
# Ensure sibling modules (providers/*.py) are importable even when the
290+
# interpreter's default sys.path[0] does not point here (e.g. zipped/embedded
291+
# Python builds). This is a no-op when the script dir is already on sys.path.
292+
_HERE = os.path.dirname(os.path.abspath(__file__))
293+
if _HERE not in sys.path:
294+
sys.path.insert(0, _HERE)
295+
289296
# Optional Codex/ChatGPT OAuth helper (only needed for "codex_oauth" routes).
290297
try:
291298
from providers import codex_oauth as _codex_oauth # type: ignore
@@ -1932,9 +1939,12 @@ def _classifier_complete(slot, system_prompt, user_content, timeout):
19321939
headers[hk] = hv
19331940
req = urllib.request.Request(url, data=data, headers=headers, method="POST")
19341941
resp = urllib.request.urlopen(req, timeout=timeout)
1935-
obj = json.loads(resp.read().decode("utf-8"))
1936-
msg = ((obj.get("choices") or [{}])[0].get("message") or {})
1937-
return msg.get("content") or ""
1942+
try:
1943+
obj = json.loads(resp.read().decode("utf-8"))
1944+
msg = ((obj.get("choices") or [{}])[0].get("message") or {})
1945+
return msg.get("content") or ""
1946+
finally:
1947+
resp.close()
19381948

19391949
# Anthropic passthrough (real Claude or any Anthropic-compatible endpoint).
19401950
url = (slot.get("upstream") or UPSTREAM).rstrip("/") + "/v1/messages"
@@ -1951,8 +1961,11 @@ def _classifier_complete(slot, system_prompt, user_content, timeout):
19511961
headers[hk] = hv
19521962
req = urllib.request.Request(url, data=data, headers=headers, method="POST")
19531963
resp = urllib.request.urlopen(req, timeout=timeout)
1954-
obj = json.loads(resp.read().decode("utf-8"))
1955-
return _text_from_anthropic_content(obj.get("content"))
1964+
try:
1965+
obj = json.loads(resp.read().decode("utf-8"))
1966+
return _text_from_anthropic_content(obj.get("content"))
1967+
finally:
1968+
resp.close()
19561969

19571970

19581971
def _parse_scores(text, candidate_ids):
@@ -2264,15 +2277,18 @@ def _handle_models(self) -> bool:
22642277
try:
22652278
req = urllib.request.Request(url, headers=fwd_headers, method="GET")
22662279
resp = urllib.request.urlopen(req, timeout=30)
2267-
parsed = json.loads(resp.read().decode("utf-8"))
2268-
if isinstance(parsed, dict) and isinstance(parsed.get("data"), list):
2269-
base = parsed
2270-
# Learn the current real-Claude ids from this successful fetch and
2271-
# cache them, so a newly released Opus is remembered for next time
2272-
# (even when upstream is later unreachable). Recompute stock after
2273-
# learning so any new id also lands in THIS response.
2274-
_learn_stock_from_upstream(base["data"])
2275-
stock = _stock_models()
2280+
try:
2281+
parsed = json.loads(resp.read().decode("utf-8"))
2282+
if isinstance(parsed, dict) and isinstance(parsed.get("data"), list):
2283+
base = parsed
2284+
# Learn the current real-Claude ids from this successful fetch and
2285+
# cache them, so a newly released Opus is remembered for next time
2286+
# (even when upstream is later unreachable). Recompute stock after
2287+
# learning so any new id also lands in THIS response.
2288+
_learn_stock_from_upstream(base["data"])
2289+
stock = _stock_models()
2290+
finally:
2291+
resp.close()
22762292
except Exception as e:
22772293
# No usable upstream list (e.g. no Anthropic credential to forward,
22782294
# or an offline blip). We still serve stock + custom below, so real
@@ -2451,26 +2467,34 @@ def _handle_openai_compat(self, body: bytes, route: dict):
24512467

24522468
def _mk_events():
24532469
req = urllib.request.Request(url, data=payload, headers=headers, method="POST")
2470+
resp = None
24542471
try:
2455-
resp = urllib.request.urlopen(req, timeout=600)
2456-
except urllib.error.HTTPError as e:
2457-
detail = ""
24582472
try:
2459-
detail = e.read().decode("utf-8", "replace")[:800]
2460-
except Exception:
2461-
pass
2462-
hint = _context_length_hint(detail)
2463-
log("openai_compat upstream HTTP %s for %s: %s" % (e.code, url, detail))
2464-
yield {"type": "error", "status": e.code,
2465-
"message": "openai_compat upstream %s: %s%s"
2466-
% (e.code, detail, hint)}
2467-
return
2468-
except Exception as e:
2469-
log("openai_compat upstream error %s for %s" % (e, url))
2470-
yield {"type": "error", "status": 502,
2471-
"message": "openai_compat upstream error: %s" % e}
2472-
return
2473-
yield from _oai_response_to_events(resp)
2473+
resp = urllib.request.urlopen(req, timeout=600)
2474+
except urllib.error.HTTPError as e:
2475+
detail = ""
2476+
try:
2477+
detail = e.read().decode("utf-8", "replace")[:800]
2478+
except Exception:
2479+
pass
2480+
hint = _context_length_hint(detail)
2481+
log("openai_compat upstream HTTP %s for %s: %s" % (e.code, url, detail))
2482+
yield {"type": "error", "status": e.code,
2483+
"message": "openai_compat upstream %s: %s%s"
2484+
% (e.code, detail, hint)}
2485+
return
2486+
except Exception as e:
2487+
log("openai_compat upstream error %s for %s" % (e, url))
2488+
yield {"type": "error", "status": 502,
2489+
"message": "openai_compat upstream error: %s" % e}
2490+
return
2491+
yield from _oai_response_to_events(resp)
2492+
finally:
2493+
if resp is not None:
2494+
try:
2495+
resp.close()
2496+
except Exception:
2497+
pass
24742498

24752499
events = _events_with_retry(_mk_events, label="openai_compat %s" % model_id)
24762500
if want_stream:
@@ -2690,33 +2714,39 @@ def _json_anthropic_from_events(self, events, model_id: str):
26902714

26912715
# ---- low-level response helpers -------------------------------------
26922716
def _relay_response(self, resp, streaming: bool):
2693-
status = getattr(resp, "status", None) or resp.getcode()
2694-
self.send_response(status)
2695-
for k, v in resp.headers.items():
2696-
kl = k.lower()
2697-
if kl in _HOP_BY_HOP or kl in ("content-length", "content-encoding"):
2698-
continue
2699-
self.send_header(k, v)
2700-
if streaming:
2701-
self.send_header("Content-Type", "text/event-stream")
2702-
self.send_header("Cache-Control", "no-cache")
2703-
self.close_connection = True
2704-
self.send_header("Connection", "close")
2705-
self.end_headers()
2717+
try:
2718+
status = getattr(resp, "status", None) or resp.getcode()
2719+
self.send_response(status)
2720+
for k, v in resp.headers.items():
2721+
kl = k.lower()
2722+
if kl in _HOP_BY_HOP or kl in ("content-length", "content-encoding"):
2723+
continue
2724+
self.send_header(k, v)
2725+
if streaming:
2726+
self.send_header("Content-Type", "text/event-stream")
2727+
self.send_header("Cache-Control", "no-cache")
2728+
self.close_connection = True
2729+
self.send_header("Connection", "close")
2730+
self.end_headers()
2731+
try:
2732+
while True:
2733+
chunk = resp.read(8192)
2734+
if not chunk:
2735+
break
2736+
self.wfile.write(chunk)
2737+
self.wfile.flush()
2738+
except Exception as e:
2739+
vlog("stream relay ended: %s" % e)
2740+
else:
2741+
data = resp.read()
2742+
self.send_header("Content-Length", str(len(data)))
2743+
self.end_headers()
2744+
self.wfile.write(data)
2745+
finally:
27062746
try:
2707-
while True:
2708-
chunk = resp.read(8192)
2709-
if not chunk:
2710-
break
2711-
self.wfile.write(chunk)
2712-
self.wfile.flush()
2713-
except Exception as e:
2714-
vlog("stream relay ended: %s" % e)
2715-
else:
2716-
data = resp.read()
2717-
self.send_header("Content-Length", str(len(data)))
2718-
self.end_headers()
2719-
self.wfile.write(data)
2747+
resp.close()
2748+
except Exception:
2749+
pass
27202750

27212751
def _send_error(self, status: int, message: str):
27222752
body = json.dumps({"type": "error",

0 commit comments

Comments
 (0)