-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproviders.py
More file actions
6186 lines (5529 loc) · 253 KB
/
Copy pathproviders.py
File metadata and controls
6186 lines (5529 loc) · 253 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Multi-provider support for Dulus.
Supported providers:
anthropic — Claude (claude-opus-4-6, claude-sonnet-4-6, ...)
openai — GPT (gpt-4o, o3-mini, ...)
gemini — Google Gemini (gemini-2.0-flash, gemini-1.5-pro, ...)
kimi — Moonshot AI (kimi-k2.5, moonshot-v1-8k/32k/128k)
kimi-code — Kimi Code (kimi-for-coding, membership API from kimi.com/code)
Supports fallback chain: KIMI_CODE_API_KEY → KIMI_CODE2_API_KEY → KIMI_CODE3_API_KEY
qwen — Alibaba DashScope (qwen-max, qwen-plus, ...)
modelstudio — Alibaba Cloud Model Studio, Singapore workspace (OpenAI-compatible)
amd — AMD Developer Cloud / ROCm vLLM server (OpenAI-compatible)
zhipu — Zhipu GLM (glm-4, glm-4-plus, ...)
deepseek — DeepSeek (deepseek-chat, deepseek-reasoner, ...)
minimax — MiniMax (MiniMax-Text-01, abab6.5s-chat, ...)
ollama — Local Ollama (llama3.3, qwen2.5-coder, ...)
lmstudio — Local LM Studio (any loaded model)
custom — Any OpenAI-compatible endpoint
Model string formats:
"claude-opus-4-6" auto-detected → anthropic
"gpt-4o" auto-detected → openai
"ollama/qwen2.5-coder" explicit provider prefix
"custom/my-model" uses CUSTOM_BASE_URL from config
"""
from __future__ import annotations
import json
import urllib.request
import urllib.parse
import urllib.error
import requests
import re
import time
import random
import functools
import subprocess
import platform
from typing import Generator, Any, Callable
# ── TLS: trust the OS certificate store ──────────────────────────────────
# Cloudflare WARP / Cloudflare One does TLS inspection with its own root CA,
# which is installed in the OS trust store (Windows cert store / macOS Keychain
# / Linux ca-certificates) but is NOT in Python's bundled `certifi`. Without
# this, every HTTPS call fails with SSLCertVerificationError while WARP is on.
# `truststore` makes Python's ssl module use the OS store, so the WARP CA is
# trusted automatically — and normal browsing (WARP off) keeps working too.
# This covers httpx (OpenAI + Anthropic SDKs), requests, and urllib at once.
#
# Optional manual override: set DULUS_CA_BUNDLE (or SSL_CERT_FILE) to a PEM
# file with the Cloudflare cert if you prefer pinning it explicitly.
import os as _os_tls
_ca_bundle = _os_tls.environ.get("DULUS_CA_BUNDLE") or _os_tls.environ.get("SSL_CERT_FILE")
if _ca_bundle and _os_tls.path.exists(_ca_bundle):
# Point the common HTTP stacks at the explicit bundle.
_os_tls.environ.setdefault("SSL_CERT_FILE", _ca_bundle)
_os_tls.environ.setdefault("REQUESTS_CA_BUNDLE", _ca_bundle)
else:
try:
import truststore as _truststore
_truststore.inject_into_ssl() # use OS trust store everywhere
except Exception:
# truststore not installed or injection failed — fall back to certifi.
# Install with: pip install truststore (Python 3.10+)
pass
# ── Provider resilience: retry with exponential backoff + jitter ─────────
class _ProviderRetry:
"""Lightweight retry wrapper for provider streaming calls.
Retries on: timeout, connection errors, 429 (rate limit), 5xx.
Does NOT retry on: 4xx (client errors), auth failures.
MAX_RETRIES = 0 by design (Kev, 2026-09-03): automatic silent retries made
models "freeze out of nowhere" — the terminal stalled in a hidden sleep
while the user had no clue a transient error happened. We now surface the
error immediately and stop; the user re-sends or switches model. Bump this
back up ONLY if you also keep the retry visible (it now yields a warning).
"""
MAX_RETRIES: int = 0
BASE_DELAY: float = 0.5
MAX_DELAY: float = 5.0
@classmethod
def is_retryable(cls, exc: Exception) -> bool:
"""Return True if the exception is worth retrying."""
msg = str(exc).lower()
# Quota exhaustion (NVIDIA "ResourceExhausted", Gemini "quota exceeded")
# will not recover within a retry window — surface it immediately.
if "resourceexhausted" in msg or "resource_exhausted" in msg or "resource exhausted" in msg:
return False
if "quota" in msg or "request limit reached" in msg:
return False
# Rate limit / server overload
if "429" in msg or "rate limit" in msg or "too many requests" in msg:
return True
# Server errors
if "500" in msg or "502" in msg or "503" in msg or "504" in msg:
return True
# Timeouts / connection issues
if "timeout" in msg or "connection" in msg or "timed out" in msg:
return True
if "chunked encoding" in msg or "broken pipe" in msg:
return True
return False
@classmethod
def sleep_for_attempt(cls, attempt: int) -> float:
"""Exponential backoff with full jitter."""
exp = cls.BASE_DELAY * (2 ** attempt)
jitter = random.random() * exp
return min(jitter, cls.MAX_DELAY)
@classmethod
def wrap_generator(cls, fn: Callable, *args, **kwargs) -> Generator:
"""Wrap a generator function with retry logic.
If the request fails BEFORE yielding anything, waits and retries up to
MAX_RETRIES times. Once a stream has emitted output it is unsafe to
retry (would duplicate partial output), so a failure after the first
chunk always propagates.
"""
last_exc: Exception | None = None
for attempt in range(cls.MAX_RETRIES + 1):
emitted = False
try:
for chunk in fn(*args, **kwargs):
emitted = True
yield chunk
return
except Exception as exc:
last_exc = exc
if (
emitted
or attempt >= cls.MAX_RETRIES
or not cls.is_retryable(exc)
):
raise
delay = cls.sleep_for_attempt(attempt)
# Announce the retry instead of freezing silently. A bare
# time.sleep() here is exactly what makes the terminal look
# "frozen out of nowhere" — the user has no idea a transient
# error (timeout / 429 / 5xx) happened and we're waiting.
try:
_reason = friendly_api_error(exc)
except Exception:
_reason = f"{type(exc).__name__}: {str(exc)[:120]}"
yield TextChunk(
f"\n⚠️ Provider hiccup ({_reason}). "
f"Retrying in {delay:.1f}s "
f"(attempt {attempt + 2}/{cls.MAX_RETRIES + 1})…\n"
)
time.sleep(delay)
# Should never reach here, but just in case
if last_exc:
raise last_exc
_ANTHROPIC_PARAM_RE = re.compile(
r'<parameter\s+name="(?P<key>[^"]+)"\s*>(?P<val>.*?)</parameter>',
re.DOTALL,
)
_TOOLCALL_NAME_RE = re.compile(r'"name"\s*:\s*"(?P<name>[^"]+)"')
def _parse_tool_call_payload(payload: str):
"""Best-effort extraction of (tool_name, input_dict) from the body of a
`<tool_call>...</tool_call>` block.
Why this exists: models sometimes leak Anthropic's `<function_calls>` /
`<parameter>` syntax INSIDE our `<tool_call>` block, which corrupts the
JSON. Without a recovery path the call is silently dropped by
`try: json.loads(...); except: pass` and the user sees their request
vanish into thin air. We try three strategies, easiest first.
Returns (name, input_dict) or None.
"""
payload = (payload or "").strip()
if not payload:
return None
# Strategy 1 — clean JSON ("name" + "input"). Vast majority of calls.
try:
data = json.loads(payload)
if isinstance(data, dict):
name = data.get("name") or (
data.get("function", {}).get("name")
if isinstance(data.get("function"), dict) else None
)
if name:
inp = data.get("input") or (
data.get("function", {}).get("arguments")
if isinstance(data.get("function"), dict) else None
) or {}
if isinstance(inp, str):
try:
inp = json.loads(inp)
except Exception:
inp = {}
return name, (inp if isinstance(inp, dict) else {})
except Exception:
pass
# Strategy 2 — Anthropic-syntax leak: `{"name": "X"> <parameter ...>` etc.
# Pull the tool name from the leading JSON-ish prefix and the params from
# all `<parameter name="K">V</parameter>` blocks. Coerce numeric/bool
# strings into proper JSON types where obvious.
if "<parameter" in payload and "</parameter>" in payload:
m = _TOOLCALL_NAME_RE.search(payload)
if m:
name = m.group("name")
inp: dict = {}
for pm in _ANTHROPIC_PARAM_RE.finditer(payload):
key = pm.group("key")
val = pm.group("val")
# Coerce common scalar forms; leave everything else as string.
sval = val.strip()
if sval.lower() == "true":
inp[key] = True
elif sval.lower() == "false":
inp[key] = False
elif sval.lower() == "null":
inp[key] = None
else:
try:
if sval.isdigit() or (sval.startswith("-") and sval[1:].isdigit()):
inp[key] = int(sval)
elif sval.replace(".", "", 1).lstrip("-").isdigit():
inp[key] = float(sval)
elif sval.startswith("[") or sval.startswith("{"):
inp[key] = json.loads(sval)
else:
inp[key] = val
except Exception:
inp[key] = val
if inp:
return name, inp
# Strategy 3 — last-ditch: maybe the JSON is just unterminated. Try to
# find balanced braces from the first `{` and parse that.
first = payload.find("{")
if first != -1:
depth = 0
end = -1
in_str = False
esc = False
for i in range(first, len(payload)):
c = payload[i]
if esc:
esc = False; continue
if c == "\\":
esc = True; continue
if c == '"':
in_str = not in_str; continue
if in_str:
continue
if c == "{":
depth += 1
elif c == "}":
depth -= 1
if depth == 0:
end = i + 1
break
if end != -1:
try:
data = json.loads(payload[first:end])
if isinstance(data, dict):
name = data.get("name")
if name:
return name, (data.get("input") or {})
except Exception:
pass
return None
def _decode_webchat_entities(text: str) -> str:
"""Decode the HTML entities a chat UI (e.g. Claude.ai webchat) may apply to a
`<tool_call>` block when it renders the assistant turn, so the parser still
finds the tags + JSON. Only entities relevant to tag/JSON detection are
decoded; everything else is left intact. (`&` is decoded last to handle
single-level double-encoding like `&lt;` → `<`.)
"""
if "&" not in text:
return text
return (text.replace("<", "<").replace(">", ">")
.replace(""", '"').replace(""", '"')
.replace("'", "'").replace("'", "'")
.replace("&", "&"))
class WebToolParser:
"""Shared parser for prompt-based tool calls in XML format.
Also supports auto-wrapping raw JSON tool calls if auto_wrap_json=True.
"""
def __init__(self, auto_wrap_json: bool = False):
self._in_call = False
self._call_buf = ""
self._raw_buf = ""
self._auto_wrap_json = auto_wrap_json
self.tool_calls = []
def parse_chunk(self, chunk: str) -> str:
"""Parse chunk, return display text and accumulate tool calls."""
if not chunk: return ""
self._raw_buf += chunk
# Claude.ai (and other chat UIs) may HTML-encode our <tool_call> tags or
# wrap them in ``` fences when rendering. Decode the relevant entities so
# the tags + JSON stay detectable (calls inside ``` fences parse as-is).
if "&" in self._raw_buf:
self._raw_buf = _decode_webchat_entities(self._raw_buf)
display = ""
while True:
if not self._in_call:
# Look for start tag
pos = self._raw_buf.find("<tool_call>")
if pos == -1:
# No start tag. Check for partial start tag at the very end
last_lt = self._raw_buf.rfind("<")
if last_lt != -1 and "<tool_call>".startswith(self._raw_buf[last_lt:]):
display += self._raw_buf[:last_lt]
self._raw_buf = self._raw_buf[last_lt:]
else:
display += self._raw_buf
self._raw_buf = ""
break
else:
# Found start tag: everything before is text
display += self._raw_buf[:pos]
self._in_call = True
self._raw_buf = self._raw_buf[pos + len("<tool_call>"):]
continue # Look for end tag in the rest of buffer
else:
# Inside a tag: look for end tag
pos = self._raw_buf.find("</tool_call>")
if pos == -1:
# End tag not found yet. BUT: if we already buffered a full
# Anthropic-style `<function_calls>` block leak (i.e. JSON
# opener + at least one `</parameter>`), the model is never
# going to close with `</tool_call>` — recover now instead
# of waiting forever and dumping as text on flush().
self._call_buf += self._raw_buf
self._raw_buf = ""
if "</parameter>" in self._call_buf and "<parameter" in self._call_buf:
parsed = _parse_tool_call_payload(self._call_buf.strip())
if parsed:
name, inp = parsed
self.tool_calls.append({
"id": f"call_pt_{len(self.tool_calls)}",
"name": name,
"input": inp,
})
self._call_buf = ""
self._in_call = False
continue
break
else:
# Found end tag: extract JSON and continue
self._call_buf += self._raw_buf[:pos]
self._raw_buf = self._raw_buf[pos + len("</tool_call>"):]
parsed = _parse_tool_call_payload(self._call_buf.strip())
if parsed:
name, inp = parsed
self.tool_calls.append({
"id": f"call_pt_{len(self.tool_calls)}",
"name": name,
"input": inp,
})
self._call_buf = ""
self._in_call = False
continue # Look for more tags in the rest of buffer
# 2. Raw JSON Fallback (only if enabled and NOT inside a tag)
if self._auto_wrap_json and not self._in_call and "{" in display:
search_pos = 0
while True:
start = display.find("{", search_pos)
if start == -1: break
snippet = display[start:start+500]
if '"name"' in snippet and ('"input"' in snippet or '"arguments"' in snippet):
brace_count = 0
end_pos = -1
for j in range(start, len(display)):
if display[j] == "{": brace_count += 1
elif display[j] == "}":
brace_count -= 1
if brace_count == 0:
end_pos = j + 1
break
if end_pos != -1:
try:
json_str = display[start:end_pos]
data = json.loads(json_str)
name = data.get("name") or (data.get("function", {}).get("name") if isinstance(data.get("function"), dict) else None)
if name:
self.tool_calls.append({
"id": f"call_pt_{len(self.tool_calls)}",
"name": name,
"input": data.get("input") or data.get("function", {}).get("arguments") or {},
})
display = display[:start] + display[end_pos:]
search_pos = start
continue
except: pass
search_pos = start + 1
return display
def flush(self) -> str:
"""Return any remaining text in the buffer."""
res = self._raw_buf
self._raw_buf = ""
# If we were in a call but it never ended, we should probably output the partial call?
# But for now, just the raw text.
if self._in_call:
res = "<tool_call>" + self._call_buf + res
self._call_buf = ""
self._in_call = False
return res
def _format_web_tool_manifest(tool_schemas: list, config: dict, messages: list) -> str:
"""Format tools as a prompt hint for web models.
First turn → full manifest with strong instructions + tool list.
Continuation turns → short format reminder (always injected, cheap).
Disable entirely with config["no_tools"] = True.
"""
if not tool_schemas or config.get("no_tools"):
return ""
is_first_turn = len([m for m in messages if m.get("role") == "user"]) <= 1
# Web providers (claude.ai, qwen.ai, etc.) keep the conversation server-side,
# so the turn-1 manifest is still in the model's context on every later turn.
# Re-injecting wastes tokens. Skip unless the user explicitly opted in.
if not is_first_turn and not config.get("always_inject_tools"):
return ""
manifest = [
"\n\n[TOOL USE — READ CAREFULLY]",
"You are running inside an agent harness that can EXECUTE tools for you.",
"When you need information, file contents, or to run an action — DO NOT describe what you would do; CALL the tool.",
"",
"EXACT format (any deviation = the call is ignored):",
' <tool_call>{"name": "ToolName", "input": {"key": "value"}}</tool_call>',
"",
"Rules:",
"1. The <tool_call> tag MUST be on its own line, with valid JSON inside.",
"2. Use ONLY tool names from the list below. Do NOT invent tools (no `SleepTimer`, no `WaitFor`, no fake names — `Reminder` is the real one if you need a delayed wake-up).",
"3. To call multiple tools, emit multiple <tool_call> blocks in the SAME response — do not wait for results between them.",
"4. After tool results come back, you may call more tools or give a final answer.",
"5. If no tool is needed, just answer normally — no tool_call tag.",
"",
"Example (correct):",
' <tool_call>{"name": "Read", "input": {"file_path": "/tmp/foo.txt"}}</tool_call>',
"",
"Available Tools:",
]
for s in tool_schemas:
manifest.append(f"- {s['name']}: {s.get('description', '')}")
manifest.append(f" Inputs: {json.dumps(s.get('parameters', {}).get('properties', {}), separators=(',', ':'))}")
return "\n".join(manifest)
def _consolidate_web_history(messages: list, manifest: str = "") -> str:
"""Consolidate history since last assistant turn into one prompt string.
This ensures tool results and system notifications are correctly perceived
by web-based models that take a single prompt string.
"""
if not messages:
return manifest
# Find last assistant message that actually has text or was saved
last_ast = -1
for i in range(len(messages) - 1, -1, -1):
if messages[i].get("role") == "assistant":
last_ast = i
break
parts = []
relevant = messages[last_ast + 1:] if last_ast != -1 else messages
for m in relevant:
role = m.get("role", "user")
content = m.get("content", "")
# We only skip empty content if it's NOT a tool result.
# Tool results must be sent even if empty so the model knows they ran.
if role != "tool" and not content:
continue
header = f"--- [{role.upper()}] ---"
if role == "tool":
header = f"--- [Tool Result: {m.get('name', 'Unknown')}] ---"
if not content:
content = "(No output / Empty result)"
parts.append(f"{header}\n{content}")
prompt = "\n\n".join(parts).strip()
if manifest:
prompt = manifest + "\n\n" + prompt
return prompt.strip()
# ── Provider registry ──────────────────────────────────────────────────────
PROVIDERS: dict[str, dict] = {
"anthropic": {
"type": "anthropic",
"api_key_env": "ANTHROPIC_API_KEY",
"context_limit": 200000,
"models": [
"claude-opus-4-6", "claude-sonnet-4-6", "claude-haiku-4-5-20251001",
"claude-opus-4-5", "claude-sonnet-4-5",
"claude-3-5-sonnet-20241022", "claude-3-5-haiku-20241022",
],
},
"openai": {
"type": "openai",
"api_key_env": "OPENAI_API_KEY",
"base_url": "https://api.openai.com/v1",
"context_limit": 128000,
"max_completion_tokens": 16384, # safe cap across gpt-4o/gpt-4.1 family
"models": [
"gpt-4o", "gpt-4o-mini", "gpt-4-turbo", "gpt-4.1", "gpt-4.1-mini",
"o3-mini", "o1", "o1-mini",
],
},
"gemini": {
"type": "openai",
"api_key_env": "GEMINI_API_KEY",
"base_url": "https://generativelanguage.googleapis.com/v1beta/openai/",
"context_limit": 1000000,
"max_completion_tokens": 65536, # Gemini 2.x supports up to 65k output tokens
"models": [
"gemini-2.5-pro-preview-03-25",
"gemini-2.0-flash", "gemini-2.0-flash-lite",
"gemini-1.5-pro", "gemini-1.5-flash",
],
},
"kimi": {
"type": "openai",
"api_key_env": "MOONSHOT_API_KEY",
"base_url": "https://api.moonshot.ai/v1",
"context_limit": 250000,
"models": [
"kimi-k2.5", "kimi-latest",
"moonshot-v1-8k", "moonshot-v1-32k", "moonshot-v1-128k",
],
},
"kimi-code": {
"type": "openai",
"api_key_env": "KIMI_CODE_API_KEY",
"base_url": "https://api.kimi.com/coding/v1",
"context_limit": 1_000_000,
# Official Kimi Code model IDs (kimi.com/code/docs → Model Configuration):
# k3 (up to 1M), k3-256k, kimi-for-coding (K2.7 Code, 256k).
"models": [
"k3", "k3-256k", "kimi-for-coding",
],
},
# Kimi membership OAuth (`/login kimi`) — same api.kimi.com/coding/v1 endpoint
# as kimi-code, but bills against the user's Kimi membership (no API key).
"kimi-oauth": {
"type": "kimi-oauth",
"api_key_env": None,
"base_url": "https://api.kimi.com/coding/v1",
"context_limit": 1_000_000,
"models": [
"k3", "k3-256k", "kimi-for-coding",
],
},
"qwen": {
"type": "openai",
"api_key_env": "DASHSCOPE_API_KEY",
"base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",
"context_limit": 1000000,
"models": [
"qwen-max", "qwen-plus", "qwen-turbo", "qwen-long",
"qwen2.5-72b-instruct", "qwen2.5-coder-32b-instruct",
"qwq-32b",
],
},
# Alibaba Cloud Model Studio (Singapore / ap-southeast-1). OpenAI-compatible
# endpoint scoped to a workspace. The base_url embeds your Workspace ID:
# https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
# Override the workspace without editing code via env/config:
# MODELSTUDIO_WORKSPACE_ID=ws-xxxx (or MODELSTUDIO_BASE_URL=<full url>)
# MODELSTUDIO_API_KEY=<key> (falls back to DASHSCOPE_API_KEY)
# Pick models as 'modelstudio/<model>' e.g. 'modelstudio/qwen-max'.
"modelstudio": {
"type": "openai",
"api_key_env": "MODELSTUDIO_API_KEY",
"base_url": "https://ws-1qcqvxk37njsah79.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
"context_limit": 1000000,
# qwen rejects max_tokens > 65536 (400 invalid_parameter). Cap output so a
# large config max_tokens (e.g. 1,000,000) doesn't blow up every call.
"max_completion_tokens": 32768,
# Ordered fallback chain (strongest → cheaper) of the free-quota LLM
# models in the Singapore plan. Override per-account with
# /config modelstudio_fallback_chain=<id>,<id>,...
# A wrong/retired id just falls through to the next one automatically.
"models": [
"qwen3-max", "qwen3.7-max", "qwen3.7-plus", "qwen3.6-plus",
"qwen3.5-plus-2026-04-20", "qwen3.6-flash", "qwen3.5-flash",
"qwen3.5-122b-a10b", "deepseek-v4-pro", "deepseek-v3.2", "glm-5.1",
],
},
# AMD Developer Cloud / ROCm. Serve any open model with vLLM (or TGI) on an
# AMD GPU instance — both expose an OpenAI-compatible /v1 endpoint. Point
# Dulus at it without editing code:
# AMD_BASE_URL=http://<instance-ip>:8000/v1 (your vLLM server)
# AMD_API_KEY=<token> (optional; vLLM accepts any value by default)
# Pick models as 'amd/<served-model-name>' e.g. 'amd/Qwen2.5-72B-Instruct'.
# The served name must match what you launched vLLM with (--served-model-name).
"amd": {
"type": "openai",
"api_key_env": "AMD_API_KEY",
"base_url": "", # resolved at call time from AMD_BASE_URL / config
"context_limit": 131072,
"models": [
"Qwen2.5-72B-Instruct", "Qwen2.5-Coder-32B-Instruct",
"Llama-3.3-70B-Instruct", "Mixtral-8x7B-Instruct",
],
},
"zhipu": {
"type": "openai",
"api_key_env": "ZHIPU_API_KEY",
"base_url": "https://api.z.ai/api/coding/paas/v4",
"context_limit": 128000,
"models": [
"glm-4-plus", "glm-4", "glm-4-flash", "glm-4-air",
"glm-z1-flash", "GLM-4.7", "GLM-4.5-AIR",
],
},
"dulus": {
# Fuel-backed models on the Dulus control plane. Sign in with
# `/login dulus` (OAuth PKCE — no API key) or mint a dulus_sk_* key
# with `/login dulus key` for CI/servers. The control plane maps the
# dulus-* tiers to upstream models and meters Fuel per token; the
# client never sees the upstream model name and holds no provider key.
"type": "dulus-oauth",
"api_key_env": None,
"base_url": "https://control.dulus.ai/v1",
"context_limit": 262144,
# 8k was too small: with thinking:max the model burns the whole
# completion budget on reasoning and the stream ends on
# finish_reason="length" with no answer and no tool call.
"max_completion_tokens": 32768,
"models": [
"dulus-a-9b", "dulus-b-27b", "dulus-x-397b",
"dulus-mistral-7b", "dulus-mistral-nemo", "dulus-gpt-oss-20b",
"dulus-mistral-small-24b", "dulus-qwen-32b", "dulus-coder-30b",
"dulus-llama-70b", "dulus-vl-72b", "dulus-gpt-oss-120b",
],
},
"deepseek": {
"type": "openai",
"api_key_env": "DEEPSEEK_API_KEY",
"base_url": "https://api.deepseek.com/v1",
"context_limit": 64000,
"models": [
"deepseek-chat", "deepseek-coder", "deepseek-reasoner",
"deepseek-v3", "deepseek-r1",
],
},
# Azure OpenAI (v1 OpenAI-compatible endpoint). Deployment name == model
# name. The endpoint is per-resource, so set it via your environment:
# AZURE_OPENAI_ENDPOINT=https://<your-resource>.cognitiveservices.azure.com
# AZURE_OPENAI_KEY=<your-key> (or: /config azure_api_key=...)
# Pick models as 'azure/<deployment-name>'. Also serves Kimi/other
# deployments hosted on Azure AI Foundry.
"azure": {
"type": "openai",
"api_key_env": "AZURE_OPENAI_KEY",
"base_url": "", # resolved at call time from AZURE_OPENAI_ENDPOINT / config
"context_limit": 128000,
"max_completion_tokens": 16384,
"models": [
"gpt-4.1-nano", "gpt-4.1-mini", "gpt-4.1", "gpt-4o", "gpt-4o-mini",
],
},
# LiteLLM unified gateway. ONE provider entry that fans out to 100+
# underlying backends via prefixed model strings:
# openrouter/anthropic/claude-3-5-sonnet
# groq/llama-3.3-70b-versatile
# together_ai/meta-llama/Llama-3-70b-chat-hf
# bedrock/anthropic.claude-3-sonnet-20240229-v1:0
# vertex_ai/gemini-1.5-pro
# cohere/command-r-plus
# perplexity/sonar-large-online
# xai/grok-2-latest
# mistral/mistral-large-latest
# fireworks_ai/... anyscale/... replicate/... azure/...
# LiteLLM auto-reads per-backend env vars (OPENROUTER_API_KEY,
# GROQ_API_KEY, TOGETHER_API_KEY, …). User picks the model string in
# the welcome wizard; the right env var must exist for that backend.
"litellm": {
"type": "litellm",
"api_key_env": None, # backend-specific; LiteLLM resolves the right one
"context_limit": 200000, # safe default; LiteLLM has accurate per-model values
"models": [
# A curated, useful slice — LiteLLM supports ~1000 model strings.
# The user can type any of them; these are just suggestions for /model picker.
"openrouter/anthropic/claude-3-5-sonnet",
"openrouter/openai/gpt-4o",
"openrouter/google/gemini-pro-1.5",
"openrouter/meta-llama/llama-3.3-70b-instruct",
"openrouter/x-ai/grok-2-1212",
"groq/llama-3.3-70b-versatile",
"groq/mixtral-8x7b-32768",
"together_ai/meta-llama/Llama-3-70b-chat-hf",
"perplexity/sonar-large-online",
"cohere/command-r-plus",
"mistral/mistral-large-latest",
"fireworks_ai/accounts/fireworks/models/llama-v3p3-70b-instruct",
],
},
"minimax": {
"type": "openai",
"api_key_env": "MINIMAX_API_KEY",
"base_url": "https://api.minimaxi.chat/v1",
"context_limit": 1000000,
"models": [
"MiniMax-Text-01", "MiniMax-VL-01",
"abab6.5s-chat", "abab6.5-chat",
"abab5.5s-chat", "abab5.5-chat",
],
},
"ollama": {
"type": "ollama",
"api_key_env": None,
"base_url": "http://localhost:11434",
"api_key": "ollama",
"context_limit": 250000,
"models": [
"gemma4", "qwen3", "qwen2.5-coder", "llama3.3",
"deepseek-r1", "mistral",
],
},
"lmstudio": {
"type": "openai",
"api_key_env": None,
"base_url": "http://localhost:1234/v1",
"api_key": "lm-studio",
"context_limit": 128000,
"models": [], # dynamic, depends on loaded model
},
"edge": {
# Local / on-device small models over an OpenAI-compatible endpoint. The
# provider is backend-agnostic — ANY server that speaks OpenAI on
# 127.0.0.1 works. Three ways to feed it, easiest first:
# • llama.cpp: llama-server -m gemma-3-1b-it-Q4_K_M.gguf --port 8080
# (works today, runs anywhere: desktop, VM, Termux/phone)
# • Ollama: ollama serve
# (then /config edge_base_url=http://127.0.0.1:11434/v1)
# • Dulus Edge Bridge APK — on-device Gemma on Android via AICore
# (NPU-accelerated, zero-download). WORK IN PROGRESS: the Android
# build takes time; llama.cpp/Ollama is the path that ships now.
# The requested model name is just a label — llama-server serves whatever
# weights you loaded with -m. Override host/port (Termux, a phone on your
# LAN) with DULUS_EDGE_BASE_URL or `/config edge_base_url=http://HOST:PORT/v1`.
"type": "openai",
"api_key_env": None,
"base_url": "http://127.0.0.1:8080/v1",
"api_key": "dulus-edge",
"context_limit": 32000,
"models": [
# llama.cpp / Ollama GGUFs — the path that works today.
"gemma-3n-e4b", "gemma-3n-e2b",
# Dulus Edge Bridge APK (on-device Android) — WIP.
"gemma-4-e4b", "gemma-4-e2b", "gemini-nano",
],
},
"nvidia-web": {
"type": "openai",
"api_key_env": "NVIDIA_API_KEY",
"base_url": "https://integrate.api.nvidia.com/v1",
"context_limit": 128000,
"max_completion_tokens": 16384,
"models": [
"deepseek-ai/deepseek-v4-flash",
"deepseek-ai/deepseek-r1",
"meta/llama-3.3-70b-instruct",
"nvidia/llama-3.1-nemotron-70b-instruct",
"mistralai/mixtral-8x22b-instruct-v0.1",
"microsoft/phi-3-medium-128k-instruct",
"stepfun-ai/step-3.5-flash",
"qwen/qwen2.5-72b-instruct",
"google/gemma-2-27b-it",
],
},
"gcloud": {
"type": "gcloud",
"api_key_env": None,
"context_limit": 1000000,
"max_completion_tokens": 65536,
"models": [
"gemini-2.5-pro",
"gemini-2.0-flash",
"gemini-1.5-pro",
],
},
"xai-oauth": {
"type": "xai-oauth",
"api_key_env": None,
"context_limit": 128000,
"models": [
"grok-4", "grok-3", "grok-2-latest", "grok-beta", "grok-build",
],
},
# ChatGPT / Codex subscription OAuth (`/login chatgpt` or reuse ~/.codex/auth.json).
# Hits chatgpt.com/backend-api/codex (Responses API) — NOT api.openai.com.
# Usage bills against the ChatGPT plan, not platform API credits.
"chatgpt-oauth": {
"type": "chatgpt-oauth",
"api_key_env": None,
"base_url": "https://chatgpt.com/backend-api/codex",
"context_limit": 200000,
"models": [
# Keep model IDs bare. The picker adds `chatgpt-oauth/`; embedding
# `chatgpt/` here produced malformed `chatgpt-oauth/chatgpt/...`.
"gpt-5.6-sol", "gpt-5.6-sol-pro", "gpt-5.6-terra", "gpt-5.6-luna",
"gpt-5.5", "gpt-5.4", "gpt-5.4-mini",
"gpt-5.1-codex", "gpt-5.1-codex-mini",
"codex-mini-latest", "o3", "o4-mini",
],
},
"xiaomi": {
"type": "openai_compat",
"api_key_env": "XIAOMI_API_KEY",
"base_url": "https://api.xiaomimimo.com/v1",
"context_limit": 128000,
"models": [
"mimo-v2.5", "mimo-v2.5-pro", "mimo-v2-omni", "MiMo-V2-Pro",
],
# Quirks ripped from open Hermes Xiaomi provider:
# - supports_vision=True but supports_vision_tool_messages=False (rejects list tool content)
# - health check /v1/models returns 401 even with key
# - thinking mode support on some variants
},
"sakana": {
"type": "openai",
"api_key_env": "SAKANA_API_KEY",
"base_url": "https://api.sakana.ai/v1",
"context_limit": 128000,
"models": [
"fugu-mini", "fugu-ultra",
],
},
# Meta AI (Muse Spark) — Responses-API-style SSE endpoint at api.meta.ai.
# Key via /config meta_api_key=... or export META_API_KEY.
# Pick models as 'meta/muse-spark-1.3' (or bare 'muse-spark-1.3').
"meta": {
"type": "meta",
"api_key_env": "META_API_KEY",
"base_url": "https://api.meta.ai/v1",
"context_limit": 128000,
"max_completion_tokens": 32000,
"models": [
"muse-spark-1.3", "muse-spark-1.3-contributor",
],
},
}
# Cost per million tokens (approximate, fallback to 0 for unknown)
COSTS = {
"claude-opus-4-6": (15.0, 75.0),
"claude-sonnet-4-6": (3.0, 15.0),
"claude-haiku-4-5-20251001": (0.8, 4.0),
"gpt-4o": (2.5, 10.0),
"gpt-4o-mini": (0.15, 0.6),
"o3-mini": (1.1, 4.4),
"gemini-2.0-flash": (0.075, 0.3),
"gemini-1.5-pro": (1.25, 5.0),
"gemini-2.5-pro-preview-03-25": (1.25, 10.0),
"moonshot-v1-8k": (1.0, 3.0),
"moonshot-v1-32k": (2.4, 7.0),
"moonshot-v1-128k": (8.0, 24.0),
"qwen-max": (2.4, 9.6),
"qwen-plus": (0.4, 1.2),
"deepseek-chat": (0.27, 1.1),
"deepseek-reasoner": (0.55, 2.19),
"glm-4-plus": (0.7, 0.7),
"GLM-4.7": (0.7, 0.7),
"GLM-4.5-AIR": (0.5, 0.5),
"MiniMax-Text-01": (0.7, 2.1),
"abab6.5s-chat": (0.1, 0.1),
"abab6.5-chat": (0.5, 0.5),
"gcloud/gemini-2.5-pro": (1.25, 10.0),
"gcloud/gemini-2.0-flash": (0.075, 0.3),
"gcloud/gemini-1.5-pro": (1.25, 5.0),
# Edge / local (llama.cpp, Ollama, on-device APK) — no per-token cost.
"gemma-3n-e4b": (0.0, 0.0),
"gemma-3n-e2b": (0.0, 0.0),
"gemma-4-e4b": (0.0, 0.0),
"gemma-4-e2b": (0.0, 0.0),
"gemini-nano": (0.0, 0.0),
}
# Auto-detection: prefix → provider name
_PREFIXES = [
# Dulus account models (Fuel-metered control plane, /login dulus) — MUST
# precede the generic mistral/qwen/llama→ollama rules below, or ids like
# dulus-mistral-7b would route to a local Ollama instead of the Dulus
# control plane. Order matters: first match wins.
("dulus/", "dulus"),
("dulus-", "dulus"),
# ChatGPT/Codex subscription (OAuth) — MUST precede the generic "gpt-"→openai
# rule below, or gpt-5.x / codex-* ids route to the paid API instead of the
# user's ChatGPT plan. Order matters: first match wins.
("chatgpt/", "chatgpt-oauth"),
("chatgpt-", "chatgpt-oauth"),
("codex/", "chatgpt-oauth"),
("codex-", "chatgpt-oauth"),
("gpt-5.6", "chatgpt-oauth"),
("gpt-5.5", "chatgpt-oauth"),
("gpt-5.4", "chatgpt-oauth"),
("gpt-5.1-codex", "chatgpt-oauth"),
("gpt-5-codex", "chatgpt-oauth"),
("codex-mini", "chatgpt-oauth"),
("codex-auto", "chatgpt-oauth"),
# Meta AI (Muse Spark) — api.meta.ai Responses-style SSE, key via META_API_KEY.
("meta/", "meta"),
("muse-", "meta"),
("claude-", "anthropic"),
("gpt-", "openai"),
("o1", "openai"),
("o3", "openai"),
# Edge / local small models over an OpenAI-compatible server (llama.cpp
# `llama-server`, Ollama, or the WIP Dulus Edge Bridge APK). MUST precede the
# gemini-/gemma cloud+ollama rules below so these win. Arbitrary GGUFs are
# reachable with the explicit `edge/<name>` prefix.
("edge/", "edge"),
("gemini-nano", "edge"),
("gemma-3n", "edge"),
("gemma-4", "edge"),
("gemini-", "gemini"),
("kimi-code/", "kimi-code"),
("kimi-for-coding", "kimi-code"),
("kimi", "kimi"), # matches 'kimi-' and 'kimi'
("moonshot-", "kimi"),
("moonshot", "kimi"),
("qwen", "qwen"), # qwen-max, qwen2.5-...
("qwq-", "qwen"),
("glm-", "zhipu"),
("GLM-", "zhipu"),
("deepseek-", "deepseek"),
("minimax-", "minimax"),
("MiniMax-", "minimax"),
("abab", "minimax"),
("llama", "ollama"),
("mistral", "ollama"),
("phi", "ollama"),
("gemma", "ollama"),
("gcloud/", "gcloud"),
("gcloud-", "gcloud"),
("grok-", "xai-oauth"),
("grok-build", "xai-oauth"),
("xai-", "xai-oauth"),
("xai-oauth", "xai-oauth"),
("xiaomi-", "xiaomi"),
("mimo-", "xiaomi"),
("xiaomi", "xiaomi"),
("fugu-", "sakana"),
("sakana-", "sakana"),
]
def detect_provider(model: str) -> str:
"""Return provider name for a model string.
Supports 'provider/model' explicit format, or auto-detect by prefix."""
if "/" in model:
p = model.split("/", 1)[0]
if p in PROVIDERS:
return p
for prefix, pname in _PREFIXES:
if model.lower().startswith(prefix):
return pname
return "openai" # fallback
XAI_OAUTH_CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828"
XAI_OAUTH_SCOPE = "openid profile email offline_access grok-cli:access api:access"
XAI_OAUTH_ISSUER = "https://auth.x.ai"
XAI_OAUTH_DISCOVERY_URL = f"{XAI_OAUTH_ISSUER}/.well-known/openid-configuration"
XAI_OAUTH_REDIRECT_HOST = "127.0.0.1"
XAI_OAUTH_REDIRECT_PORT = 56121
XAI_OAUTH_REDIRECT_PATH = "/callback"
XAI_OAUTH_BASE_URL = "https://api.x.ai/v1"