-
-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathmodels.py
More file actions
1980 lines (1691 loc) · 75.3 KB
/
models.py
File metadata and controls
1980 lines (1691 loc) · 75.3 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
import contextvars
from dataclasses import dataclass
import ipaddress
import json
import logging
import os
import pathlib
import threading
from urllib.parse import urlparse
import urllib.error
import urllib.request
try:
import ollama as _ollama_mod
except ImportError:
_ollama_mod = None # type: ignore[assignment]
try:
from langchain_ollama import ChatOllama
except ImportError:
ChatOllama = None # type: ignore[assignment,misc]
logger = logging.getLogger(__name__)
# ── Cloud provider URLs ─────────────────────────────────────────────────────
OPENAI_BASE_URL = "https://api.openai.com/v1"
OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"
ANTHROPIC_BASE_URL = "https://api.anthropic.com/v1"
GOOGLE_GENAI_BASE_URL = "https://generativelanguage.googleapis.com/v1beta"
XAI_BASE_URL = "https://api.x.ai/v1"
MINIMAX_ANTHROPIC_BASE_URL = "https://api.minimax.io/anthropic"
OLLAMA_CLOUD_BASE_URL = "https://ollama.com"
# ── Context-size heuristics (prefix-match, checked top-to-bottom) ───────────
# Used when the provider API doesn't expose context_length (e.g. OpenAI) and
# the model isn't in the OpenRouter cross-reference cache. More-specific
# prefixes must come before shorter ones. Covers OpenAI, Anthropic & Gemini.
_CONTEXT_HEURISTICS: list[tuple[str, int]] = [
# ── OpenAI ────────────────────────────────────────────────────────
("gpt-4.1", 1_048_576), # gpt-4.1 / mini / nano — 1M
("gpt-4.5", 1_048_576), # gpt-4.5 family — 1M
("gpt-5", 1_048_576), # gpt-5 / 5.4 etc — 1M
("gpt-4o", 128_000), # gpt-4o / 4o-mini — 128K
("gpt-4-turbo", 128_000), # gpt-4-turbo — 128K
("gpt-4", 8_192), # base gpt-4 (legacy) — 8K
("gpt-3.5", 16_385), # gpt-3.5-turbo — 16K
("o1", 200_000), # o1 / o1-mini / o1-pro — 200K
("o3", 200_000), # o3 / o3-mini / o3-pro — 200K
("o4", 200_000), # o4-mini etc — 200K
("chatgpt-", 128_000), # chatgpt- aliases — 128K
# ── Anthropic ─────────────────────────────────────────────────────
("claude-opus-4", 1_000_000), # Opus 4.x — 1M
("claude-sonnet-4",1_000_000), # Sonnet 4.x — 1M
("claude-haiku-4", 200_000), # Haiku 4.x — 200K
("claude-3-5", 200_000), # Claude 3.5 family — 200K
("claude-3", 200_000), # Claude 3 family — 200K
("claude-2", 100_000), # Claude 2.x (legacy) — 100K
("claude", 200_000), # Catch-all Claude — 200K
# ── Google Gemini ─────────────────────────────────────────────────
("gemini-3", 1_048_576), # Gemini 3.x — 1M
("gemini-2.5", 1_048_576), # Gemini 2.5 Flash/Pro — 1M
("gemini-2.0", 1_048_576), # Gemini 2.0 — 1M
("gemini-1.5-pro", 2_097_152), # Gemini 1.5 Pro — 2M
("gemini-1.5", 1_048_576), # Gemini 1.5 Flash — 1M
("gemini-1.0", 32_768), # Legacy Gemini 1.0 — 32K
("gemini", 1_048_576), # Catch-all Gemini — 1M
# ── xAI (Grok) ─────────────────────────────────────────────────────
("grok-4", 2_000_000), # Grok 4 / 4.20 — 2M
("grok-3", 131_072), # Grok 3 & 3-mini — 131K
("grok-2", 131_072), # Grok 2 family — 131K
("grok", 131_072), # Catch-all Grok — 131K
# ── MiniMax ──────────────────────────────────────────────────────
("minimax-m2", 204_800), # MiniMax M2.x Anthropic-compatible models
]
_CLOUD_CONTEXT_FALLBACK = 256_000 # safe default for totally unknown models
def _estimate_context_heuristic(model_name: str) -> int:
"""Guess context size from the model name using prefix heuristics.
Strips any ``provider/`` prefix (e.g. ``openai/gpt-4o`` → ``gpt-4o``)
before matching. Returns ``_CLOUD_CONTEXT_FALLBACK`` if nothing matches.
"""
bare = _runtime_model_name(model_name).split("/")[-1].lower() # strip provider/ slug
for prefix, ctx in _CONTEXT_HEURISTICS:
if bare.startswith(prefix):
return ctx
return _CLOUD_CONTEXT_FALLBACK
def _parse_provider_model_ref(model_name: str | None) -> tuple[str, str] | None:
try:
from providers.selection import parse_model_ref
return parse_model_ref(model_name)
except Exception:
return None
def _runtime_model_name(model_name: str | None) -> str:
raw = str(model_name or "")
parsed = _parse_provider_model_ref(raw)
return parsed[1] if parsed else raw
def _provider_qualified_cloud_cache_key(provider_id: str | None, model_id: str | None) -> str:
provider = str(provider_id or "").strip()
model = str(model_id or "").strip()
return f"model:{provider}:{model}" if provider and model else ""
def _cloud_cache_entry_for(model_name: str | None, provider_id: str | None = None) -> dict | None:
parsed = _parse_provider_model_ref(model_name)
runtime_model = _runtime_model_name(model_name)
provider = provider_id or (parsed[0] if parsed else None)
qualified_key = _provider_qualified_cloud_cache_key(provider, runtime_model)
if qualified_key:
info = _cloud_model_cache.get(qualified_key)
if isinstance(info, dict):
cached_provider = str(info.get("provider") or "")
if not cached_provider or cached_provider == provider:
return info
info = _cloud_model_cache.get(runtime_model)
if isinstance(info, dict):
cached_provider = str(info.get("provider") or "")
if not provider or not cached_provider or cached_provider == provider:
return info
return None
# Prefixes considered chat-capable when filtering OpenAI /v1/models
_OPENAI_CHAT_PREFIXES = ("gpt-", "o1", "o3", "o4", "chatgpt-")
# Substrings that indicate a non-chat model — skip these
_OPENAI_SKIP_SUBSTRINGS = ("dall-e", "whisper", "tts", "embedding", "davinci",
"babbage", "moderation", "realtime", "audio",
"transcri", "search")
# ── Dynamic cloud model cache ───────────────────────────────────────────────
_cloud_model_cache: dict[str, dict] = {} # model_id → {label, ctx, provider}
_cloud_cache_lock = threading.Lock()
# ── Context catalog (keyless OpenRouter public data) ────────────────────────
_context_catalog: dict[str, int] = {} # model_id → context_length
_context_catalog_lock = threading.Lock()
# ── Deprecated Ollama discovery cache (kept as inert compatibility state) ───
_trending_ollama_cache: list[str] = []
_trending_fetched: bool = False
DEFAULT_MODEL = "qwen3:14b"
DEFAULT_CONTEXT_SIZE = 32768
CONTEXT_SIZE_OPTIONS = [16384, 32768, 65536, 131072, 262144]
CONTEXT_SIZE_LABELS = {16384: "16K", 32768: "32K",
65536: "64K", 131072: "128K", 262144: "256K"}
# Cloud-model context options (user-selectable cap — reduces cost / rate-limit pressure)
DEFAULT_CLOUD_CONTEXT_SIZE = 131072 # 128K — safe default for most API tiers
CLOUD_CONTEXT_SIZE_OPTIONS = [32768, 65536, 131072, 262144, 524288, 1048576]
CLOUD_CONTEXT_SIZE_LABELS = {
32768: "32K", 65536: "64K", 131072: "128K",
262144: "256K", 524288: "512K", 1048576: "1M",
}
# ── Persistent settings file ────────────────────────────────────────────────
def _coerce_context_size(
value,
default: int,
*,
allowed: list[int] | tuple[int, ...] | None = None,
minimum: int | None = None,
) -> int:
"""Return a numeric context size from persisted/UI values."""
fallback = int(default or 0)
try:
if isinstance(value, bool):
raise ValueError
if isinstance(value, (int, float)):
parsed = int(value)
else:
text = str(value or "").strip().lower().replace(",", "").replace("_", "")
multiplier = 1
if text.endswith("k"):
multiplier = 1_000
text = text[:-1]
elif text.endswith("m"):
multiplier = 1_000_000
text = text[:-1]
parsed = int(float(text) * multiplier)
except (TypeError, ValueError):
parsed = fallback
if allowed:
allowed_ints = sorted(int(item) for item in allowed)
if parsed in allowed_ints:
return parsed
if parsed < allowed_ints[0]:
return allowed_ints[0]
return min(allowed_ints, key=lambda item: abs(item - parsed))
if minimum is not None and parsed < int(minimum):
return int(minimum)
return parsed if parsed > 0 else fallback
_DATA_DIR = pathlib.Path(os.environ.get("THOTH_DATA_DIR", pathlib.Path.home() / ".thoth"))
_SETTINGS_PATH = _DATA_DIR / "model_settings.json"
_CLOUD_CACHE_PATH = _DATA_DIR / "cloud_models_cache.json"
_CONTEXT_CATALOG_PATH = _DATA_DIR / "context_catalog_cache.json"
def _load_settings() -> dict:
"""Load persisted model settings, or return defaults."""
try:
if _SETTINGS_PATH.exists():
return json.loads(_SETTINGS_PATH.read_text())
except Exception:
logger.warning("Failed to load model settings from %s", _SETTINGS_PATH, exc_info=True)
return {}
def _save_settings(settings: dict):
"""Persist model settings to disk."""
_DATA_DIR.mkdir(parents=True, exist_ok=True)
_SETTINGS_PATH.write_text(json.dumps(settings, indent=2))
def _load_cloud_cache() -> dict:
"""Load persisted cloud model cache from disk."""
try:
if _CLOUD_CACHE_PATH.exists():
data = json.loads(_CLOUD_CACHE_PATH.read_text())
if isinstance(data, dict):
return data
except Exception:
logger.warning("Failed to load cloud cache from %s", _CLOUD_CACHE_PATH, exc_info=True)
return {}
def _save_cloud_cache():
"""Persist current cloud model cache to disk."""
try:
_DATA_DIR.mkdir(parents=True, exist_ok=True)
with _cloud_cache_lock:
_CLOUD_CACHE_PATH.write_text(json.dumps(_cloud_model_cache))
except Exception:
logger.warning("Failed to save cloud cache to %s", _CLOUD_CACHE_PATH, exc_info=True)
def _load_context_catalog() -> dict[str, int]:
"""Load persisted context catalog from disk."""
try:
if _CONTEXT_CATALOG_PATH.exists():
data = json.loads(_CONTEXT_CATALOG_PATH.read_text())
if isinstance(data, dict):
return data
except Exception:
logger.warning("Failed to load context catalog from %s",
_CONTEXT_CATALOG_PATH, exc_info=True)
return {}
def _save_context_catalog():
"""Persist current context catalog to disk."""
try:
_DATA_DIR.mkdir(parents=True, exist_ok=True)
with _context_catalog_lock:
_CONTEXT_CATALOG_PATH.write_text(json.dumps(_context_catalog))
except Exception:
logger.warning("Failed to save context catalog to %s",
_CONTEXT_CATALOG_PATH, exc_info=True)
# Initialise from saved settings (fall back to defaults for first run)
_saved = _load_settings()
# Load persisted cloud cache so is_cloud_model() works before refresh
_cloud_model_cache.update(_load_cloud_cache())
# Load persisted context catalog so context resolution works before live fetch
_context_catalog.update(_load_context_catalog())
POPULAR_MODELS = [
# ── Qwen family ──────────────────────────────────────────────────────
"qwen3:8b", "qwen3:14b", "qwen3:30b", "qwen3:32b", "qwen3:235b",
"qwen3.5:9b", "qwen3.5:27b", "qwen3.5:35b", "qwen3.5:122b",
"qwen3-coder:30b",
# ── Llama family ─────────────────────────────────────────────────────
"llama3.1:8b", "llama3.1:70b", "llama3.1:405b",
"llama3.3:70b",
"llama3-groq-tool-use:8b", "llama3-groq-tool-use:70b",
# ── Mistral family ───────────────────────────────────────────────────
"mistral:7b",
"mistral-nemo:12b",
"mistral-small:22b", "mistral-small:24b",
"mistral-small3.1:24b",
"mistral-small3.2:24b",
"mistral-large:123b",
"mixtral:8x7b", "mixtral:8x22b",
"magistral:24b",
"ministral-3:8b", "ministral-3:14b",
# ── Other tool-capable models ────────────────────────────────────────
"rnj-1:8b",
"glm-4.7-flash:30b",
"nemotron-3-nano:30b",
"nemotron:70b",
"devstral-small-2:24b",
"devstral-2:123b",
"olmo-3.1:32b",
"lfm2:24b",
"gpt-oss:20b", "gpt-oss:120b",
"firefunction-v2:70b",
]
# Set of all model *family* prefixes known to support Ollama tool calling.
# Used to flag downloaded models NOT in this set with a ⚠️ warning.
_TOOL_COMPATIBLE_FAMILIES: set[str] = {
m.split(":")[0] for m in POPULAR_MODELS
}
try:
from providers.selection import model_choice_value as _canonical_model_choice_value
_current_model = _canonical_model_choice_value(_saved.get("model", DEFAULT_MODEL))
except Exception:
_current_model = _saved.get("model", DEFAULT_MODEL)
_num_ctx = _coerce_context_size(
_saved.get("context_size", DEFAULT_CONTEXT_SIZE),
DEFAULT_CONTEXT_SIZE,
allowed=CONTEXT_SIZE_OPTIONS,
)
_cloud_num_ctx = _coerce_context_size(
_saved.get("cloud_context_size", DEFAULT_CLOUD_CONTEXT_SIZE),
DEFAULT_CLOUD_CONTEXT_SIZE,
allowed=CLOUD_CONTEXT_SIZE_OPTIONS,
)
_llm_instance = None
_model_max_ctx_cache: dict[str, int | None] = {} # model_name → max context
@dataclass(frozen=True)
class ContextPolicy:
model_ref: str
provider_id: str
runtime_model: str
native_max: int | None
user_cap: int
effective_context: int
policy_kind: str
cap_source: str
request_application: str
def _normalize_ollama_client_host(host: str) -> str:
normalized = (host or "127.0.0.1").strip()
if normalized == "0.0.0.0":
return "127.0.0.1"
if normalized == "::":
return "::1"
return normalized
def _format_ollama_base_url(host: str, port: int, scheme: str = "http") -> str:
formatted_host = host
try:
if isinstance(ipaddress.ip_address(host), ipaddress.IPv6Address):
formatted_host = f"[{host}]"
except ValueError:
pass
return f"{scheme or 'http'}://{formatted_host}:{port}"
def _ollama_endpoint_parts() -> tuple[str, int, str]:
raw = (os.environ.get("OLLAMA_HOST") or "127.0.0.1").strip() or "127.0.0.1"
parsed = urlparse(raw if "://" in raw else f"//{raw}")
host = _normalize_ollama_client_host(parsed.hostname or raw)
try:
port = parsed.port or 11434
except ValueError:
port = 11434
return host, port, parsed.scheme or "http"
def _ollama_base_url() -> str:
"""Return a client-safe Ollama base URL derived from OLLAMA_HOST."""
host, port, scheme = _ollama_endpoint_parts()
return _format_ollama_base_url(host, port, scheme)
def _ollama_client():
if not _ollama_mod:
return None
client_factory = getattr(_ollama_mod, "Client", None)
if callable(client_factory):
return client_factory(host=_ollama_base_url())
return _ollama_mod
def _ollama_http_json(path: str, payload: dict | None = None, *, timeout: float = 4.0) -> dict:
url = f"{_ollama_base_url().rstrip('/')}/{str(path or '').lstrip('/')}"
data = None
headers = {"Accept": "application/json"}
if payload is not None:
data = json.dumps(payload).encode("utf-8")
headers["Content-Type"] = "application/json"
request = urllib.request.Request(url, data=data, headers=headers, method="POST" if payload is not None else "GET")
with urllib.request.urlopen(request, timeout=timeout) as response:
raw = response.read()
parsed = json.loads(raw.decode("utf-8") or "{}")
return parsed if isinstance(parsed, dict) else {}
def _chat_ollama(model: str, **kwargs):
if ChatOllama is None:
raise RuntimeError("langchain-ollama is not installed")
if "reasoning" not in kwargs:
try:
from providers.ollama import is_ollama_reasoning_model
if is_ollama_reasoning_model(model):
kwargs["reasoning"] = True
except Exception:
pass
return ChatOllama(model=model, base_url=_ollama_base_url(), **kwargs)
def get_llm():
"""Return the current LLM instance, creating one if needed.
If the default model is a cloud model, returns the appropriate
``ChatOpenAI`` instance. Otherwise returns ``ChatOllama``.
"""
global _llm_instance
if _llm_instance is None:
if is_cloud_model(_current_model):
_llm_instance = _get_cloud_llm(_current_model)
else:
runtime_model = _runtime_model_name(_current_model)
num_ctx = _local_num_ctx_for(_current_model)
logger.info("Creating LLM instance: model=%s, num_ctx=%s", runtime_model, num_ctx)
_llm_instance = _chat_ollama(model=runtime_model, num_ctx=num_ctx)
return _llm_instance
_override_llm_cache: dict[tuple[str, int], object] = {} # model → ChatOllama or ChatOpenAI
def clear_llm_cache() -> None:
"""Drop cached chat model clients so provider credential changes take effect."""
global _llm_instance
_llm_instance = None
_override_llm_cache.clear()
def _local_num_ctx_for(model_name: str | None) -> int:
"""Return the Ollama ``num_ctx`` after applying native model caps."""
model_max = get_model_max_context(model_name)
user_ctx = _coerce_context_size(_num_ctx, DEFAULT_CONTEXT_SIZE, minimum=CONTEXT_SIZE_OPTIONS[0])
model_ctx = _coerce_context_size(model_max, 0) if model_max else None
return min(model_ctx, user_ctx) if model_ctx and model_ctx > 0 else user_ctx
def get_llm_for(model_name: str, num_ctx: int | None = None):
"""Return an LLM for a specific model (not the global singleton).
For local (Ollama) models, returns a ``ChatOllama``.
For cloud (OpenRouter) models, returns a ``ChatOpenAI`` pointed at
the OpenRouter API. Results are cached per (model, ctx) pair.
"""
if is_cloud_model(model_name):
return _get_cloud_llm(model_name)
runtime_model = _runtime_model_name(model_name)
if num_ctx is None:
num_ctx = _local_num_ctx_for(model_name)
key = (runtime_model, num_ctx)
if key not in _override_llm_cache:
logger.info("Creating override LLM: model=%s, num_ctx=%s", runtime_model, num_ctx)
_override_llm_cache[key] = _chat_ollama(model=runtime_model, num_ctx=num_ctx)
return _override_llm_cache[key]
def get_model_max_context(model_name: str | None = None) -> int | None:
"""Query Ollama for the model's native max context length.
For cloud models, returns the hardcoded context size from the catalog.
Returns the context_length from model metadata, or *None* if it
cannot be determined. Results are cached per model name.
"""
raw_name = model_name or _current_model
resolved = _resolved_context_identity(raw_name)
if resolved and resolved.provider_id.startswith("custom_openai_"):
endpoint = resolved.endpoint or {}
models = endpoint.get("models") if isinstance(endpoint, dict) else []
if isinstance(models, list):
for item in models:
if not isinstance(item, dict):
continue
item_model = str(item.get("model_id") or item.get("id") or "")
if item_model != resolved.runtime_model:
continue
ctx = _coerce_context_size(item.get("context_window") or item.get("ctx"), 0)
return ctx if ctx > 0 else None
probe = endpoint.get("last_probe") if isinstance(endpoint.get("last_probe"), dict) else {}
ctx = _coerce_context_size(probe.get("context_window"), 0)
return ctx if ctx > 0 else None
if is_cloud_model(raw_name):
return get_cloud_model_context(raw_name)
name = _runtime_model_name(raw_name)
if name in _model_max_ctx_cache:
return _model_max_ctx_cache[name]
client = _ollama_client()
metadata: dict | None = None
try:
if client:
info = client.show(name)
metadata = getattr(info, "modelinfo", None) or getattr(info, "model_info", None) or {}
except Exception:
logger.debug("Could not query max context for model %s", name, exc_info=True)
if metadata is None:
try:
info = _ollama_http_json("/api/show", {"model": name})
metadata = info.get("model_info") or info.get("modelinfo") or {}
except Exception:
logger.debug("Could not query max context over Ollama HTTP for model %s", name, exc_info=True)
metadata = {}
arch = str(metadata.get("general.architecture") or "")
ctx = metadata.get(f"{arch}.context_length") if arch else None
if ctx is None:
for key, value in metadata.items():
if str(key).endswith(".context_length"):
ctx = value
break
try:
_model_max_ctx_cache[name] = int(ctx) if ctx is not None else None
except (TypeError, ValueError):
_model_max_ctx_cache[name] = None
return _model_max_ctx_cache[name]
def set_model(model_name: str):
"""Switch the active model. Accepts both local Ollama and cloud model IDs.
For local models: unloads the previous model from Ollama's VRAM.
For cloud models: just updates the setting (no Ollama interaction).
"""
global _current_model, _llm_instance
if model_name != _current_model:
logger.info("Switching model: %s → %s", _current_model, model_name)
# Unload previous local model from Ollama memory
client = _ollama_client()
if not is_cloud_model(_current_model) and client:
try:
client.generate(model=_runtime_model_name(_current_model), prompt="", keep_alive=0)
except Exception:
logger.debug("Could not unload previous model %s", _current_model, exc_info=True)
_current_model = model_name
if is_cloud_model(model_name):
_llm_instance = _get_cloud_llm(model_name)
else:
_llm_instance = _chat_ollama(
model=_runtime_model_name(model_name),
num_ctx=_local_num_ctx_for(model_name),
)
_save_settings({"model": _current_model, "context_size": _num_ctx,
"cloud_context_size": _cloud_num_ctx})
# Thread-local model override — allows agent.py to propagate the per-thread
# cloud model override so that get_context_size() (and everything downstream:
# get_tool_budget, _keep_browser_snapshots, tool budgets) automatically uses
# the correct context window without every caller needing an explicit argument.
_active_model_override: contextvars.ContextVar[str] = contextvars.ContextVar(
"active_model_override", default=""
)
def set_active_model_override(name: str) -> None:
"""Set the thread-local model override (called by agent.py before execution)."""
_active_model_override.set(name)
def _resolved_context_identity(model_name: str):
try:
from providers.resolution import resolve_provider_config
return resolve_provider_config(model_name, allow_legacy_local=True)
except Exception:
return None
def get_context_policy(model_name: str | None = None) -> ContextPolicy:
"""Return the resolved context policy for the given (or active) model."""
name = model_name or _active_model_override.get() or _current_model
resolved = _resolved_context_identity(name)
provider_id = resolved.provider_id if resolved else (get_cloud_provider(name) or "ollama")
runtime_model = resolved.runtime_model if resolved else _runtime_model_name(name)
model_ref_value = resolved.selection_ref if resolved else name
remote_policy = bool(resolved and resolved.execution_location != "local") or is_cloud_model(name)
if resolved and resolved.execution_location == "local" and provider_id.startswith("custom_openai_"):
remote_policy = False
user_cap = _coerce_context_size(
_cloud_num_ctx if remote_policy else _num_ctx,
DEFAULT_CLOUD_CONTEXT_SIZE if remote_policy else DEFAULT_CONTEXT_SIZE,
minimum=(CLOUD_CONTEXT_SIZE_OPTIONS[0] if remote_policy else CONTEXT_SIZE_OPTIONS[0]),
)
model_max = get_model_max_context(name)
model_max_int = _coerce_context_size(model_max, 0) if model_max else 0
native_max = model_max_int if model_max_int > 0 else None
cap_source = "provider_metadata" if native_max else "unknown"
if native_max is None and remote_policy:
native_max = _estimate_context_heuristic(runtime_model)
cap_source = "heuristic"
if native_max is None and provider_id.startswith("custom_openai_"):
endpoint = resolved.endpoint if resolved else {}
fallback_context = int(endpoint.get("unknown_context_fallback") or 0) if isinstance(endpoint, dict) else 0
if fallback_context > 0:
native_max = fallback_context
cap_source = "profile_default"
effective = int(min(user_cap, native_max) if native_max else user_cap)
if provider_id == "ollama" and not remote_policy:
request_application = "ollama_num_ctx"
elif provider_id.startswith("custom_openai_"):
endpoint = resolved.endpoint if resolved else {}
context_param = str(endpoint.get("context_param_name") or "")
if endpoint.get("supports_runtime_context_override") and context_param:
request_application = f"request_param:{context_param}"
else:
request_application = "trim_only"
else:
request_application = "trim_only"
return ContextPolicy(
model_ref=model_ref_value,
provider_id=provider_id,
runtime_model=runtime_model,
native_max=int(native_max) if native_max else None,
user_cap=int(user_cap),
effective_context=effective,
policy_kind="provider" if remote_policy else "local",
cap_source=cap_source,
request_application=request_application,
)
def get_context_size(model_name: str | None = None) -> int:
"""Return the *effective* context size for the given (or current) model.
- **Cloud models** use ``min(user_cloud_cap, model_native_max)``.
The user-configurable cap reduces cost and rate-limit pressure.
- **Local (Ollama) models** use ``min(user_setting, model_native_max)``
because ``num_ctx`` directly controls VRAM usage.
Resolution order for the model name:
1. Explicit *model_name* argument.
2. Thread-local ``_active_model_override`` (set by agent.py).
3. Global ``_current_model``.
"""
return get_context_policy(model_name).effective_context
def get_tool_budget(fraction: float, *,
floor: int = 10_000, ceiling: int = 200_000) -> int:
"""Dynamic char budget for a tool result, scaled to the model's context.
Returns a *character* limit suitable for string slicing.
Assumes ~3 chars per token for the tokens-to-chars conversion.
Clamped between *floor* and *ceiling* to prevent extremes.
"""
ctx = get_context_size()
return min(ceiling, max(floor, int(ctx * fraction * 3)))
def get_user_context_size() -> int:
"""Return the raw user-selected context size (before model capping)."""
return _coerce_context_size(_num_ctx, DEFAULT_CONTEXT_SIZE, minimum=CONTEXT_SIZE_OPTIONS[0])
def get_cloud_context_size() -> int:
"""Return the raw user-selected cloud context cap."""
return _coerce_context_size(
_cloud_num_ctx,
DEFAULT_CLOUD_CONTEXT_SIZE,
minimum=CLOUD_CONTEXT_SIZE_OPTIONS[0],
)
def set_cloud_context_size(size: int):
"""Change the cloud context cap and recreate the LLM instance."""
global _cloud_num_ctx, _llm_instance
coerced = _coerce_context_size(size, DEFAULT_CLOUD_CONTEXT_SIZE, allowed=CLOUD_CONTEXT_SIZE_OPTIONS)
logger.info("Cloud context size changed: %s → %s", _cloud_num_ctx, coerced)
_cloud_num_ctx = coerced
_override_llm_cache.clear()
if is_cloud_model(_current_model):
_llm_instance = _get_cloud_llm(_current_model)
_save_settings({"model": _current_model, "context_size": _num_ctx,
"cloud_context_size": _cloud_num_ctx})
def set_context_size(size: int):
"""Change the context window size and recreate the LLM instance."""
global _num_ctx, _llm_instance
coerced = _coerce_context_size(size, DEFAULT_CONTEXT_SIZE, allowed=CONTEXT_SIZE_OPTIONS)
logger.info("Context size changed: %s → %s", _num_ctx, coerced)
_num_ctx = coerced
_override_llm_cache.clear()
if is_cloud_model(_current_model):
_llm_instance = _get_cloud_llm(_current_model)
else:
_llm_instance = _chat_ollama(
model=_runtime_model_name(_current_model),
num_ctx=_local_num_ctx_for(_current_model),
)
_save_settings({"model": _current_model, "context_size": _num_ctx,
"cloud_context_size": _cloud_num_ctx})
def get_current_model() -> str:
_reset_current_model_if_missing_custom_provider()
return _current_model
def _ollama_host_port() -> tuple[str, int]:
"""Return the TCP host/port configured for the local Ollama daemon."""
host, port, _scheme = _ollama_endpoint_parts()
return host, port
def _ollama_reachable(timeout: float = 1.0) -> bool:
"""Fast TCP probe to check if the Ollama server is listening."""
import socket
host, port = _ollama_host_port()
try:
with socket.create_connection((host, port), timeout=timeout):
return True
except (OSError, TimeoutError):
return False
def list_local_models() -> list[str]:
"""Return names of models currently exposed by the Ollama daemon."""
if not _ollama_reachable():
return []
names: set[str] = set()
client = _ollama_client()
try:
if client:
response = client.list()
for model in getattr(response, "models", []) or []:
name = getattr(model, "model", None) or getattr(model, "name", None)
if isinstance(model, dict):
name = model.get("model") or model.get("name") or name
if name:
names.add(str(name))
except Exception:
logger.debug("Could not list local Ollama models", exc_info=True)
if not names:
try:
response = _ollama_http_json("/api/tags")
for model in response.get("models", []) or []:
if not isinstance(model, dict):
continue
name = model.get("model") or model.get("name")
if name:
names.add(str(name))
except Exception:
logger.debug("Could not list local Ollama models over HTTP", exc_info=True)
return sorted(names)
def list_all_models() -> list[str]:
"""Return models currently exposed by the Ollama daemon."""
return sorted(set(list_local_models()))
def get_trending_models() -> list[str]:
"""Return no public Ollama discovery rows; Thoth manages daemon models only."""
return []
def fetch_trending_ollama_models() -> list[str]:
"""Deprecated compatibility shim.
Thoth no longer fetches public Ollama model listings or offers downloads.
Local model management lives in Ollama; this app only reads daemon-exposed
tags.
"""
global _trending_ollama_cache, _trending_fetched
_trending_ollama_cache = []
_trending_fetched = True
return []
def is_model_local(model_name: str) -> bool:
"""Check whether a model is already downloaded."""
parsed = _parse_provider_model_ref(model_name)
if parsed and parsed[0] not in {"local", "ollama"}:
return False
runtime_model = _runtime_model_name(model_name)
local = list_local_models()
return any(
runtime_model == m
or f"{runtime_model}:latest" == m
or runtime_model == m.split(":")[0]
for m in local
)
def _looks_like_cloud_model(model_name: str) -> bool:
"""Heuristic: return True if *model_name* looks like a cloud model.
Only used as a last-resort fallback when the persisted cache is empty
AND the in-memory cache hasn't been populated yet.
"""
if "/" in model_name: # OpenRouter format: provider/model
return True
if any(model_name.startswith(p) for p in _OPENAI_CHAT_PREFIXES):
# Exclude known Ollama models that happen to share a prefix
family = model_name.split(":")[0]
if family in _TOOL_COMPATIBLE_FAMILIES:
return False
return True
if model_name.split("/")[-1].lower().startswith("minimax"):
return True
return False
def _infer_cloud_provider(model_name: str) -> str | None:
"""Infer a cloud provider from a model ID when the cache is unavailable."""
parsed = _parse_provider_model_ref(model_name)
if parsed:
provider_id, _model_id = parsed
if provider_id == "ollama":
try:
from providers.ollama import is_ollama_cloud_offload_model
return "ollama" if is_ollama_cloud_offload_model(_model_id) else None
except Exception:
return None
return None if provider_id == "local" else provider_id
model_name = _runtime_model_name(model_name)
try:
from providers.ollama import is_ollama_cloud_offload_model
if is_ollama_cloud_offload_model(model_name):
return "ollama"
except Exception:
pass
_sync_custom_model_cache()
if model_name in _cloud_model_cache:
return _cloud_model_cache[model_name]["provider"]
if "/" in model_name:
return "openrouter"
bare_name = model_name.split("/")[-1]
if any(bare_name.startswith(prefix) for prefix in _OPENAI_CHAT_PREFIXES):
family = bare_name.split(":")[0]
if family not in _TOOL_COMPATIBLE_FAMILIES:
return "openai"
if bare_name.startswith("claude"):
return "anthropic"
if bare_name.startswith("gemini"):
return "google"
if bare_name.startswith("grok"):
return "xai"
if bare_name.lower().startswith("minimax"):
return "minimax"
return None
def is_cloud_model(model_name: str) -> bool:
"""Return True if *model_name* is a known cloud model.
Uses the persisted cache (loaded from disk at startup), then falls back
to provider-prefix inference so a saved cloud default survives cache or
key outages.
"""
return _infer_cloud_provider(model_name) is not None
def get_cloud_provider(model_name: str) -> str | None:
"""Return the cloud provider id for a model, or ``None`` for local models."""
return _infer_cloud_provider(model_name)
# ── Provider emoji mapping ───────────────────────────────────────────────────
_PROVIDER_EMOJI: dict[str | None, str] = {
"openai": "⬡",
"ollama": "☁️",
"ollama_cloud": "☁️",
"codex": "C",
"opencode_zen": "OZ",
"opencode_go": "OG",
"openrouter": "🌐",
"anthropic": "🔶",
"google": "💎",
"xai": "𝕏",
"minimax": "M",
None: "☁️", # fallback for unknown cloud
}
def get_provider_emoji(model_name: str) -> str:
"""Return a provider-specific emoji for a model.
Local models get 🖥️, cloud models get a provider-specific icon.
"""
if not is_cloud_model(model_name):
return "🖥️"
prov = get_cloud_provider(model_name)
return _PROVIDER_EMOJI.get(prov, _PROVIDER_EMOJI[None])
def is_cloud_available() -> bool:
"""Return True if any cloud API key is configured."""
from providers.runtime import list_configured_provider_ids
return bool(list_configured_provider_ids())
def is_openai_available() -> bool:
"""Return True if an OpenAI API key is configured."""
from api_keys import get_key
return bool(get_key("OPENAI_API_KEY"))
def is_openrouter_available() -> bool:
"""Return True if an OpenRouter API key is configured."""
from api_keys import get_key
return bool(get_key("OPENROUTER_API_KEY"))
def is_ollama_cloud_available() -> bool:
"""Return True if an Ollama Cloud API key is configured."""
from api_keys import get_key
return bool(get_key("OLLAMA_API_KEY"))
def is_anthropic_available() -> bool:
"""Return True if an Anthropic API key is configured."""
from api_keys import get_key
return bool(get_key("ANTHROPIC_API_KEY"))
def is_google_available() -> bool:
"""Return True if a Google AI API key is configured."""
from api_keys import get_key
return bool(get_key("GOOGLE_API_KEY"))
def is_xai_available() -> bool:
"""Return True if an xAI API key is configured."""
from api_keys import get_key
return bool(get_key("XAI_API_KEY"))
def is_minimax_available() -> bool:
"""Return True if a MiniMax API key is configured."""
from api_keys import get_key
return bool(get_key("MINIMAX_API_KEY"))
def list_cloud_models(provider: str | None = None) -> list[str]:
"""Return cached cloud model IDs, optionally filtered by provider."""
_sync_custom_model_cache()
if provider:
models = [m for m, info in _cloud_model_cache.items() if info["provider"] == provider]
if provider == "codex":
try:
from providers.codex import list_codex_model_infos
seen = set(models)
for model_info in list_codex_model_infos():
if model_info.model_id not in seen:
models.append(model_info.model_id)
seen.add(model_info.model_id)
except Exception:
pass
return models
return list(_cloud_model_cache.keys())
def _sync_custom_model_cache() -> None:
try:
from providers.custom import custom_model_cache_entries
entries = custom_model_cache_entries()
except Exception:
return
with _cloud_cache_lock:
for model_id, info in list(_cloud_model_cache.items()):
if isinstance(info, dict) and str(info.get("provider") or "").startswith("custom_openai_"):
replacement = entries.get(model_id)
if not replacement or replacement.get("provider") != info.get("provider"):
_cloud_model_cache.pop(model_id, None)
_cloud_model_cache.update(entries)
def reset_current_model_if_removed(
provider_id: str,
*,
removed_model_ids: set[str] | None = None,
) -> bool:
"""Reset the saved Brain default if it points at a removed provider/model."""