Repository navigation
Expand file tree
/
Copy pathdynamic_retriever.py
More file actions
2727 lines (2461 loc) · 125 KB
/
Copy pathdynamic_retriever.py
File metadata and controls
2727 lines (2461 loc) · 125 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
#!/usr/bin/env python
"""Unified retriever: tool-use (agentic) and decomposed RAG paradigms.
This module supersedes the historical pair (``agentic_retriever.py`` +
``dynamic_retriever.py``). The active paradigm is selected at runtime:
* ``--mode tool-use`` (default) — LLM-driven function-calling loop over
Cosmos DB (vector + fulltext + ranker) with auto-prune on context overflow.
* ``--mode decomposed`` — :class:`DecomposedRAGPipeline` (decompose → answer
sub-questions → regenerate → synthesize) with diversity-aware retrieval.
The CLI flag ``--mode`` overrides ``pipeline.mode`` in the loaded YAML
config; the default when neither is set is ``tool-use``.
"""
from __future__ import annotations
import argparse
import asyncio
from collections.abc import Callable
import copy
import contextvars
import datetime
import json
import os
import re
import shutil
import sys
import time
import threading
import warnings
from collections import OrderedDict
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, TYPE_CHECKING
import httpx
import yaml
import openai
import openai as oai # alias used by tool-use code paths
import tiktoken
from azure.cosmos.aio import CosmosClient
from azure.core.exceptions import ServiceRequestError as AzureServiceRequestError
class ServiceConnectionError(Exception):
"""Raised when a required backend service cannot be reached."""
from azure.identity import DefaultAzureCredential as SyncDefaultAzureCredential, AzureCliCredential, get_bearer_token_provider
from azure.identity.aio import AzureCliCredential as AsyncAzureCliCredential
from dotenv import load_dotenv
from openai import AsyncAzureOpenAI, AsyncOpenAI
from tqdm import tqdm
import numpy as np
from greedy_log_det import greedy_log_det_select
from utils.fulltext import fulltext_search, fulltext_search_options, is_fulltext_field_path
from utils.candidates import (
ConfigurationError,
candidate_projection,
fetch_candidate_documents,
resolve_partition_key_path,
)
from utils.ranker import RankerUnavailableError, rerank_documents, verify_ranker_token
load_dotenv()
# =============================================================================
# TIMING INSTRUMENTATION (enabled via --timing flag)
# =============================================================================
_TIMING: bool = False
_t0: float = 0.0
_print_lock = threading.Lock()
_TIMING_MARK = "¤"
_CURRENT_QUESTION_ID: contextvars.ContextVar[str | None] = contextvars.ContextVar("current_question_id", default=None)
_ANSI_RESET = "\x1b[0m"
_ANSI_COLORS = {
"timing": "\x1b[90m",
"query": "\x1b[2;33m",
"success": "\x1b[92m",
"warn": "\x1b[93m",
"error": "\x1b[91m",
"info": "\x1b[94m",
}
def _stdout_supports_color() -> bool:
if os.getenv("NO_COLOR"):
return False
if os.getenv("FORCE_COLOR"):
return True
stream = sys.stdout
streams = getattr(stream, "_streams", None)
if streams:
return any(bool(getattr(s, "isatty", lambda: False)()) for s in streams)
return bool(getattr(stream, "isatty", lambda: False)())
def _colorize(text: str, kind: str) -> str:
if not _stdout_supports_color():
return text
if kind == "timing":
base = _ANSI_COLORS["timing"]
white = "\x1b[97m"
pattern = re.compile(r"(?P<num>[+-]?[0-9]*\.?[0-9]+s)")
def repl(match: re.Match[str]) -> str:
return f"{white}{match.group('num')}{base}"
return f"{base}{pattern.sub(repl, text)}{_ANSI_RESET}"
if kind == "query":
base = _ANSI_COLORS["query"]
highlight = "\x1b[22;93m"
pattern = re.compile(r"(?P<prefix>text=)(?P<quote>['\"])(?P<value>.*?)(?P=quote)")
def repl(match: re.Match[str]) -> str:
prefix = match.group("prefix")
quote = match.group("quote")
value = match.group("value")
return f"{prefix}{quote}{highlight}{value}{base}{quote}"
return f"{base}{pattern.sub(repl, text)}{_ANSI_RESET}"
color = _ANSI_COLORS.get(kind)
if not color:
return text
return f"{color}{text}{_ANSI_RESET}"
def _log_line(text: str, kind: str = "info", use_lock: bool = False) -> None:
if kind == "query":
text = _query_text_with_question_prefix(text)
styled = _colorize(text, kind)
if use_lock:
with _print_lock:
print(styled)
else:
print(styled)
def _get_current_question_id() -> str | None:
main_mod = sys.modules.get("__main__")
runtime_var = getattr(main_mod, "_CURRENT_QUESTION_ID", None)
if runtime_var is not None and hasattr(runtime_var, "get"):
try:
value = runtime_var.get()
except Exception:
value = None
if value:
return value
return _CURRENT_QUESTION_ID.get()
def _timing_text_with_question_prefix(text: str) -> str:
question_id = _get_current_question_id()
if not question_id:
return text
marker = f"{_TIMING_MARK} "
if marker in text:
return text.replace(marker, f"{marker}{question_id}: ", 1)
return f"{question_id}: {text}"
def _query_text_with_question_prefix(text: str) -> str:
question_id = _get_current_question_id()
if not question_id:
return text
return f" {question_id}: {text.lstrip()}"
def _ck(label: str, ref: float | None = None) -> float:
"""Print a timing checkpoint; returns current perf_counter value."""
now = time.perf_counter()
if _TIMING:
elapsed = now - (ref if ref is not None else _t0)
total = now - _t0
if "– start" in label:
timing = f"(total {total:.3f}s)"
else:
timing = f"+{elapsed:.3f}s (total {total:.3f}s)"
_log_line(
_timing_text_with_question_prefix(f" {_TIMING_MARK} {label}: {timing}"),
kind="timing",
use_lock=True,
)
return now
def _format_activity_id_note(activity_ids: list[str]) -> str:
unique_ids = list(dict.fromkeys(aid for aid in activity_ids if aid))
if not unique_ids:
return ""
if len(unique_ids) == 1:
return f" [ActivityId={unique_ids[0]}]"
shown = ", ".join(unique_ids[:3])
remaining = len(unique_ids) - 3
suffix = f", +{remaining} more" if remaining > 0 else ""
return f" [ActivityIds={shown}{suffix}]"
def _multi_activity_reason(response_meta: list[dict[str, str]]) -> str:
if not response_meta:
return ""
activity_ids = [m.get("activity_id", "") for m in response_meta if m.get("activity_id")]
unique_ids = list(dict.fromkeys(activity_ids))
if len(unique_ids) <= 1:
return ""
partition_ranges = {m.get("partition_range_id", "") for m in response_meta if m.get("partition_range_id")}
physical_partitions = {m.get("physical_partition_id", "") for m in response_meta if m.get("physical_partition_id")}
continuation_count = sum(1 for m in response_meta if m.get("has_continuation") == "1")
retry_hint_count = sum(1 for m in response_meta if m.get("retry_after_ms"))
reasons: list[str] = []
if len(partition_ranges) > 1:
reasons.append(f"fan-out across {len(partition_ranges)} partition key ranges")
elif len(physical_partitions) > 1:
reasons.append(f"fan-out across {len(physical_partitions)} physical partitions")
if continuation_count > 0:
reasons.append(f"pagination/continuation on {continuation_count} response(s)")
if retry_hint_count > 0:
reasons.append(f"retry-after present on {retry_hint_count} response(s)")
if not reasons:
reasons.append("multiple backend executions (possible retries or internal query pipeline calls)")
return f" [Reason: {'; '.join(reasons)}]"
class InvalidLLMResponseError(Exception):
pass
class LRUCache:
def __init__(self, max_size: int):
self.max_size = max(1, int(max_size))
self._data: OrderedDict[str, Any] = OrderedDict()
def get(self, key: str) -> Any | None:
value = self._data.get(key)
if value is None:
return None
self._data.move_to_end(key)
return value
def set(self, key: str, value: Any) -> None:
self._data[key] = value
self._data.move_to_end(key)
while len(self._data) > self.max_size:
self._data.popitem(last=False)
# =============================================================================
# PROMPTS
# =============================================================================
from prompts import (
PRELIMINARY_PROMPT,
EFFICIENT_PRELIMINARY_PROMPT,
SUBQUESTION_PROMPT,
REGENERATE_PROMPT,
GAP_DECOMPOSE_PROMPT,
SYNTHESIS_PROMPT,
EFFICIENT_REGENERATE_PROMPT,
EFFICIENT_SYNTHESIS_PROMPT,
)
# Config loaded at runtime via load_config(); do not import-time read.
CONFIG: dict = {}
_LEGACY_SOURCE_KEY_WARNED: set[str] = set()
def _normalize_source_retrieval_keys(config: dict) -> None:
"""Migrate legacy `cosmos.sources[].retrieval` keys in-place.
Canonical names are ``search_k`` and ``fulltext_search_k`` (dynamic naming).
Legacy names ``vector_k`` and ``fulltext_k`` are still accepted; they are
rewritten to the canonical names and a one-shot ``DeprecationWarning`` is
emitted per legacy key encountered.
"""
sources = (config.get("cosmos") or {}).get("sources")
if not isinstance(sources, list):
return
legacy_map = {"vector_k": "search_k", "fulltext_k": "fulltext_search_k"}
for source in sources:
if not isinstance(source, dict):
continue
retrieval_cfg = source.get("retrieval")
if not isinstance(retrieval_cfg, dict):
continue
for legacy_name, canonical_name in legacy_map.items():
if legacy_name in retrieval_cfg and canonical_name not in retrieval_cfg:
retrieval_cfg[canonical_name] = retrieval_cfg.pop(legacy_name)
if legacy_name not in _LEGACY_SOURCE_KEY_WARNED:
_LEGACY_SOURCE_KEY_WARNED.add(legacy_name)
warnings.warn(
f"cosmos.sources[].retrieval.{legacy_name} is deprecated; "
f"use {canonical_name} instead.",
DeprecationWarning,
stacklevel=3,
)
elif legacy_name in retrieval_cfg:
# Both present: drop the legacy alias silently to avoid ambiguity.
retrieval_cfg.pop(legacy_name, None)
def load_config(path: Path) -> None:
"""Load (or reload) the YAML configuration into the module-level CONFIG dict."""
with open(path) as f:
CONFIG.clear()
CONFIG.update(yaml.safe_load(f))
_normalize_source_retrieval_keys(CONFIG)
for source in (CONFIG.get("cosmos") or {}).get("sources", []):
fulltext_search_options(source.get("retrieval") or {})
global PRELIMINARY_PROMPT, EFFICIENT_PRELIMINARY_PROMPT, SUBQUESTION_PROMPT
global REGENERATE_PROMPT, GAP_DECOMPOSE_PROMPT, SYNTHESIS_PROMPT
global EFFICIENT_REGENERATE_PROMPT, EFFICIENT_SYNTHESIS_PROMPT
preliminary_prefix = (str(CONFIG.get("pipeline", {}).get("preliminary_prefix")) or "").strip()
preliminary_prefix = preliminary_prefix + "\n\n" if preliminary_prefix else ""
subquery_prefix = (str(CONFIG.get("pipeline", {}).get("subquery_prefix")) or "").strip()
subquery_prefix = subquery_prefix + "\n\n" if subquery_prefix else ""
PRELIMINARY_PROMPT = preliminary_prefix + PRELIMINARY_PROMPT
EFFICIENT_PRELIMINARY_PROMPT = preliminary_prefix + EFFICIENT_PRELIMINARY_PROMPT
EFFICIENT_REGENERATE_PROMPT = subquery_prefix + EFFICIENT_REGENERATE_PROMPT
SUBQUESTION_PROMPT = subquery_prefix + SUBQUESTION_PROMPT
dataset_description = (str(CONFIG.get("pipeline", {}).get("dataset_description")) or "").strip()
dataset_description = dataset_description + "\n\n" if dataset_description else ""
SYNTHESIS_PROMPT = dataset_description + SYNTHESIS_PROMPT
EFFICIENT_REGENERATE_PROMPT = dataset_description + EFFICIENT_REGENERATE_PROMPT
EFFICIENT_SYNTHESIS_PROMPT = dataset_description + EFFICIENT_SYNTHESIS_PROMPT
GAP_DECOMPOSE_PROMPT = dataset_description + GAP_DECOMPOSE_PROMPT
REGENERATE_PROMPT = dataset_description + REGENERATE_PROMPT
SUBQUESTION_PROMPT = dataset_description + SUBQUESTION_PROMPT
PRELIMINARY_PROMPT = dataset_description + PRELIMINARY_PROMPT
# =============================================================================
# CONFIGURATION & DATA CLASSES
# =============================================================================
@dataclass
class Question:
question_id: str
question_text: str
group: str | None = None
ground_truth: str | None = None
@dataclass
class RetrievedChunk:
chunk_id: int | str
text: str
similarity: float | None = None
metadata: dict[str, Any] = field(default_factory=dict)
@dataclass
class SubQuestionResult:
sub_question: str
retrieved_chunks: list[dict]
answer: str
@dataclass
class RoundResult:
round_num: int
preliminary_answer_before: str
sub_question_results: list[SubQuestionResult]
regenerated_answer: str | None
# =============================================================================
# LLM CLIENT
# =============================================================================
class LLMClient:
def __init__(self, azure_az_login: bool = False):
llm_cfg = CONFIG["llm"]
# Embedding config: 'embedding' section overrides 'llm' section for backward compatibility
embed_cfg = {**llm_cfg, **CONFIG.get("embedding", {})}
self._azure_az_login = azure_az_login
self._use_rbac_auth = bool(llm_cfg["use_rbac_auth"])
self._use_embed_rbac_auth = bool(embed_cfg.get("use_rbac_auth", False))
self._llm_tenant_id = str(llm_cfg.get("tenant_id", "") or "").strip()
token_scope = llm_cfg.get("token_scope")
self._token_scope = "" if token_scope is None else str(token_scope).strip()
_shared_key = llm_cfg.get("azure_openai_key", "")
self._llm_api_key = str(llm_cfg.get("llm_api_key") or _shared_key or "").strip()
self._embed_api_key = str(embed_cfg.get("embed_api_key") or _shared_key or "").strip()
# Keep for backward compatibility
self._api_key = _shared_key
self._token_provider = None
if self._use_rbac_auth or self._use_embed_rbac_auth:
if not self._token_scope:
raise ValueError(
"llm.token_scope must be a non-empty string when llm.use_rbac_auth or embedding.use_rbac_auth is true"
)
cli_credential = (
AzureCliCredential(tenant_id=self._llm_tenant_id)
if self._llm_tenant_id
else AzureCliCredential()
)
self._token_provider = get_bearer_token_provider(cli_credential, self._token_scope)
self._llm_client = None
self._embed_client = None
self._embed_http_client = None
self._local_http_client = None
self._cfg = llm_cfg
self._embed_cfg = embed_cfg
# Local fallback config: 'local_llm' section overrides 'llm' section for backward compatibility
local_cfg = {**llm_cfg, **CONFIG.get("local_llm", {})}
self._embed_dimensions = int(embed_cfg.get("embed_dimensions") or 0)
self._use_local_fallback_for_subtasks = bool(local_cfg.get("use_local_fallback_for_subtasks", False))
self._local_fallback_endpoint = str(local_cfg.get("local_fallback_endpoint", "http://localhost:11434/api/generate") or "").strip()
self._local_fallback_model = str(local_cfg.get("local_fallback_model", "") or "").strip()
self._premium_semaphore = asyncio.Semaphore(max(1, int(llm_cfg.get("premium_max_concurrency", 4))))
self._local_semaphore = asyncio.Semaphore(max(1, int(local_cfg.get("local_max_concurrency", 8))))
self._response_cache = LRUCache(int(llm_cfg.get("prompt_cache_size", 2048)))
self._embed_cache = LRUCache(int(embed_cfg.get("embed_cache_size", 4096)))
self._local_fallback_failure_threshold = 3
self._local_fallback_cooldown_seconds = 120
self._local_fallback_failures = 0
self._local_fallback_disabled_until = 0.0
self._default_chars_per_token = 4.0
self._chars_per_token_estimate = self._default_chars_per_token
self._min_completion_tokens = 64
self._max_context_tokens_hint: int | None = None
self._max_output_tokens_hint: int | None = None
self._introspection_done = False
self._introspection_lock = asyncio.Lock()
self.total_prompt_chars = 0
self.total_prompt_tokens = 0
self.total_llm_calls = 0
@staticmethod
def _is_key_auth_disabled_error(error: Exception) -> bool:
status_code = getattr(error, "status_code", None)
if status_code != 403:
return False
txt = str(error).lower()
return (
"authenticationtypedisabled" in txt
or "key based authentication is disabled" in txt
or "authentication type is disabled" in txt
)
def _switch_to_rbac_auth(self) -> None:
self._use_rbac_auth = True
if not self._token_scope:
raise ValueError("llm.token_scope must be set before switching Azure OpenAI auth to RBAC")
if self._azure_az_login:
credential = (
AzureCliCredential(tenant_id=self._llm_tenant_id)
if self._llm_tenant_id
else AzureCliCredential()
)
else:
credential = SyncDefaultAzureCredential()
self._token_provider = get_bearer_token_provider(credential, self._token_scope)
self._llm_client = None
self._embed_client = None
def _normalize_embedding(self, embedding: list[float]) -> list[float]:
if self._embed_dimensions <= 0:
return [float(x) for x in embedding]
values = [float(x) for x in embedding]
if len(values) > self._embed_dimensions:
return values[:self._embed_dimensions]
if len(values) < self._embed_dimensions:
return values + [0.0] * (self._embed_dimensions - len(values))
return values
@property
def llm_client(self):
if not self._llm_client:
endpoint = self._cfg["llm_endpoint"]
if endpoint.startswith("http://localhost") or endpoint.startswith("http://127.0.0.1"):
self._llm_client = AsyncOpenAI(
base_url=endpoint,
api_key=self._llm_api_key or "dummy",
timeout=600.0,
max_retries=0,
)
else:
client_kwargs = {
"api_version": self._cfg["api_version"],
"azure_endpoint": endpoint,
}
if self._use_rbac_auth:
client_kwargs["azure_ad_token_provider"] = self._token_provider
else:
if not self._llm_api_key:
raise ValueError("llm.llm_api_key (or llm.azure_openai_key) must be set when llm.use_rbac_auth is false")
client_kwargs["api_key"] = self._llm_api_key
self._llm_client = AsyncAzureOpenAI(**client_kwargs)
return self._llm_client
@property
def embed_client(self) -> AsyncAzureOpenAI:
if not self._embed_client:
client_kwargs = {
"api_version": self._embed_cfg["api_version"],
"azure_endpoint": self._embed_cfg["embed_endpoint"],
}
if self._use_embed_rbac_auth:
client_kwargs["azure_ad_token_provider"] = self._token_provider
else:
if not self._embed_api_key:
raise ValueError("embedding.embed_api_key (or llm.azure_openai_key) must be set when use_rbac_auth is false")
client_kwargs["api_key"] = self._embed_api_key
self._embed_client = AsyncAzureOpenAI(**client_kwargs)
return self._embed_client
def _should_use_local_fallback(self, label: str) -> bool:
if not self._use_local_fallback_for_subtasks:
return False
if self._local_fallback_disabled_until > time.time():
return False
return label.startswith("LLM gap-decompose") or label.startswith("LLM sub-Q answer")
def _is_premium_configured(self) -> bool:
endpoint = str(self._cfg.get("llm_endpoint", "") or "").strip()
model = str(self._cfg.get("llm_model", "") or "").strip()
return bool(endpoint and model)
def _truncate_prompt(self, prompt: str, max_chars: int) -> str:
if len(prompt) <= max_chars:
return prompt
head = int(max_chars * 0.6)
tail = max_chars - head
return (
prompt[:head]
+ "\n\n[... context truncated to satisfy model request constraints ...]\n\n"
+ prompt[-tail:]
)
@staticmethod
def _extract_first_int(value: Any) -> int | None:
if isinstance(value, int):
return value if value > 0 else None
if isinstance(value, str):
match = re.search(r"\d+", value)
if match:
number = int(match.group(0))
return number if number > 0 else None
return None
def _update_limit_hints(self, context_tokens: int | None = None, output_tokens: int | None = None) -> None:
if context_tokens:
self._max_context_tokens_hint = context_tokens if self._max_context_tokens_hint is None else min(self._max_context_tokens_hint, context_tokens)
if output_tokens:
self._max_output_tokens_hint = output_tokens if self._max_output_tokens_hint is None else min(self._max_output_tokens_hint, output_tokens)
async def _introspect_llm_capabilities(self) -> None:
if self._introspection_done:
return
async with self._introspection_lock:
if self._introspection_done:
return
try:
model_name = self._cfg["llm_model"]
model_obj = None
try:
model_obj = await self.llm_client.models.retrieve(model_name)
except Exception:
pass
if model_obj is None:
try:
models = await self.llm_client.models.list()
for candidate in models.data:
if getattr(candidate, "id", None) == model_name:
model_obj = candidate
break
except Exception:
pass
if model_obj is not None:
as_dict = model_obj.model_dump() if hasattr(model_obj, "model_dump") else dict(model_obj)
context_keys = [
"context_length",
"max_context_tokens",
"input_token_limit",
"max_input_tokens",
"token_limit",
]
output_keys = [
"output_token_limit",
"max_output_tokens",
"max_completion_tokens",
]
context_tokens = next((self._extract_first_int(as_dict.get(k)) for k in context_keys if self._extract_first_int(as_dict.get(k))), None)
output_tokens = next((self._extract_first_int(as_dict.get(k)) for k in output_keys if self._extract_first_int(as_dict.get(k))), None)
self._update_limit_hints(context_tokens=context_tokens, output_tokens=output_tokens)
finally:
self._introspection_done = True
def _update_hints_from_headers(self, headers: dict[str, str]) -> None:
context_header_keys = [
"x-model-context-length",
"x-max-context-tokens",
"x-max-input-tokens",
"x-azure-openai-model-context-length",
]
output_header_keys = [
"x-max-output-tokens",
"x-max-completion-tokens",
"x-azure-openai-max-output-tokens",
]
context_tokens = next((self._extract_first_int(headers.get(k)) for k in context_header_keys if self._extract_first_int(headers.get(k))), None)
output_tokens = next((self._extract_first_int(headers.get(k)) for k in output_header_keys if self._extract_first_int(headers.get(k))), None)
self._update_limit_hints(context_tokens=context_tokens, output_tokens=output_tokens)
def _update_hints_from_badrequest(self, error_text: str) -> None:
txt = error_text.lower()
context_patterns = [
r"maximum context length is\s*(\d+)",
r"max(?:imum)?\s+context\s+length\s*(?:is|:)\s*(\d+)",
r"max(?:imum)?\s+input\s+tokens?\s*(?:is|:)\s*(\d+)",
]
output_patterns = [
r"max(?:imum)?\s+output\s+tokens?\s*(?:is|:)\s*(\d+)",
r"max(?:imum)?\s+completion\s+tokens?\s*(?:is|:)\s*(\d+)",
]
context_tokens = None
output_tokens = None
for pattern in context_patterns:
match = re.search(pattern, txt)
if match:
context_tokens = int(match.group(1))
break
for pattern in output_patterns:
match = re.search(pattern, txt)
if match:
output_tokens = int(match.group(1))
break
requested_match = re.search(r"requested\s*(\d+)\s*tokens?\s*\((\d+)\s*in the messages,\s*(\d+)\s*in the completion", txt)
if requested_match:
msg_tokens = int(requested_match.group(2))
completion_tokens = int(requested_match.group(3))
if context_tokens is None:
context_tokens = msg_tokens + completion_tokens - 1
if output_tokens is None and completion_tokens > 0:
output_tokens = completion_tokens - 1
self._update_limit_hints(context_tokens=context_tokens, output_tokens=output_tokens)
def _effective_max_completion_tokens(self, requested_tokens: int) -> int:
limit = requested_tokens
if self._max_output_tokens_hint is not None:
limit = min(limit, self._max_output_tokens_hint)
return max(self._min_completion_tokens, int(limit))
def _effective_max_completion_tokens_for_prompt(self, prompt: str, requested_tokens: int) -> int:
limit = self._effective_max_completion_tokens(requested_tokens)
if self._max_context_tokens_hint is None:
return limit
est_prompt_tokens = max(1, int(len(prompt) / max(1.0, self._chars_per_token_estimate)))
safety_reserve = 32
available_for_output = self._max_context_tokens_hint - est_prompt_tokens - safety_reserve
if available_for_output <= 0:
raise InvalidLLMResponseError(
"Prompt uses full model context window; no room left for completion tokens"
)
return max(1, min(limit, int(available_for_output)))
def _estimate_prompt_tokens(self, prompt: str) -> int:
return max(1, int(len(prompt) / max(1.0, self._chars_per_token_estimate)))
def _effective_prompt_char_limit(self, max_completion_tokens: int) -> int | None:
if self._max_context_tokens_hint is None:
return None
reserve_tokens = max(self._min_completion_tokens, max_completion_tokens) + 256
available_prompt_tokens = self._max_context_tokens_hint - reserve_tokens
if available_prompt_tokens <= 0:
available_prompt_tokens = self._max_context_tokens_hint // 2
return max(2000, int(available_prompt_tokens * self._chars_per_token_estimate))
def _safe_fallback_response(self, label: str) -> str:
if label.startswith("LLM gap-decompose"):
return "[]"
if label.startswith("LLM sub-Q answer"):
return "Insufficient context to answer this sub-question reliably."
if label.startswith("LLM regenerate"):
return "Unable to regenerate answer due request constraints."
if label.startswith("LLM synthesis"):
return "Unable to synthesize final answer due request constraints."
return "Unable to generate response due request constraints."
@staticmethod
def _content_to_text(content: Any) -> str:
if isinstance(content, str):
return content
if isinstance(content, list):
parts: list[str] = []
for item in content:
if isinstance(item, str):
parts.append(item)
continue
if isinstance(item, dict):
text = item.get("text")
if isinstance(text, str):
parts.append(text)
continue
text = getattr(item, "text", None)
if isinstance(text, str):
parts.append(text)
return "".join(parts)
return ""
def _validated_completion_text(self, result: Any, label: str) -> str:
choices = getattr(result, "choices", None) or []
if not choices:
raise InvalidLLMResponseError(f"{label}: no choices in completion result")
choice = choices[0]
finish_reason = str(getattr(choice, "finish_reason", "") or "").strip().lower()
message = getattr(choice, "message", None)
if message is None:
raise InvalidLLMResponseError(f"{label}: missing message in completion choice")
refusal = getattr(message, "refusal", None)
tool_calls = getattr(message, "tool_calls", None)
raw_content = getattr(message, "content", None)
text = self._content_to_text(raw_content)
issues: list[str] = []
if finish_reason in {"tool_calls", "function_call", "content_filter"}:
issues.append(f"finish_reason={finish_reason}")
if isinstance(refusal, str):
if refusal.strip():
issues.append("message.refusal present")
elif refusal:
issues.append("message.refusal present")
if tool_calls:
issues.append("tool_calls present")
if not text or not text.strip():
issues.append("empty content")
if issues:
refusal_present = bool(refusal.strip()) if isinstance(refusal, str) else bool(refusal)
tool_calls_present = bool(tool_calls)
content_type = type(raw_content).__name__ if raw_content is not None else "None"
content_len = len(text) if isinstance(text, str) else 0
diag = (
f"finish_reason={finish_reason or 'None'}, "
f"refusal={refusal_present}, "
f"tool_calls={tool_calls_present}, "
f"content_type={content_type}, "
f"content_len={content_len}"
)
raise InvalidLLMResponseError(f"{label}: invalid completion ({'; '.join(issues)}) [{diag}]")
return text.strip()
async def _complete_premium_once(self, prompt: str, label: str, max_completion_tokens: int) -> str:
await self._introspect_llm_capabilities()
estimated_prompt_tokens = self._estimate_prompt_tokens(prompt)
max_completion_tokens = self._effective_max_completion_tokens_for_prompt(prompt, max_completion_tokens)
if _TIMING:
_log_line(
_timing_text_with_question_prefix(
" "
f"{label} token budget: prompt_est={estimated_prompt_tokens}, "
f"completion={max_completion_tokens}, "
f"context_hint={self._max_context_tokens_hint}, "
f"output_hint={self._max_output_tokens_hint}"
),
kind="timing",
use_lock=True,
)
t = _ck(f"{label} – start")
async with self._premium_semaphore:
raw_response = await self.llm_client.chat.completions.with_raw_response.create(
messages=[{"role": "user", "content": prompt}],
model=self._cfg["llm_model"],
temperature=self._cfg["temperature"],
max_completion_tokens=max_completion_tokens,
)
result = raw_response.parse()
_ck(f"{label} – done", t)
headers = {str(k).lower(): str(v) for k, v in raw_response.headers.items()}
self._update_hints_from_headers(headers)
usage = getattr(result, "usage", None)
prompt_tokens = getattr(usage, "prompt_tokens", None) if usage is not None else None
if isinstance(prompt_tokens, int) and prompt_tokens > 0:
self.total_llm_calls += 1
self.total_prompt_tokens += prompt_tokens
observed = len(prompt) / float(prompt_tokens)
observed = min(8.0, max(2.0, observed))
self._chars_per_token_estimate = (self._chars_per_token_estimate * 0.8) + (observed * 0.2)
return self._validated_completion_text(result, label)
async def _complete_premium(self, prompt: str, retries: int, label: str) -> str:
if retries is None:
retries = int(self._cfg["max_retries"])
max_completion_tokens = int(self._cfg["max_completion_tokens"])
for attempt in range(retries):
try:
return await self._complete_premium_once(prompt, label, max_completion_tokens)
except InvalidLLMResponseError as e:
_log_line(f"Invalid LLM response on {label}: {e} ({attempt + 1}/{retries})", kind="warn")
if attempt + 1 >= retries:
raise
wait = min(2.0 * (2 ** attempt), 30.0)
_log_line(f"Retrying {label} in {wait}s after invalid response", kind="warn")
await asyncio.sleep(wait)
except openai.RateLimitError:
wait = min(5.0 * (2 ** attempt), 5.0 * (2 ** 8))
_log_line(f"Rate limited, retry in {wait}s ({attempt + 1}/{retries})", kind="warn")
await asyncio.sleep(wait)
except openai.BadRequestError as e:
error_text = str(e)
_log_line(
f"BadRequestError details on {label}: {error_text[:400]}",
kind="warn",
)
self._update_hints_from_badrequest(error_text)
err_text = error_text.lower()
prior_completion_tokens = max_completion_tokens
max_completion_tokens = self._effective_max_completion_tokens(max_completion_tokens)
prompt_limit = self._effective_prompt_char_limit(max_completion_tokens)
changed = False
if max_completion_tokens < prior_completion_tokens:
changed = True
if prompt_limit is not None and len(prompt) > prompt_limit:
prompt = self._truncate_prompt(prompt, prompt_limit)
changed = True
if not changed and ("maximum context" in err_text or "max tokens" in err_text or "token" in err_text):
prompt = self._truncate_prompt(prompt, max(2000, int(len(prompt) * 0.7)))
max_completion_tokens = max(self._min_completion_tokens, int(max_completion_tokens * 0.75))
changed = True
if changed:
_log_line(
f"BadRequestError on {label}; retrying with adaptive limits "
f"(max_completion_tokens={max_completion_tokens})",
kind="warn",
)
continue
raise
except (openai.APIStatusError, openai.APIConnectionError, openai.APITimeoutError) as e:
if self._is_key_auth_disabled_error(e) and not self._use_rbac_auth:
try:
self._switch_to_rbac_auth()
_log_line("Azure OpenAI key auth is disabled for this resource; switched to Entra ID RBAC", kind="success")
continue
except Exception as switch_err:
_log_line(f"Failed switching to Entra ID RBAC ({type(switch_err).__name__}); continuing retries", kind="error")
wait = min(5.0 * (2 ** attempt), 5.0 * (2 ** 8))
_log_line(f"LLMAPI error ({type(e).__name__}), retry in {wait}s ({attempt + 1}/{retries})", kind="error")
await asyncio.sleep(wait)
raise Exception("Max retries exceeded")
async def _complete_local(self, prompt: str, label: str) -> str:
if not self._local_fallback_endpoint or not self._local_fallback_model:
raise RuntimeError("Local fallback endpoint/model is not configured")
if self._local_http_client is None:
self._local_http_client = httpx.AsyncClient(timeout=120)
t = _ck(f"{label} (local) – start")
async with self._local_semaphore:
response = await self._local_http_client.post(
self._local_fallback_endpoint,
json={
"model": self._local_fallback_model,
"prompt": prompt,
"stream": False,
"options": {"temperature": self._cfg["temperature"]},
},
headers={"Content-Type": "application/json"},
)
response.raise_for_status()
payload = response.json()
text = payload.get("response")
if not isinstance(text, str):
raise RuntimeError(f"Unexpected local fallback payload: {payload}")
if not text.strip():
raise RuntimeError("Local fallback returned empty content")
_ck(f"{label} (local) – done", t)
return text
async def complete(self, prompt: str, retries: int | None = None, label: str = "LLM complete") -> str:
if retries is None:
retries = int(self._cfg["max_retries"])
self.total_prompt_chars += len(prompt)
use_local_fallback = self._should_use_local_fallback(label)
premium_configured = self._is_premium_configured()
route_key = "premium" if premium_configured else "local"
cache_key = f"{route_key}|{label}|{prompt}"
cached = self._response_cache.get(cache_key)
if isinstance(cached, str):
return cached
premium_error: Exception | None = None
if premium_configured:
try:
premium_response = await self._complete_premium(prompt, retries, label)
self._response_cache.set(cache_key, premium_response)
return premium_response
except Exception as e:
premium_error = e
if use_local_fallback and (not premium_configured or premium_error is not None):
try:
local_response = await self._complete_local(prompt, label)
self._local_fallback_failures = 0
self._response_cache.set(cache_key, local_response)
return local_response
except Exception as e:
self._local_fallback_failures += 1
if self._local_fallback_failures >= self._local_fallback_failure_threshold:
self._local_fallback_disabled_until = time.time() + self._local_fallback_cooldown_seconds
_log_line(
f"Local fallback temporarily disabled for {self._local_fallback_cooldown_seconds}s "
f"after {self._local_fallback_failures} failures",
kind="warn",
)
_log_line(f"Local fallback error ({type(e).__name__}); local fallback unavailable", kind="error")
if premium_error is not None:
if isinstance(premium_error, InvalidLLMResponseError):
_log_line(f"Invalid LLM response on {label}; using safe fallback response", kind="warn")
premium_response = self._safe_fallback_response(label)
elif isinstance(premium_error, openai.BadRequestError):
_log_line(f"BadRequestError on {label}; using safe fallback response", kind="warn")
premium_response = self._safe_fallback_response(label)
elif label.startswith("LLM gap-decompose") or label.startswith("LLM sub-Q answer"):
_log_line(f"{label} failed after retries; using safe fallback response", kind="warn")
premium_response = self._safe_fallback_response(label)
else:
raise premium_error
else:
premium_response = self._safe_fallback_response(label)
self._response_cache.set(cache_key, premium_response)
return premium_response
async def embed(self, text: str) -> list[float]:
cached = self._embed_cache.get(text)
if isinstance(cached, list):
return list(cached)
embed_endpoint = str(self._embed_cfg.get("embed_endpoint", "")).strip()
if embed_endpoint.endswith("/api/embeddings"):
try:
if self._embed_http_client is None:
self._embed_http_client = httpx.AsyncClient(timeout=60)
response = await self._embed_http_client.post(
embed_endpoint,
json={"model": self._embed_cfg["embed_model"], "prompt": text},
headers={"Content-Type": "application/json"},
)
response.raise_for_status()
body = response.text
parsed = json.loads(body)
embedding = parsed.get("embedding")
if not isinstance(embedding, list):
raise ValueError("Invalid Ollama embedding response: missing 'embedding' list")
normalized = self._normalize_embedding(embedding)
self._embed_cache.set(text, normalized)
return list(normalized)
except httpx.HTTPStatusError as e:
detail = e.response.text if e.response is not None else ""
status = e.response.status_code if e.response is not None else "unknown"
raise RuntimeError(f"Embedding endpoint HTTP {status}: {detail[:300]}") from e
except httpx.RequestError as e:
raise RuntimeError(
f"Cannot connect to embedding service at {embed_endpoint}. "
f"Please ensure Ollama (or your configured embedding service) is running and accessible. "
f"Error: {e}"
) from e
except json.JSONDecodeError as e:
raise RuntimeError(f"Invalid JSON response from embedding endpoint {embed_endpoint}: {e}") from e
t = _ck("embed – start")
result = await self.embed_client.embeddings.create(input=[text], model=self._embed_cfg["embed_model"])
_ck("embed – done", t)
normalized = self._normalize_embedding(result.data[0].embedding)
self._embed_cache.set(text, normalized)
return list(normalized)
async def close(self):
if self._llm_client is not None:
await self._llm_client.close()
self._llm_client = None
if self._embed_client is not None: