-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapi_provider.py
More file actions
4322 lines (3707 loc) · 185 KB
/
Copy pathapi_provider.py
File metadata and controls
4322 lines (3707 loc) · 185 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 base64
import inspect
import json
import os
import random
import re
import threading
import time
import urllib.error
import urllib.request
from pathlib import Path
from typing import Callable, NamedTuple
from urllib.parse import urlparse
import ollama
try:
import requests
REQUESTS_AVAILABLE = True
except ImportError:
requests = None
REQUESTS_AVAILABLE = False
# Qt-removal plan R4.1: import the Qt-free split, not graphlink_config -
# this module must be importable from backend/ without PySide6 loading.
import graphlink_task_config as config
from graphlink_audio import guess_audio_mime_type
from graphlink_model_catalog import FALLBACK_ENABLED_TASKS, ModelDescriptor, ModelRef, ollama_descriptor, sort_descriptors
# The ollama package ships its module-level helpers (ollama.chat/embed/list/
# show) as bound methods of ONE module-level Client, and that client is built
# with `timeout=None` - i.e. no socket timeout of any kind. Every other
# provider in this file is bounded (the OpenAI/Anthropic SDKs default to
# 600s; the hand-rolled Anthropic/Gemini REST calls pass explicit timeouts),
# so Ollama was the one path that could block a worker thread FOREVER.
#
# Why that is worse than it sounds: a daemon that accepts the TCP connection
# but never answers (a GPU hang or a stuck model load - a real, known Ollama
# failure mode) parks the calling thread on a socket read that never
# returns. Cancellation cannot help, because the cancel event is only polled
# between streamed chunks / after the call returns, and the dispatch watchdog
# (asyncio.wait_for) only stops WAITING - the worker keeps its
# asyncio.to_thread pool slot. Enough of those and the shared executor is
# exhausted and every to_thread in the app - including all settings
# mutations - queues forever: the whole backend soft-hangs.
#
# Configured on the existing shared client rather than by constructing our
# own: every call site keeps calling `ollama.chat(...)` exactly as before,
# and the test suite's monkeypatching of those module attributes keeps
# working. READ_TIMEOUT is deliberately generous and sits ABOVE the dispatch
# watchdog, so this is a backstop against a genuinely wedged daemon, not
# something that can cut a legitimately slow local generation short (for a
# streaming call httpx applies it per-chunk-read, i.e. to the GAP between
# tokens, not to the whole reply).
_OLLAMA_CONNECT_TIMEOUT_SECONDS = 10.0
_OLLAMA_READ_TIMEOUT_SECONDS = 600.0
def _configure_ollama_client_timeout() -> None:
"""Bound the shared ollama client's socket timeouts. Best-effort: this
reaches into the package's own internals (the bound method's __self__
and its httpx client), so a future ollama release that reshapes either
must degrade to the previous no-timeout behavior rather than breaking
import of this whole module."""
try:
import httpx
client = getattr(ollama.chat, "__self__", None)
inner = getattr(client, "_client", None)
if inner is None:
return
inner.timeout = httpx.Timeout(
connect=_OLLAMA_CONNECT_TIMEOUT_SECONDS,
read=_OLLAMA_READ_TIMEOUT_SECONDS,
write=60.0,
pool=_OLLAMA_CONNECT_TIMEOUT_SECONDS,
)
except Exception: # pragma: no cover - defensive, see docstring
pass
_configure_ollama_client_timeout()
USE_API_MODE = False
API_PROVIDER_TYPE = None
API_CLIENT = None
API_KEY = None
API_BASE_URL = None
LOCAL_PROVIDER_TYPE = config.LOCAL_PROVIDER_OLLAMA
# R8a: reasoning is now a graded level, not a bool "mode" - see
# REASONING_LEVELS' own docstring below for the full mapping story. Local
# providers default to "high" (the old "Thinking" default - local compute
# is free to the user, so thorough-by-default is the right starting
# point); cloud providers default to "off" (extended thinking on a paid
# API is an opt-in cost/latency tradeoff, never a silent default).
OLLAMA_REASONING_LEVEL = "high"
ANTHROPIC_REASONING_LEVEL = "off"
GEMINI_REASONING_LEVEL = "off"
OPENAI_REASONING_LEVEL = "off"
API_MODELS = {
config.TASK_TITLE: None,
config.TASK_CHAT: None,
config.TASK_CHART: None,
config.TASK_IMAGE_GEN: None,
config.TASK_WEB_VALIDATE: None,
config.TASK_WEB_SUMMARIZE: None,
}
LLAMA_CPP_SETTINGS = {
"chat_model_path": "",
"title_model_path": "",
"reasoning_level": "high",
"chat_format": "",
"n_ctx": 4096,
"n_gpu_layers": 0,
"n_threads": 0,
}
_LLAMA_CPP_CLIENT_CACHE = {}
_LLAMA_CPP_CLIENT_LOCK = threading.RLock()
# _LLAMA_CPP_CLIENT_LOCK above guards only the CACHE (lookup/creation). It
# does NOT guard INFERENCE, and those are genuinely different critical
# sections: one cached Llama instance is handed to every caller that resolves
# to the same model, and llama-cpp-python's Llama is not thread-safe (it
# carries mutable per-sequence state - n_tokens and the KV cache - and
# releases the GIL inside llama_decode). RunRegistry.is_busy is per-kind
# per-session, so a streaming chat reply and a chart/note generation in the
# same session, or two sessions at once, legitimately run concurrently on
# separate worker threads - and before this lock they could interleave two
# generations on ONE native context, which corrupts output or dies in native
# code and takes the whole backend process with it.
#
# A plain Lock, not an RLock, and deliberately so: a stream() generator holds
# this across its whole consumption and releases it in a finally, which -
# if the caller abandons the generator - runs during garbage collection,
# potentially on a DIFFERENT thread. RLock refuses a release from any thread
# but its owner (RuntimeError); a plain Lock permits it, which is exactly the
# behavior this ownership pattern needs.
_LLAMA_CPP_SHARED_INFERENCE_LOCK = threading.Lock()
def llama_cpp_inference_lock(client):
"""The inference lock for one cached Llama instance - see
_LLAMA_CPP_SHARED_INFERENCE_LOCK's own comment for why inference needs a
lock separate from the cache lock.
Per-CLIENT rather than global, so two different models (separate native
contexts, no shared state) still run concurrently; only calls sharing one
instance serialize. A client with no attached lock - a monkeypatched fake
in a test, or an instance built before this existed - falls back to the
module-wide lock, which is over-strict but never unsafe."""
lock = getattr(client, "_graphlink_inference_lock", None)
return lock if lock is not None else _LLAMA_CPP_SHARED_INFERENCE_LOCK
# Guards the provider globals above. Mutators (initialize_api,
# initialize_local_provider, set_task_model) write under this lock;
# chat()/generate_image() take one consistent snapshot under it at request entry and
# route the whole request through that snapshot. Previously a mode switch during an
# in-flight request could interleave with the request's many separate global reads,
# executing it against a half-swapped provider (e.g. the new provider type with the
# old client/key). The module globals stay authoritative (and monkeypatchable) - the
# snapshot is a per-request view.
_PROVIDER_STATE_LOCK = threading.Lock()
class _ProviderSnapshot(NamedTuple):
use_api_mode: bool
api_provider_type: str | None
api_client: object
api_key: str | None
api_base_url: str | None
local_provider_type: str
api_models: dict
llama_cpp_settings: dict
ollama_reasoning_level: str
anthropic_reasoning_level: str
gemini_reasoning_level: str
openai_reasoning_level: str
# ADR-006 stage 6.5 (H6): the Ollama per-task model table, copied UNDER
# the provider lock at snapshot time. chat()/chat_stream() previously
# read config.OLLAMA_MODELS live AFTER taking their snapshot - a
# concurrent model-assignment change (or even an app-composer republish,
# which used to sync the table on the read path) could swap the model
# between the snapshot and the provider construction. Trailing field
# with a default so existing positional constructions stay valid.
ollama_models: dict = {}
def _snapshot_provider_state() -> _ProviderSnapshot:
with _PROVIDER_STATE_LOCK:
return _ProviderSnapshot(
use_api_mode=USE_API_MODE,
api_provider_type=API_PROVIDER_TYPE,
api_client=API_CLIENT,
api_key=API_KEY,
api_base_url=API_BASE_URL,
local_provider_type=LOCAL_PROVIDER_TYPE,
api_models=dict(API_MODELS),
llama_cpp_settings=dict(LLAMA_CPP_SETTINGS),
ollama_reasoning_level=OLLAMA_REASONING_LEVEL,
anthropic_reasoning_level=ANTHROPIC_REASONING_LEVEL,
gemini_reasoning_level=GEMINI_REASONING_LEVEL,
openai_reasoning_level=OPENAI_REASONING_LEVEL,
ollama_models=dict(config.OLLAMA_MODELS),
)
def sync_ollama_models(settings_manager=None):
"""ADR-006 stage 6.5 (H6): the ONLY sanctioned writer entry point for
config.OLLAMA_MODELS/CURRENT_MODEL - takes the provider lock so the
table can never change between a request snapshot's copy of it and the
rest of that snapshot. config.sync_ollama_task_models itself stays in
graphlink_task_config (it owns the persistence semantics); this wrapper
owns the locking, which that module cannot (it would be a circular
import)."""
with _PROVIDER_STATE_LOCK:
return config.sync_ollama_task_models(settings_manager)
def set_current_ollama_model(model: str) -> None:
"""Locked twin of config.set_current_model - see sync_ollama_models."""
with _PROVIDER_STATE_LOCK:
config.set_current_model(model)
class ProviderRuntime:
"""ADR-006 stage 6.5: one session's complete provider configuration.
Instances constructed directly hold their OWN state - two sessions can
hold different providers/models/reasoning levels concurrently. The
module-level DEFAULT_RUNTIME below is the one exception: it PROXIES the
legacy module globals, which stay authoritative (and monkeypatchable -
the entire existing test suite patches them) for the default session.
Every mutator and every snapshot goes through _read_all/_write, which is
the only thing the module-backed subclass overrides.
A request captures `snapshot()` once at entry and routes the whole
request through it - the same mid-request-swap immunity the module
globals' _ProviderSnapshot always provided, now including the Ollama
model table (H6)."""
def __init__(self):
self._lock = threading.Lock()
self._state = {
"use_api_mode": False,
"api_provider_type": None,
"api_client": None,
"api_key": None,
"api_base_url": None,
"local_provider_type": config.LOCAL_PROVIDER_OLLAMA,
"api_models": dict.fromkeys(API_MODELS),
"llama_cpp_settings": _normalize_llama_cpp_settings(),
"ollama_reasoning_level": "high",
"anthropic_reasoning_level": "off",
"gemini_reasoning_level": "off",
"openai_reasoning_level": "off",
"ollama_models": {},
}
@classmethod
def from_snapshot(cls, snapshot: "_ProviderSnapshot") -> "ProviderRuntime":
"""Seed a fresh per-session runtime from an existing configuration -
how a non-default session starts out matching the default one before
diverging."""
runtime = cls()
runtime._write(**snapshot._asdict())
return runtime
# -- state access (the ONLY methods the module-backed subclass overrides)
def _read_all(self) -> dict:
with self._lock:
state = dict(self._state)
state["api_models"] = dict(state["api_models"])
state["llama_cpp_settings"] = dict(state["llama_cpp_settings"])
state["ollama_models"] = dict(state["ollama_models"])
return state
def _write(self, **updates) -> dict:
"""Apply updates under the lock; returns the PREVIOUS values of the
updated keys (initialize_local_provider's llama.cpp rollback needs
the capture and the write to be one atomic step)."""
with self._lock:
previous = {key: self._state[key] for key in updates}
self._state.update(updates)
return previous
def set_task_model(self, task: str, api_model: str) -> None:
with self._lock:
if task in self._state["api_models"]:
self._state["api_models"][task] = api_model
def set_ollama_models(self, models: dict) -> None:
"""Per-session twin of sync_ollama_models: replaces this runtime's
own Ollama task table (a plain dict write - per-session runtimes do
not share config.OLLAMA_MODELS)."""
self._write(ollama_models=dict(models))
# -- the shared configuration logic ---------------------------------------
def snapshot(self) -> _ProviderSnapshot:
return _ProviderSnapshot(**self._read_all())
def initialize_api(self, provider: str, api_key: str, base_url: str = None):
client, api_key, base_url = _build_api_client(provider, api_key, base_url)
self._write(
use_api_mode=True,
api_provider_type=provider,
api_client=client,
api_key=api_key,
api_base_url=base_url,
)
return client
def initialize_local_provider(
self, provider: str, settings: dict | None = None, *, preload_model: bool = False
):
if provider == config.LOCAL_PROVIDER_OLLAMA:
normalized_settings = _normalize_llama_cpp_settings()
updates = dict(
use_api_mode=False,
local_provider_type=provider,
api_provider_type=None,
api_client=None,
api_key=None,
api_base_url=None,
llama_cpp_settings=normalized_settings,
)
requested_reasoning = (settings or {}).get("reasoning_level")
if requested_reasoning:
updates["ollama_reasoning_level"] = normalize_reasoning_level(requested_reasoning)
self._write(**updates)
return {"provider": provider}
if provider == config.LOCAL_PROVIDER_LLAMACPP:
normalized_settings = _normalize_llama_cpp_settings(settings)
_validate_llama_cpp_model_path(
normalized_settings.get("chat_model_path"),
config.TASK_CHAT,
)
if normalized_settings.get("title_model_path"):
_validate_llama_cpp_model_path(normalized_settings["title_model_path"], config.TASK_TITLE)
# ADR-006 stage 6.5 review fix (LOW): preload BEFORE writing state,
# not write-then-rollback-on-failure. The (potentially slow,
# multi-GB) preload deliberately happens outside the state lock
# so it never blocks other requests' snapshots - but a snapshot
# taken in that window used to see the NEW, not-yet-validated
# settings, which from_snapshot() can now copy into a per-session
# runtime that never gets corrected if the preload then fails and
# this runtime rolls back. Preloading first means a write only
# ever commits a value already known-good, so there is nothing to
# roll back and nothing transient for a concurrent snapshot to
# capture.
if preload_model:
_get_llama_cpp_client(config.TASK_CHAT, normalized_settings)
self._write(
use_api_mode=False,
local_provider_type=provider,
api_provider_type=None,
api_client=None,
api_key=None,
api_base_url=None,
llama_cpp_settings=normalized_settings,
)
return {
"provider": provider,
"model_path": _get_llama_cpp_model_path(config.TASK_CHAT, normalized_settings),
"preloaded": bool(preload_model),
}
raise ValueError(f"Unknown local provider: {provider}")
def set_ollama_reasoning_level(self, level: str) -> None:
self._write(ollama_reasoning_level=normalize_reasoning_level(level))
def set_anthropic_reasoning_level(self, level: str) -> None:
self._write(anthropic_reasoning_level=normalize_reasoning_level(level))
def set_gemini_reasoning_level(self, level: str) -> None:
self._write(gemini_reasoning_level=normalize_reasoning_level(level))
def set_openai_reasoning_level(self, level: str) -> None:
self._write(openai_reasoning_level=normalize_reasoning_level(level))
def is_api_mode(self) -> bool:
return self.snapshot().use_api_mode
def is_local_ollama_mode(self) -> bool:
state = self.snapshot()
return not state.use_api_mode and state.local_provider_type == config.LOCAL_PROVIDER_OLLAMA
def is_local_llama_cpp_mode(self) -> bool:
state = self.snapshot()
return not state.use_api_mode and state.local_provider_type == config.LOCAL_PROVIDER_LLAMACPP
def is_configured(self) -> bool:
state = self.snapshot()
if state.use_api_mode:
# ADR-006 stage 6.5 (H6): TASK_IMAGE_GEN is deliberately ABSENT
# for EVERY provider, not just Anthropic - image generation is
# capability-gated at call time (generate_image's own explicit
# no-model/no-images-API errors), so a text-only OpenAI-compatible
# endpoint (vLLM, LM Studio, llama-server) counts as configured.
required_tasks = (
config.TASK_TITLE,
config.TASK_CHAT,
config.TASK_CHART,
config.TASK_WEB_VALIDATE,
config.TASK_WEB_SUMMARIZE,
)
return state.api_client is not None and all(
state.api_models.get(task_key) for task_key in required_tasks
)
if state.local_provider_type == config.LOCAL_PROVIDER_OLLAMA:
return bool(state.ollama_models.get(config.TASK_CHAT))
if state.local_provider_type == config.LOCAL_PROVIDER_LLAMACPP:
return bool(_get_llama_cpp_model_path(config.TASK_CHAT, state.llama_cpp_settings))
return False
def context_window(self, task: str) -> int:
"""ADR-006 stage 6.6: the active chat model's context window in
tokens, for `task`'s configured model under THIS runtime's current
snapshot. Three sources, in honesty order:
- llama.cpp mode: the configured n_ctx - exact truth, it IS the
allocated context.
- Ollama mode: "<arch>.context_length" from a cached ollama.show()
lookup (_get_ollama_context_window); falls back to the
conservative default when the server/metadata is unavailable.
- API mode: the documented per-family table (_KNOWN_CONTEXT_WINDOWS,
matched by model-id prefix - same name-heuristic posture as
anthropic_supports_reasoning); unknown ids get the conservative
default, preserving pre-6.6 behavior for unrecognized endpoints.
"""
state = self.snapshot()
if not state.use_api_mode:
if state.local_provider_type == config.LOCAL_PROVIDER_LLAMACPP:
try:
n_ctx = int(state.llama_cpp_settings.get("n_ctx") or 0)
except (TypeError, ValueError):
n_ctx = 0
return n_ctx if n_ctx > 0 else _DEFAULT_CONTEXT_WINDOW
if state.local_provider_type == config.LOCAL_PROVIDER_OLLAMA:
return _ollama_effective_context_window(state.ollama_models.get(task))
return _DEFAULT_CONTEXT_WINDOW
return known_context_window(state.api_models.get(task))
class _ModuleBackedProviderRuntime(ProviderRuntime):
"""The default session's runtime: state lives in the module globals
above (guarded by _PROVIDER_STATE_LOCK), which stay authoritative and
monkeypatchable - `patch.object(api_provider, "USE_API_MODE", ...)`
keeps working exactly as before. Only the two state-access primitives
differ; every piece of configuration LOGIC is inherited."""
_GLOBAL_NAMES = {
"use_api_mode": "USE_API_MODE",
"api_provider_type": "API_PROVIDER_TYPE",
"api_client": "API_CLIENT",
"api_key": "API_KEY",
"api_base_url": "API_BASE_URL",
"local_provider_type": "LOCAL_PROVIDER_TYPE",
"llama_cpp_settings": "LLAMA_CPP_SETTINGS",
"ollama_reasoning_level": "OLLAMA_REASONING_LEVEL",
"anthropic_reasoning_level": "ANTHROPIC_REASONING_LEVEL",
"gemini_reasoning_level": "GEMINI_REASONING_LEVEL",
"openai_reasoning_level": "OPENAI_REASONING_LEVEL",
}
def __init__(self):
# Deliberately NO super().__init__() - the module IS the state.
pass
def _read_all(self) -> dict:
return _snapshot_provider_state()._asdict()
def _write(self, **updates) -> dict:
module_globals = globals()
with _PROVIDER_STATE_LOCK:
previous = {}
for key, value in updates.items():
if key == "api_models":
previous[key] = dict(API_MODELS)
API_MODELS.clear()
API_MODELS.update(value)
elif key == "ollama_models":
previous[key] = dict(config.OLLAMA_MODELS)
config.OLLAMA_MODELS.clear()
config.OLLAMA_MODELS.update(value)
else:
previous[key] = module_globals[self._GLOBAL_NAMES[key]]
module_globals[self._GLOBAL_NAMES[key]] = value
return previous
def set_task_model(self, task: str, api_model: str) -> None:
with _PROVIDER_STATE_LOCK:
if task in API_MODELS:
API_MODELS[task] = api_model
# The default session's runtime - the one every module-level function below
# delegates to, and the one backend/app.py hands to the default session.
DEFAULT_RUNTIME = _ModuleBackedProviderRuntime()
GEMINI_MODELS_STATIC = sorted([
"gemini-3.1-pro-preview",
"gemini-3-flash-preview",
"gemini-3.1-flash-lite-preview",
"gemini-2.5-pro",
"gemini-2.5-flash",
"gemini-2.5-flash-lite",
"gemini-2.0-flash",
])
GEMINI_IMAGE_MODELS_STATIC = sorted([
"gemini-2.5-flash-image",
"gemini-3.1-flash-image-preview",
])
GEMINI_BASE_URL = "https://generativelanguage.googleapis.com"
ANTHROPIC_MODELS_URL = "https://api.anthropic.com/v1/models?limit=1000"
ANTHROPIC_DEFAULT_MAX_TOKENS = {
config.TASK_TITLE: 128,
config.TASK_WEB_VALIDATE: 64,
config.TASK_CHAT: 4096,
config.TASK_CHART: 4096,
config.TASK_WEB_SUMMARIZE: 4096,
}
_OLLAMA_CAPABILITY_CACHE = {}
# ADR-006 stage 6.6: context windows extracted from the same `ollama.show()`
# call the capability cache uses, cached under the same key discipline and
# invalidated by the same invalidate_ollama_capability_cache() entry point.
_OLLAMA_CONTEXT_WINDOW_CACHE = {}
# ADR-006 stage 6.6: API-mode context windows, matched by model-id prefix.
# Same posture as anthropic_supports_reasoning below: a documented
# name-based heuristic, not an API lookup - providers expose no context-
# window endpoint. First matching prefix wins (ordered, longest-first where
# prefixes overlap). Unknown models (including unrecognized OpenAI-
# compatible endpoints) fall back to _DEFAULT_CONTEXT_WINDOW, preserving
# the pre-6.6 8k budget for anything we cannot vouch for.
_KNOWN_CONTEXT_WINDOWS = (
("claude-", 200_000), # claude-3/3.5/4+ families all document 200k
("gemini-", 1_048_576), # gemini-2.0-flash / 2.5-pro/flash / 3* all 1M
("gpt-4.1", 1_047_576), # gpt-4.1 family documents ~1M
("gpt-4o", 128_000),
("gpt-5", 128_000), # conservative floor for the family
("o1", 128_000),
("o3", 128_000),
("o4", 128_000),
)
_DEFAULT_CONTEXT_WINDOW = 8_192
# ADR-006 stage 6.8 review fix (HIGH): what we ask the Ollama daemon to
# SERVE (options.num_ctx) when the Modelfile has no explicit num_ctx. The
# trained max from model_info is NOT a safe default to request - a 131k
# num_ctx on llama3.1 allocates a KV cache that OOMs typical consumer GPUs,
# and the daemon's own default (~4k) silently truncates prompts front-first
# instead. 8192 is the KV-cache-safe middle ground; users who want more set
# num_ctx in their Modelfile and we honor it exactly.
_OLLAMA_SERVED_CONTEXT_CAP = 8_192
def _ollama_effective_context_window(model: str | None) -> int:
"""The single source of truth for Ollama-mode context: the served
window from show() (see _get_ollama_context_window) or the conservative
default. Used by BOTH the budget side (ProviderRuntime.context_window)
and the request side (OllamaProvider's options.num_ctx) so the two can
never disagree."""
window = _get_ollama_context_window(model)
return window if window else _DEFAULT_CONTEXT_WINDOW
def known_context_window(model_id: str | None) -> int:
"""Best-known context window for an API-mode model id (see the table
above). Falls back to the conservative default for unknown ids."""
normalized = str(model_id or "").strip().lower()
for prefix, window in _KNOWN_CONTEXT_WINDOWS:
if normalized.startswith(prefix):
return window
return _DEFAULT_CONTEXT_WINDOW
_KNOWN_OLLAMA_AUDIO_MODEL_FAMILIES = {"gemma4"}
_OLLAMA_REASONING_RETRY_BACKOFF_SECONDS = 1.0
# ADR-006 stage 6.8: transient-transport retry, DISTINCT from Ollama's own
# reasoning-content retry above (they must never nest wrongly: the transport
# wrapper wraps the WHOLE provider stream/complete call, Ollama's reasoning
# retries included - a ReasoningWithoutAnswerError never escapes the
# provider, and its exhausted-retries RuntimeError is not transport-shaped,
# so the wrapper never re-runs a content retry).
_TRANSPORT_RETRY_MAX_ATTEMPTS = 2 # retries, so at most 3 total tries
_TRANSPORT_RETRY_BASE_BACKOFF_SECONDS = 1.0
_TRANSPORT_RETRY_MAX_SLEEP_SECONDS = 30.0
_TRANSPORT_RETRY_STATUS_CODES = (429, 500, 502, 503, 504)
_THINK_TAG_PATTERN = re.compile(r"<(think|thinking)>\s*(.*?)\s*</\1>", re.DOTALL | re.IGNORECASE)
_THINK_CLOSING_ONLY_PATTERN = re.compile(r"</(think|thinking)>", re.IGNORECASE)
_FALLBACK_REASONING_PATTERN = re.compile(
r"--- REASONING ---\s*(.*?)\s*--- END REASONING ---",
re.DOTALL | re.IGNORECASE,
)
_HARMONY_ANALYSIS_PREFIX_PATTERN = re.compile(
r"^\s*<\|channel\|>analysis<\|message\|>\s*",
re.IGNORECASE,
)
_HARMONY_FINAL_MARKER_PATTERN = re.compile(
r"<\|start\|>assistant<\|channel\|>(?:final|final json)<\|message\|>\s*",
re.IGNORECASE,
)
_HARMONY_END_MARKER_PATTERN = re.compile(r"<\|end\|>\s*", re.IGNORECASE)
class RequestCancelledError(RuntimeError):
"""Raised when the user cancels an in-flight model request."""
def _normalize_ollama_models_root(path_value: str | None) -> Path | None:
normalized = str(path_value or "").strip()
if not normalized:
return None
candidate = Path(normalized).expanduser()
if not candidate.is_dir():
return None
# Support all common Ollama layout variants:
# .../manifests
# .../models
# .../<custom-root-with-manifests-and-blobs>
candidate_name = candidate.name.lower()
if candidate_name == "manifests":
return candidate
if (candidate / "manifests").is_dir():
return candidate / "manifests"
if (candidate / "models" / "manifests").is_dir():
return candidate / "models" / "manifests"
if candidate_name == "models":
return candidate / "manifests"
return candidate / "models" / "manifests"
def _iter_existing_ollama_manifest_roots() -> list[Path]:
candidate_roots: list[Path] = []
env_models_root = os.environ.get("OLLAMA_MODELS")
local_app_data = os.environ.get("LOCALAPPDATA")
program_data = os.environ.get("PROGRAMDATA")
for raw_path in (
env_models_root,
Path.home() / ".ollama",
Path.home() / ".ollama" / "models",
local_app_data and Path(local_app_data) / "Ollama",
local_app_data and Path(local_app_data) / "Ollama" / "models",
program_data and Path(program_data) / "Ollama",
program_data and Path(program_data) / "Ollama" / "models",
):
manifests_root = _normalize_ollama_models_root(raw_path)
if manifests_root and manifests_root.is_dir():
candidate_roots.append(manifests_root)
unique_roots: list[Path] = []
seen_roots: set[str] = set()
for root in candidate_roots:
resolved = str(root.resolve()).lower()
if resolved in seen_roots:
continue
seen_roots.add(resolved)
unique_roots.append(root)
return unique_roots
def _discover_manifest_roots_in_folder(scan_path: str) -> list[Path]:
root_path = Path(scan_path).expanduser()
if not root_path.exists():
raise RuntimeError(f"Scan folder does not exist: {scan_path}")
if not root_path.is_dir():
raise RuntimeError(f"Scan folder is not a directory: {scan_path}")
direct_candidates = [
root_path,
root_path / "manifests",
root_path / "models" / "manifests",
]
manifest_roots: list[Path] = []
seen_roots: set[str] = set()
for candidate in direct_candidates:
manifests_root = _normalize_ollama_models_root(candidate)
if manifests_root and manifests_root.is_dir():
resolved = str(manifests_root.resolve()).lower()
if resolved not in seen_roots:
seen_roots.add(resolved)
manifest_roots.append(manifests_root)
for current_root, dir_names, _ in os.walk(root_path):
current_name = os.path.basename(current_root).lower()
parent_name = os.path.basename(os.path.dirname(current_root)).lower()
if current_name == "blobs":
dir_names[:] = []
continue
if current_name == "manifests" and parent_name == "models":
manifests_root = Path(current_root)
resolved = str(manifests_root.resolve()).lower()
if resolved not in seen_roots:
seen_roots.add(resolved)
manifest_roots.append(manifests_root)
dir_names[:] = []
return manifest_roots
def _extract_model_name_from_manifest_path(manifest_path: Path, manifests_root: Path) -> str | None:
try:
relative_parts = manifest_path.relative_to(manifests_root).parts
except ValueError:
return None
if len(relative_parts) < 3:
return None
repository_parts = list(relative_parts[1:-1])
if repository_parts and repository_parts[0].lower() == "library":
repository_parts = repository_parts[1:]
if not repository_parts:
return None
tag = relative_parts[-1].strip()
if not tag:
return None
repository_name = "/".join(part.strip() for part in repository_parts if part.strip())
if not repository_name:
return None
return f"{repository_name}:{tag}"
def _collect_models_from_manifest_root(manifests_root: Path) -> list[str]:
discovered_models: set[str] = set()
for current_root, dir_names, file_names in os.walk(manifests_root):
dir_names[:] = [dir_name for dir_name in dir_names if dir_name.lower() != "blobs"]
for file_name in file_names:
manifest_path = Path(current_root) / file_name
model_name = _extract_model_name_from_manifest_path(manifest_path, manifests_root)
if model_name:
discovered_models.add(model_name)
return sorted(discovered_models, key=str.lower)
def _list_model_descriptors_from_running_ollama() -> tuple[list[ModelDescriptor], bool, str]:
"""Return installed Ollama models plus an honest server health signal."""
try:
response = ollama.list()
except Exception as exc:
return [], False, str(exc)
raw_models = _extract_response_field(response, "models", [])
descriptors = []
for raw_model in raw_models or []:
descriptor = ollama_descriptor(raw_model)
if descriptor.model_id:
descriptors.append(descriptor)
return sort_descriptors(descriptors), True, ""
def scan_local_ollama_models(scan_path: str | None = None) -> dict:
running_descriptors: list[ModelDescriptor] = []
server_reachable = None
server_error = ""
if scan_path:
manifest_roots = _discover_manifest_roots_in_folder(scan_path)
scan_mode = "folder"
scan_root = str(Path(scan_path).expanduser().resolve())
running_models: list[str] = []
else:
manifest_roots = _iter_existing_ollama_manifest_roots()
scan_mode = "system"
scan_root = ""
running_descriptors, server_reachable, server_error = _list_model_descriptors_from_running_ollama()
running_models = [descriptor.model_id for descriptor in running_descriptors]
discovered_models: set[str] = set(running_models)
scanned_locations: list[str] = []
for manifests_root in manifest_roots:
discovered_models.update(_collect_models_from_manifest_root(manifests_root))
scanned_locations.append(str(manifests_root.resolve()))
descriptors_by_id = {
descriptor.model_id.lower(): descriptor
for descriptor in (running_descriptors if not scan_path else [])
}
for model_name in discovered_models:
descriptors_by_id.setdefault(
model_name.lower(),
ModelDescriptor(
model_id=model_name,
provider=config.LOCAL_PROVIDER_OLLAMA,
ready=True,
available=True,
source="manifest",
),
)
return {
"models": sorted(discovered_models, key=str.lower),
"descriptors": [
{
"model_id": descriptor.model_id,
"provider": descriptor.provider,
"ready": descriptor.ready,
"available": descriptor.available,
"capabilities": sorted(descriptor.capabilities),
"source": descriptor.source,
"size_bytes": descriptor.size_bytes,
"context_length": descriptor.context_length,
"quantization": descriptor.quantization,
}
for descriptor in sort_descriptors(descriptors_by_id.values())
],
"scan_mode": scan_mode,
"scan_path": scan_root,
"locations": sorted(set(scanned_locations), key=str.lower),
"server_reachable": server_reachable if not scan_path else None,
"server_error": server_error if not scan_path else "",
}
def _normalize_llama_cpp_scan_root(path_value: str | None) -> Path | None:
normalized = str(path_value or "").strip()
if not normalized:
return None
candidate = Path(normalized).expanduser()
if candidate.is_file():
return candidate.parent
return candidate
def _iter_existing_llama_cpp_scan_roots() -> list[Path]:
local_app_data = os.environ.get("LOCALAPPDATA")
candidate_roots = [
os.environ.get("LLAMA_CPP_MODELS"),
Path.home() / "models",
Path.home() / "llama.cpp",
Path.home() / "llama.cpp" / "models",
Path.home() / "Downloads",
Path.home() / "Documents",
Path.home() / "Desktop",
Path.home() / ".cache" / "lm-studio" / "models",
local_app_data and Path(local_app_data) / "llama.cpp" / "models",
]
unique_roots: list[Path] = []
seen_roots: set[str] = set()
for raw_path in candidate_roots:
root = _normalize_llama_cpp_scan_root(raw_path)
if not root or not root.is_dir():
continue
resolved = str(root.resolve()).lower()
if resolved in seen_roots:
continue
seen_roots.add(resolved)
unique_roots.append(root)
return unique_roots
_GGUF_SCAN_MAX_DIRECTORIES = 50_000
_GGUF_SCAN_MAX_SECONDS = 30
def _collect_gguf_files_from_root(root_path: Path) -> tuple[list[str], bool]:
"""Walk root_path for .gguf files, bounded by directory count and wall-clock time.
The default (no scan_path configured) roots include the user's whole
Downloads/Documents/Desktop trees (see _iter_existing_llama_cpp_scan_roots) - an
unbounded os.walk there can run for a very long time against a pathological or
cloud-synced tree. Returns (models, was_truncated) so callers can tell the scan
stopped early rather than silently reporting an incomplete list as complete.
"""
discovered_models: set[str] = set()
skip_directories = {
".git",
".hg",
".svn",
"__pycache__",
"node_modules",
"venv",
".venv",
}
started_at = time.monotonic()
directories_visited = 0
truncated = False
for current_root, dir_names, file_names in os.walk(root_path):
directories_visited += 1
if (
directories_visited > _GGUF_SCAN_MAX_DIRECTORIES
or (time.monotonic() - started_at) > _GGUF_SCAN_MAX_SECONDS
):
truncated = True
break
dir_names[:] = [
dir_name for dir_name in dir_names
if dir_name.lower() not in skip_directories
]
for file_name in file_names:
if not file_name.lower().endswith(".gguf"):
continue
model_path = Path(current_root) / file_name
discovered_models.add(str(model_path.resolve()))
return sorted(discovered_models, key=str.lower), truncated
def scan_local_llama_cpp_models(scan_path: str | None = None) -> dict:
if scan_path:
root = _normalize_llama_cpp_scan_root(scan_path)
if not root or not root.exists():
raise RuntimeError(f"Scan folder does not exist: {scan_path}")
if not root.is_dir():
raise RuntimeError(f"Scan folder is not a directory: {scan_path}")
scan_roots = [root]
scan_mode = "folder"
scan_root = str(root.resolve())
else:
scan_roots = _iter_existing_llama_cpp_scan_roots()
scan_mode = "system"
scan_root = ""
discovered_models: set[str] = set()
scanned_locations: list[str] = []
truncated = False
for root in scan_roots:
root_models, root_truncated = _collect_gguf_files_from_root(root)
discovered_models.update(root_models)
scanned_locations.append(str(root.resolve()))
truncated = truncated or root_truncated
return {
"models": sorted(discovered_models, key=str.lower),
"scan_mode": scan_mode,
"scan_path": scan_root,
"locations": sorted(set(scanned_locations), key=str.lower),
"truncated": truncated,
}
def _read_attachment_bytes(file_path: str, attachment_kind: str) -> bytes:
resolved_path = os.path.abspath(file_path or "")
attachment_name = os.path.basename(resolved_path or file_path or "")
if not resolved_path or not os.path.isfile(resolved_path):
raise RuntimeError(
f"Attached {attachment_kind} file is no longer available: "
f"{attachment_name or '[missing file]'}"
)
try:
with open(resolved_path, "rb") as source_file:
return source_file.read()
except OSError as exc:
raise RuntimeError(
f"Failed to read attached {attachment_kind} file '{attachment_name}': {exc}"
) from exc
def _extract_response_field(payload, field_name: str, default=None):
if payload is None:
return default
if isinstance(payload, dict):
return payload.get(field_name, default)
if hasattr(payload, field_name):
return getattr(payload, field_name)
try:
return payload[field_name]
except Exception:
return default
def _append_unique_text_segment(parts: list[str], text, seen: set[str]):
normalized = str(text or "").strip()
if not normalized:
return
key = re.sub(r"\s+", " ", normalized).strip().lower()
if not key or key in seen:
return
seen.add(key)
parts.append(normalized)
def _strip_leading_harmony_tokens(text: str) -> str:
remaining = str(text or "")