Repository navigation
Expand file tree
/
Copy pathssot_config.py
More file actions
2970 lines (2526 loc) · 129 KB
/
Copy pathssot_config.py
File metadata and controls
2970 lines (2526 loc) · 129 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 python3
# Copyright 2025-2026 mrveiss
# SPDX-License-Identifier: Apache-2.0
# AutoBot - AI-Powered Automation Platform
# Author: mrveiss
"""
SSOT Configuration Loader for Python
=====================================
Single Source of Truth - reads from .env file with AUTOBOT_ prefix.
This module provides typed configuration access across the entire backend.
All configuration values are defined in the master .env file and accessed
through Pydantic models for type safety and validation.
Usage:
from autobot_shared.ssot_config import get_config, config
# Access VM IPs
redis_ip = config.vm.redis
backend_ip = config.vm.main
# Access ports
backend_port = config.port.backend
# Access computed URLs
backend_url = config.backend_url
redis_url = config.redis_url
# Access LLM settings
default_model = config.llm.default_model
# Access timeouts
http_timeout = config.timeout.http
Issue: #601 - SSOT Phase 1: Foundation
Related: #599 - SSOT Configuration System Epic
"""
from __future__ import annotations
import logging
import os
from enum import Enum
from functools import lru_cache
from pathlib import Path
from typing import Dict, List
from pydantic import AliasChoices, Field, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
from autobot_shared.env_utils import env_int_clamped
# Determine project root for .env file location
def _find_project_root() -> Path:
"""Find the project root directory containing .env file."""
current = Path(__file__).resolve()
for parent in [current] + list(current.parents):
if (parent / ".env").exists():
return parent
# Fallback to runtime location (env var or /opt/autobot)
return Path(os.environ.get("AUTOBOT_BASE_DIR", "/opt/autobot")) # ssot-config-exempt: bootstrap self-reference
PROJECT_ROOT = _find_project_root()
# Default model constants - single source of truth for fallback values (#2553)
# These are used when .env doesn't specify a value.
# All agent/tier model assignments MUST reference these constants — never hardcode
# model name strings elsewhere. Change models here to change the entire system.
# Primary quality model — user-facing chat, research, code analysis, reasoning
DEFAULT_LLM_MODEL = "qwen3.5:9b"
DEFAULT_EMBEDDING_MODEL = "nomic-embed-text:latest"
# Per-role model defaults (6-tier mapping, #2553)
# Each tier is optimised for its workload class — see docs/developer/TIERED_MODEL_ROUTING.md
TRIVIAL_MODEL = "llama3.2:1b" # Trivial tier: simplest queries, no tools/RAG/memory (GH#9050)
ROUTING_MODEL = "llama3.2:1b" # Orchestrator only, no tool use
CLASSIFICATION_MODEL = "gemma2:2b" # Intent detection, classification
LIGHT_PROCESSING_MODEL = "phi3:mini" # Extraction, formatting, lightweight tasks
INSTRUCTION_MODEL = "mistral:7b-instruct" # RAG, entity extraction, instruction following
SYSTEM_MODEL = "dolphin-llama3:8b" # System commands, security (uncensored)
QUALITY_MODEL = DEFAULT_LLM_MODEL # User-facing chat, research, code analysis
# Truthy env-var values — shared by every boolean flag below.
_TRUE_VALUES = {"1", "true", "yes"}
# Best-of-N plan selection (#10583)
# AUTOBOT_PLAN_BEST_OF_N_ENABLED=true → opt-in path (default: off)
# AUTOBOT_PLAN_BEST_OF_N_COUNT=3 → number of candidate plans (default: 3, max: 5)
PLAN_BEST_OF_N_ENABLED: bool = os.environ.get("AUTOBOT_PLAN_BEST_OF_N_ENABLED", "false").lower() in _TRUE_VALUES
# Reuse the shared env_int_clamped helper (safe-parse — no import-time crash on
# bad input — + clamp); do NOT reimplement it locally (#11022 audit follow-up).
PLAN_BEST_OF_N_COUNT: int = env_int_clamped("AUTOBOT_PLAN_BEST_OF_N_COUNT", 3, 2, 5)
# #10602: ClaimVerifier wiring — adds KB RAG + optional research-agent LLM call per claim.
# Default OFF because it adds latency/cost; set AUTOBOT_CLAIM_VERIFICATION_ENABLED=true to opt in.
CLAIM_VERIFICATION_ENABLED: bool = os.environ.get("AUTOBOT_CLAIM_VERIFICATION_ENABLED", "false").lower() in _TRUE_VALUES
# #10602: Self-improvement write path — pure plumbing, no extra LLM calls until outcomes exist.
# Default ON. Set AUTOBOT_SELF_IMPROVEMENT_ENABLED=false to disable.
SELF_IMPROVEMENT_ENABLED: bool = os.environ.get("AUTOBOT_SELF_IMPROVEMENT_ENABLED", "true").lower() in _TRUE_VALUES
# #11015: Planning context (learned-strategy + similar-trajectory retrieval) at plan time.
# Kill-switch for the always-on ChromaDB/Redis I/O added by #10580/#10581 — set
# AUTOBOT_PLANNING_CONTEXT_ENABLED=false to disable the retrieval entirely (e.g. when
# the vector store is cold/slow). Default ON to preserve the shipped behaviour.
PLANNING_CONTEXT_ENABLED: bool = os.environ.get("AUTOBOT_PLANNING_CONTEXT_ENABLED", "true").lower() in _TRUE_VALUES
# #10602: Subagent reflection pass — adds LLM score + optional revision per task.
# Default OFF; set AUTOBOT_SUBAGENT_REFLECTION_ENABLED=true to opt in.
SUBAGENT_REFLECTION_ENABLED: bool = (
os.environ.get("AUTOBOT_SUBAGENT_REFLECTION_ENABLED", "false").lower() in _TRUE_VALUES
)
class VMConfig(BaseSettings):
"""
VM IP address configuration.
Supports the 6-VM distributed architecture:
- Main (WSL) - Backend API + VNC Desktop
- Frontend (VM1) - Web interface
- NPU Worker (VM2) - Hardware AI acceleration
- Redis (VM3) - Data layer
- AI Stack (VM4) - AI processing
- Browser (VM5) - Web automation
"""
model_config = SettingsConfigDict(
env_file=str(PROJECT_ROOT / ".env"),
env_file_encoding="utf-8",
extra="ignore",
)
# Issue #2953: Defaults changed to 127.0.0.1 for single-host installs.
# Distributed installs override these via AUTOBOT_*_HOST env vars in .env.
main: str = Field(default="127.0.0.1", alias="AUTOBOT_BACKEND_HOST")
frontend: str = Field(default="127.0.0.1", alias="AUTOBOT_FRONTEND_HOST")
npu: str = Field(default="127.0.0.1", alias="AUTOBOT_NPU_WORKER_HOST")
redis: str = Field(default="127.0.0.1", alias="AUTOBOT_REDIS_HOST")
aistack: str = Field(default="127.0.0.1", alias="AUTOBOT_AI_STACK_HOST")
chromadb: str = Field(default="127.0.0.1", alias="AUTOBOT_CHROMADB_HOST")
browser: str = Field(default="127.0.0.1", alias="AUTOBOT_BROWSER_SERVICE_HOST")
tts: str = Field(default="127.0.0.1", alias="AUTOBOT_TTS_WORKER_HOST")
slm: str = Field(default="127.0.0.1", alias="AUTOBOT_SLM_HOST") # Issue #768, #2953
ollama: str = Field(default="127.0.0.1", alias="AUTOBOT_OLLAMA_HOST")
class PortConfig(BaseSettings):
"""Service port configuration."""
model_config = SettingsConfigDict(
env_file=str(PROJECT_ROOT / ".env"),
env_file_encoding="utf-8",
extra="ignore",
)
backend: int = Field(default=8001, alias="AUTOBOT_BACKEND_PORT")
frontend: int = Field(default=5173, alias="AUTOBOT_FRONTEND_PORT")
redis: int = Field(default=6379, alias="AUTOBOT_REDIS_PORT")
ollama: int = Field(default=11434, alias="AUTOBOT_OLLAMA_PORT")
vnc: int = Field(default=6080, alias="AUTOBOT_VNC_PORT")
browser: int = Field(default=9001, alias="AUTOBOT_BROWSER_SERVICE_PORT") # Issue #4052: 9001; 3000 is Grafana
aistack: int = Field(default=8080, alias="AUTOBOT_AI_STACK_PORT")
chromadb: int = Field(default=8100, alias="AUTOBOT_CHROMADB_PORT") # Issue #3094: 8100 matches Ansible deploy
npu: int = Field(default=8081, alias="AUTOBOT_NPU_WORKER_PORT")
tts: int = Field(default=8083, alias="AUTOBOT_TTS_WORKER_PORT") # Issue #928; #3431: 8082 WSL2/Hyper-V reserved
slm: int = Field(default=8000, alias="AUTOBOT_SLM_PORT") # Issue #768
prometheus: int = Field(default=9090, alias="AUTOBOT_PROMETHEUS_PORT")
grafana: int = Field(default=3000, alias="AUTOBOT_GRAFANA_PORT")
chrome_cdp: int = Field(default=9222, alias="AUTOBOT_CHROME_CDP_PORT") # Issue #3829: Chrome DevTools Protocol
class LLMConfig(BaseSettings):
"""
LLM model configuration with multi-provider support.
Supports multiple LLM providers with different endpoints:
- Ollama (local): http://127.0.0.1:11434
- OpenAI: https://api.openai.com/v1
- Anthropic: https://api.anthropic.com/v1
- Custom providers via environment variables
Each model type can specify its own provider via AUTOBOT_{MODEL}_PROVIDER
environment variables, defaulting to the main AUTOBOT_LLM_PROVIDER.
"""
model_config = SettingsConfigDict(
env_file=str(PROJECT_ROOT / ".env"),
env_file_encoding="utf-8",
extra="ignore",
)
# Primary models — each role maps to its optimal 6-tier (#2553)
default_model: str = Field(default=DEFAULT_LLM_MODEL, alias="AUTOBOT_DEFAULT_LLM_MODEL")
embedding_model: str = Field(default=DEFAULT_EMBEDDING_MODEL, alias="AUTOBOT_EMBEDDING_MODEL")
trivial_model: str = Field(default=TRIVIAL_MODEL, alias="AUTOBOT_TRIVIAL_MODEL") # GH#9050
classification_model: str = Field(default=CLASSIFICATION_MODEL, alias="AUTOBOT_CLASSIFICATION_MODEL")
reasoning_model: str = Field(default=QUALITY_MODEL, alias="AUTOBOT_REASONING_MODEL")
rag_model: str = Field(default=INSTRUCTION_MODEL, alias="AUTOBOT_RAG_MODEL")
coding_model: str = Field(default=QUALITY_MODEL, alias="AUTOBOT_CODING_MODEL")
# 6-tier model fields (#2553)
light_processing_model: str = Field(default=LIGHT_PROCESSING_MODEL, alias="AUTOBOT_LIGHT_PROCESSING_MODEL")
instruction_model: str = Field(default=INSTRUCTION_MODEL, alias="AUTOBOT_INSTRUCTION_MODEL")
system_model: str = Field(default=SYSTEM_MODEL, alias="AUTOBOT_SYSTEM_MODEL")
# Agent/workflow models — each maps to its optimal tier (#2553)
orchestrator_model: str = Field(default=ROUTING_MODEL, alias="AUTOBOT_ORCHESTRATOR_MODEL")
agent_model: str = Field(default=QUALITY_MODEL, alias="AUTOBOT_AGENT_MODEL")
research_model: str = Field(default=QUALITY_MODEL, alias="AUTOBOT_RESEARCH_MODEL")
analysis_model: str = Field(default=QUALITY_MODEL, alias="AUTOBOT_ANALYSIS_MODEL")
planning_model: str = Field(default=QUALITY_MODEL, alias="AUTOBOT_PLANNING_MODEL")
# Timeout (seconds)
timeout: int = Field(default=30, alias="AUTOBOT_LLM_TIMEOUT")
# Default provider for all models (can be overridden per-model)
provider: str = Field(default="ollama", alias="AUTOBOT_LLM_PROVIDER")
# LLM cost-efficiency toggles (#10597)
# Prompt caching is a pure cost win → default on. Chat tiered routing
# downgrades models by complexity (precision-sensitive) → default off until
# validated via knowledge/rag_benchmarks.py.
llm_prompt_cache_default: bool = Field(default=True, alias="AUTOBOT_LLM_PROMPT_CACHE_DEFAULT")
chat_tiered_routing: bool = Field(default=False, alias="AUTOBOT_CHAT_TIERED_ROUTING")
# Response cache for chat(): only near-deterministic, safely-reusable
# requests are cached (low temperature, no tools/structured-output/thinking).
# Above this temperature responses must vary, so they are never cached.
llm_response_cache: bool = Field(default=True, alias="AUTOBOT_LLM_RESPONSE_CACHE")
llm_cache_max_temperature: float = Field(default=0.3, alias="AUTOBOT_LLM_CACHE_MAX_TEMPERATURE")
# Cross-vendor second-opinion verifier tier (#12618). A second LLM call on a
# genuinely distinct provider doubles spend on the verification path, so this
# is a preference/threshold pair — the master on/off switch lives in
# ``feature.cross_vendor_review_enabled`` (default off).
# Comma-separated provider names in preference order (e.g. "anthropic,openai");
# empty means "use registry registration order" (no forced preference).
cross_vendor_verifier_providers: str = Field(default="", alias="AUTOBOT_LLC_CROSS_VENDOR_VERIFIER_PROVIDERS")
# Below this confidence, an agreeing cross-vendor verdict still escalates to
# human review rather than auto-resolving (design's "both low-confidence" row).
cross_vendor_low_confidence_threshold: float = Field(
default=0.5, alias="AUTOBOT_LLC_CROSS_VENDOR_LOW_CONFIDENCE_THRESHOLD"
)
# Prepend the [Source N] citation instruction to the KB context block (#10652,
# #10736). When True the prompt includes "Answer … cite as [Source N]"; when
# False the [Source N] labels still render but the instruction is omitted.
# Renamed from chat_grounding_enabled (AUTOBOT_CHAT_GROUNDING) — old env var
# still accepted for backward-compat via AliasChoices.
chat_citation_instruction_enabled: bool = Field(
default=True,
validation_alias=AliasChoices(
"AUTOBOT_CHAT_CITATION_INSTRUCTION",
"AUTOBOT_CHAT_GROUNDING",
),
)
# Inline AgentResponseJudge on chat replies (#10599, §3.3).
# OFF by default — each judge call adds one LLM round-trip.
# Enable with AUTOBOT_CHAT_INLINE_JUDGE=true.
chat_inline_judge_enabled: bool = Field(default=False, alias="AUTOBOT_CHAT_INLINE_JUDGE")
# Minimum judge overall_score to accept a response without one regeneration
# attempt. Only used when chat_inline_judge_enabled=True.
chat_inline_judge_threshold: float = Field(default=0.6, alias="AUTOBOT_CHAT_INLINE_JUDGE_THRESHOLD")
# Knowledge-ingestion cognifier batching (#10598). When True, extraction
# cognifiers pack multiple chunks into ONE structured LLM call (index-keyed)
# instead of one call per chunk — a pure token/round-trip win, with an
# automatic per-chunk fallback that keeps correctness. Default on.
cognifier_multichunk_batching: bool = Field(default=True, alias="AUTOBOT_COGNIFIER_MULTICHUNK_BATCHING")
# Per-chunk character cap when packing chunks into a batched cognifier prompt,
# so one oversized chunk can't blow the context window (0 = no truncation).
cognifier_batch_max_chunk_chars: int = Field(default=2000, alias="AUTOBOT_COGNIFIER_BATCH_MAX_CHUNK_CHARS")
# Provider-specific endpoints (each provider can have its own URL)
ollama_endpoint: str = Field(default="http://127.0.0.1:11434", alias="AUTOBOT_OLLAMA_ENDPOINT")
openai_endpoint: str = Field(default="https://api.openai.com/v1", alias="AUTOBOT_OPENAI_ENDPOINT")
anthropic_endpoint: str = Field(default="https://api.anthropic.com/v1", alias="AUTOBOT_ANTHROPIC_ENDPOINT")
custom_endpoint: str = Field(default="", alias="AUTOBOT_CUSTOM_LLM_ENDPOINT")
lmstudio_host: str = Field(default="http://127.0.0.1:1234", alias="LMSTUDIO_HOST")
# GPU Ollama endpoint for model-to-endpoint routing (#1070)
ollama_gpu_endpoint: str = Field(default="", alias="AUTOBOT_OLLAMA_GPU_ENDPOINT")
ollama_gpu_models: str = Field(default="", alias="AUTOBOT_OLLAMA_GPU_MODELS")
# Connection pool size for Ollama requests (#1154)
# Default 6 matches typical concurrent capacity for RTX 4070 (8GB VRAM)
# Override with AUTOBOT_OLLAMA_POOL_MAX_CONNECTIONS
ollama_pool_max_connections: int = Field(default=6, alias="AUTOBOT_OLLAMA_POOL_MAX_CONNECTIONS")
# API keys (optional - can also come from provider-specific env vars)
openai_api_key: str = Field(default="", alias="OPENAI_API_KEY")
anthropic_api_key: str = Field(default="", alias="ANTHROPIC_API_KEY")
# Web-search providers (#9022 SearXNG, #9023 Brave). Empty = disabled.
# SearXNG needs no API key — only the self-hosted instance URL. Optional
# HTTP Basic / token auth for instances behind a reverse proxy.
searxng_instance_url: str = Field(default="", alias="SEARXNG_INSTANCE_URL")
searxng_basic_auth_user: str = Field(default="", alias="SEARXNG_BASIC_AUTH_USER")
searxng_basic_auth_pass: str = Field(default="", alias="SEARXNG_BASIC_AUTH_PASS")
searxng_token: str = Field(default="", alias="SEARXNG_TOKEN")
brave_search_api_key: str = Field(default="", alias="BRAVE_SEARCH_API_KEY")
# Claude escalation feature flag (#8171): disabled by default so local LLM
# path is unchanged unless AUTOBOT_CLAUDE_ESCALATION_ENABLED=true is set.
claude_escalation_enabled: bool = Field(default=False, alias="AUTOBOT_CLAUDE_ESCALATION_ENABLED")
claude_escalation_threshold: float = Field(default=7.0, alias="AUTOBOT_CLAUDE_ESCALATION_THRESHOLD")
# LlamaIndex-specific configuration for RAG/vectorization
# These are explicit settings - no fallbacks. Must be configured correctly.
llamaindex_llm_provider: str = Field(default="ollama", alias="AUTOBOT_LLAMAINDEX_LLM_PROVIDER")
llamaindex_llm_endpoint: str = Field(default="http://127.0.0.1:11434", alias="AUTOBOT_LLAMAINDEX_LLM_ENDPOINT")
llamaindex_llm_model: str = Field(default=DEFAULT_LLM_MODEL, alias="AUTOBOT_LLAMAINDEX_LLM_MODEL")
llamaindex_embedding_provider: str = Field(default="ollama", alias="AUTOBOT_LLAMAINDEX_EMBEDDING_PROVIDER")
llamaindex_embedding_endpoint: str = Field(
default="http://127.0.0.1:11434", alias="AUTOBOT_LLAMAINDEX_EMBEDDING_ENDPOINT"
)
# Chat template for local providers (ollama, vllm, llama.cpp).
# OpenAI/Anthropic/Gemini skip this — they format server-side.
# Supported values: chatml, zephyr, vicuna
chat_template: str = Field(default="chatml", alias="AUTOBOT_CHAT_TEMPLATE")
def get_ollama_endpoint_for_model(self, model_name: str) -> str:
"""Route Ollama requests to GPU or CPU endpoint by model (#1070).
Args:
model_name: Ollama model name (e.g. 'qwen3.5:9b')
Returns:
Ollama base URL (no /api suffix)
"""
if self.ollama_gpu_endpoint and self.ollama_gpu_models:
gpu_set = {m.strip().lower() for m in self.ollama_gpu_models.split(",") if m.strip()}
if model_name.strip().lower() in gpu_set:
return self.ollama_gpu_endpoint
return self.ollama_endpoint
def get_provider_for_agent(self, agent_id: str) -> str:
"""
Get the LLM provider for a specific agent.
Looks up AUTOBOT_{AGENT_ID}_PROVIDER environment variable.
Falls back to AUTOBOT_LLM_PROVIDER if not set.
Args:
agent_id: Agent identifier (e.g., 'orchestrator', 'research', 'code_analysis')
Returns:
Provider name (ollama, openai, anthropic, custom)
Example:
# In .env:
AUTOBOT_RESEARCH_PROVIDER=openai
AUTOBOT_CODE_ANALYSIS_PROVIDER=anthropic
# In code:
provider = config.llm.get_provider_for_agent("research") # Returns "openai"
provider = config.llm.get_provider_for_agent("chat") # Returns default provider
"""
# Check for agent-specific provider override via environment
env_key = f"AUTOBOT_{agent_id.upper()}_PROVIDER"
agent_provider = os.environ.get(env_key, "")
if agent_provider:
return agent_provider
# Fall back to default provider
return self.provider
def get_endpoint_for_agent(self, agent_id: str) -> str:
"""
Get the LLM API endpoint URL for a specific agent.
First checks for agent-specific endpoint (AUTOBOT_{AGENT_ID}_ENDPOINT),
then falls back to provider endpoint based on agent's provider setting.
Args:
agent_id: Agent identifier (e.g., 'orchestrator', 'research', 'code_analysis')
Returns:
API endpoint URL for the agent
Example:
# In .env:
AUTOBOT_RESEARCH_PROVIDER=openai
AUTOBOT_CODE_ANALYSIS_ENDPOINT=http://custom-claude-proxy:8080
# In code:
endpoint = config.llm.get_endpoint_for_agent("research") # Returns OpenAI endpoint
endpoint = config.llm.get_endpoint_for_agent("code_analysis") # Returns custom endpoint
"""
# Check for agent-specific endpoint override
env_key = f"AUTOBOT_{agent_id.upper()}_ENDPOINT"
agent_endpoint = os.environ.get(env_key, "")
if agent_endpoint:
return agent_endpoint
# Get provider for this agent and return its endpoint
provider = self.get_provider_for_agent(agent_id)
return self.get_endpoint_for_provider(provider)
def get_model_for_agent(self, agent_id: str) -> str:
"""
Get the LLM model name for a specific agent.
Looks up AUTOBOT_{AGENT_ID}_MODEL environment variable.
Falls back to AUTOBOT_DEFAULT_LLM_MODEL if not set.
Args:
agent_id: Agent identifier (e.g., 'orchestrator', 'research', 'code_analysis')
Returns:
Model name (e.g., 'gpt-4', 'claude-3-opus', 'qwen3.5:9b')
Example:
# In .env:
AUTOBOT_RESEARCH_MODEL=gpt-4-turbo
AUTOBOT_CODE_ANALYSIS_MODEL=claude-3-opus-20240229
# In code:
model = config.llm.get_model_for_agent("research") # Returns "gpt-4-turbo"
model = config.llm.get_model_for_agent("chat") # Returns default model
"""
# Check for agent-specific model override via environment
env_key = f"AUTOBOT_{agent_id.upper()}_MODEL"
agent_model = os.environ.get(env_key, "")
if agent_model:
return agent_model
# Fall back to default model
return self.default_model
def get_agent_config(self, agent_id: str) -> dict:
"""
Get complete LLM configuration for a specific agent.
Returns a dictionary with provider, endpoint, model, and API key
for the specified agent.
Args:
agent_id: Agent identifier (e.g., 'orchestrator', 'research', 'code_analysis')
Returns:
Dict with keys: provider, endpoint, model, api_key, timeout
Example:
config = config.llm.get_agent_config("research")
# Returns: {
# "provider": "openai",
# "endpoint": "https://api.openai.com/v1",
# "model": "gpt-4-turbo",
# "api_key": "sk-...",
# "timeout": 30
# }
"""
provider = self.get_provider_for_agent(agent_id)
return {
"provider": provider,
"endpoint": self.get_endpoint_for_agent(agent_id),
"model": self.get_model_for_agent(agent_id),
"api_key": self._get_api_key_for_provider(provider),
"timeout": self.timeout,
}
def _get_api_key_for_provider(self, provider: str) -> str:
"""Get API key for a specific provider."""
if provider.lower() == "openai":
return self.openai_api_key
elif provider.lower() == "anthropic":
return self.anthropic_api_key
# Ollama and custom providers may use different auth mechanisms
return ""
def get_endpoint_for_provider(self, provider: str) -> str:
"""
Get the API endpoint URL for a specific provider.
Args:
provider: Provider name (ollama, openai, anthropic, custom)
Returns:
API endpoint URL
"""
endpoints = {
"ollama": self.ollama_endpoint,
"openai": self.openai_endpoint,
"anthropic": self.anthropic_endpoint,
"custom": self.custom_endpoint,
"lmstudio": self.lmstudio_host,
}
return endpoints.get(provider.lower(), self.ollama_endpoint)
# Backward compatibility aliases
def get_provider_for_model(self, model_type: str) -> str:
"""Alias for get_provider_for_agent for backward compatibility."""
return self.get_provider_for_agent(model_type)
def get_endpoint_for_model(self, model_type: str) -> str:
"""
Get the API endpoint URL for a specific model type.
Args:
model_type: Model type (embedding, orchestrator, research, coding, etc.)
Returns:
API endpoint URL for the model's provider
"""
provider = self.get_provider_for_model(model_type)
return self.get_endpoint_for_provider(provider)
class TimeoutConfig(BaseSettings):
"""
Timeout configuration — all values in seconds unless noted.
Fields are env-overridable via AUTOBOT_TIMEOUT_* variables. The
existing AUTOBOT_API_TIMEOUT / AUTOBOT_LLM_TIMEOUT / … aliases are
preserved for backward compatibility.
"""
model_config = SettingsConfigDict(
env_file=str(PROJECT_ROOT / ".env"),
env_file_encoding="utf-8",
extra="ignore",
)
# ------------------------------------------------------------------ #
# HTTP / REST clients (seconds) #
# ------------------------------------------------------------------ #
# Generic HTTP API call (used by most aiohttp/httpx sessions)
http: float = Field(default=10.0, alias="AUTOBOT_TIMEOUT_HTTP")
# Health / liveness probes — must be short to avoid blocking startup
health_check: float = Field(default=3.0, alias="AUTOBOT_HEALTH_CHECK_TIMEOUT")
# Connectivity probes (quick: just confirm a socket can be reached)
connect: float = Field(default=5.0, alias="AUTOBOT_TIMEOUT_CONNECT")
# ------------------------------------------------------------------ #
# LLM / AI inference (seconds) #
# ------------------------------------------------------------------ #
# Synchronous / short LLM call (classification, routing, embedding)
llm: float = Field(default=30.0, alias="AUTOBOT_LLM_TIMEOUT")
# Long-running LLM call or agent loop step (research, code analysis)
llm_long: float = Field(default=120.0, alias="AUTOBOT_TIMEOUT_LLM_LONG")
# ------------------------------------------------------------------ #
# Redis operations (seconds) #
# ------------------------------------------------------------------ #
# Individual Redis command (get/set/pipeline)
redis_op: float = Field(default=2.0, alias="AUTOBOT_TIMEOUT_REDIS_OP")
# ------------------------------------------------------------------ #
# Subprocess / shell commands (seconds) #
# ------------------------------------------------------------------ #
# Quick subprocess (health query, lspci, xrandr, …)
subprocess_short: float = Field(default=5.0, alias="AUTOBOT_TIMEOUT_SUBPROCESS_SHORT")
# Standard subprocess (git operations, rsync small payload)
subprocess: float = Field(default=30.0, alias="AUTOBOT_TIMEOUT_SUBPROCESS")
# Long-running subprocess (Ansible playbook, large rsync, deploy)
subprocess_long: float = Field(default=300.0, alias="AUTOBOT_TIMEOUT_SUBPROCESS_LONG")
# Very long subprocess (full deployment pipeline, TLS provisioning)
subprocess_deploy: float = Field(default=600.0, alias="AUTOBOT_TIMEOUT_SUBPROCESS_DEPLOY")
# ------------------------------------------------------------------ #
# MCP / skill processes (seconds) #
# ------------------------------------------------------------------ #
# Time allowed for an MCP server subprocess to start up
mcp_startup: float = Field(default=10.0, alias="AUTOBOT_TIMEOUT_MCP_STARTUP")
# Time allowed for a single MCP tool call round-trip
mcp_call: float = Field(default=30.0, alias="AUTOBOT_TIMEOUT_MCP_CALL")
# ------------------------------------------------------------------ #
# WebSocket (seconds) #
# ------------------------------------------------------------------ #
websocket: float = Field(default=30.0, alias="AUTOBOT_WEBSOCKET_TIMEOUT")
# ------------------------------------------------------------------ #
# Background tasks (seconds) #
# ------------------------------------------------------------------ #
# Default cap for a background task before it is considered hung
background_task: float = Field(default=600.0, alias="AUTOBOT_TIMEOUT_BACKGROUND_TASK")
# ------------------------------------------------------------------ #
# A2A task manager (seconds) #
# ------------------------------------------------------------------ #
# How long an A2A task remains queryable in Redis before eviction.
# 60s was the old in-memory eviction window; Redis persistence needs a
# realistic poll window — default 3600s (1 hour), overridable via env.
a2a_task_ttl: float = Field(default=3600.0, alias="AUTOBOT_A2A_TASK_TTL_SECONDS")
# ------------------------------------------------------------------ #
# Elevation session (seconds) #
# ------------------------------------------------------------------ #
# How long an approved elevation session remains valid before the user
# must re-authenticate. Default 900 s (15 min) matches the UI label.
# Override with AUTOBOT_ELEVATION_SESSION_TTL. (#10723)
elevation_session_ttl: int = Field(default=900, alias="AUTOBOT_ELEVATION_SESSION_TTL")
# ------------------------------------------------------------------ #
# Skill / code validation (seconds) #
# ------------------------------------------------------------------ #
# Sandbox execution timeout for skill package tests
skill_test: float = Field(default=15.0, alias="AUTOBOT_TIMEOUT_SKILL_TEST")
# Secure sandbox / subprocess execution (docker, shell code execution)
sandbox: float = Field(default=300.0, alias="AUTOBOT_SANDBOX_TIMEOUT")
# ------------------------------------------------------------------ #
# Service-to-service / LLM request (seconds) #
# ------------------------------------------------------------------ #
# General inter-service HTTP request (e.g. ServiceHTTPClient)
default_request: float = Field(default=30.0, alias="AUTOBOT_REQUEST_TIMEOUT")
# LLM inference request (longer than generic HTTP — model may take time)
llm_request: float = Field(default=60.0, alias="AUTOBOT_LLM_REQUEST_TIMEOUT")
# ------------------------------------------------------------------ #
# HTTP connection pool (seconds) #
# ------------------------------------------------------------------ #
connection_pool_read: float = Field(default=60.0, alias="AUTOBOT_POOL_READ_TIMEOUT")
connection_pool_write: float = Field(default=30.0, alias="AUTOBOT_POOL_WRITE_TIMEOUT")
connection_pool: float = Field(default=30.0, alias="AUTOBOT_POOL_TIMEOUT")
# ------------------------------------------------------------------ #
# Legacy / frontend aliases (milliseconds) #
# ------------------------------------------------------------------ #
# Kept for backward compat — frontend reads this as ms
api: int = Field(default=10000, alias="AUTOBOT_API_TIMEOUT")
api_retry_attempts: int = Field(default=3, alias="AUTOBOT_API_RETRY_ATTEMPTS")
api_retry_delay: int = Field(default=1000, alias="AUTOBOT_API_RETRY_DELAY")
# ------------------------------------------------------------------ #
# Convenience properties #
# ------------------------------------------------------------------ #
@property
def api_seconds(self) -> float:
"""Get legacy api timeout in seconds (milliseconds / 1000)."""
return self.api / 1000.0
@property
def http_seconds(self) -> float:
"""Alias — returns http field directly (already in seconds)."""
return self.http
class RedisConfig(BaseSettings):
"""Redis database configuration."""
model_config = SettingsConfigDict(
env_file=str(PROJECT_ROOT / ".env"),
env_file_encoding="utf-8",
extra="ignore",
)
# Enable/disable Redis
enabled: bool = Field(default=True, alias="AUTOBOT_REDIS_ENABLED")
# Database assignments — defaults match redis-databases.yaml SSOT (#2670)
db_main: int = Field(default=0, alias="AUTOBOT_REDIS_DB_MAIN")
db_knowledge: int = Field(default=1, alias="AUTOBOT_REDIS_DB_KNOWLEDGE")
db_prompts: int = Field(default=2, alias="AUTOBOT_REDIS_DB_PROMPTS")
db_agents: int = Field(default=3, alias="AUTOBOT_REDIS_DB_AGENTS")
db_metrics: int = Field(default=4, alias="AUTOBOT_REDIS_DB_METRICS")
db_cache: int = Field(default=5, alias="AUTOBOT_REDIS_DB_CACHE")
db_sessions: int = Field(default=6, alias="AUTOBOT_REDIS_DB_SESSIONS")
db_tasks: int = Field(default=7, alias="AUTOBOT_REDIS_DB_TASKS")
db_logs: int = Field(default=8, alias="AUTOBOT_REDIS_DB_LOGS")
db_temp: int = Field(default=9, alias="AUTOBOT_REDIS_DB_TEMP")
db_audit: int = Field(default=10, alias="AUTOBOT_REDIS_DB_AUDIT")
db_analytics: int = Field(default=11, alias="AUTOBOT_REDIS_DB_ANALYTICS")
db_celery_broker: int = Field(default=14, alias="AUTOBOT_REDIS_DB_CELERY_BROKER")
db_celery_results: int = Field(default=15, alias="AUTOBOT_REDIS_DB_CELERY_RESULTS")
db_testing: int = Field(default=13, alias="AUTOBOT_REDIS_DB_TESTING")
# LangGraph checkpoint TTL (#1481, #3231)
checkpoint_ttl_minutes: int = Field(
default=43200,
alias="AUTOBOT_REDIS_CHECKPOINT_TTL_MINUTES",
description=(
"TTL in minutes for LangGraph checkpoint keys. "
"Active sessions refresh on read so the window resets on each "
"interaction. Default is 30 days (43200 min) to accommodate "
"human-in-the-loop pauses that span multiple days without "
"silently expiring the checkpoint. Set to 0 to disable expiry."
),
)
# Security
password: str | None = Field(default=None, alias="AUTOBOT_REDIS_PASSWORD")
class CacheCoordinatorConfig(BaseSettings):
"""
Cache coordinator configuration for memory pressure management.
Controls automatic eviction when system memory is under pressure.
The coordinator monitors memory usage and triggers cache eviction
across all caches to maintain performance and prevent OOM conditions.
Issue: #743 - Memory Optimization (Phase 3.1)
"""
model_config = SettingsConfigDict(
env_file=str(PROJECT_ROOT / ".env"),
env_file_encoding="utf-8",
extra="ignore",
)
pressure_threshold: float = Field(
default=0.80,
alias="AUTOBOT_CACHE_COORDINATOR_PRESSURE_THRESHOLD",
description="Trigger eviction at this memory usage percentage (0.0-1.0)",
)
eviction_ratio: float = Field(
default=0.20,
alias="AUTOBOT_CACHE_COORDINATOR_EVICTION_RATIO",
description="Percentage of each cache to evict during pressure (0.0-1.0)",
)
check_interval: int = Field(
default=30,
alias="AUTOBOT_CACHE_COORDINATOR_CHECK_INTERVAL",
description="Seconds between memory pressure checks",
)
class CacheRedisConfig(BaseSettings):
"""
Redis connection pool configuration for caching.
Controls connection pooling behavior for Redis cache operations.
Separate from main Redis config to allow independent tuning.
Issue: #743 - Memory Optimization (Phase 3.1)
"""
model_config = SettingsConfigDict(
env_file=str(PROJECT_ROOT / ".env"),
env_file_encoding="utf-8",
extra="ignore",
)
max_connections: int = Field(
default=20,
alias="AUTOBOT_CACHE_REDIS_MAX_CONNECTIONS",
description="Maximum Redis connections in pool",
)
socket_timeout: float = Field(
default=5.0,
alias="AUTOBOT_CACHE_REDIS_SOCKET_TIMEOUT",
description="Socket timeout in seconds",
)
socket_connect_timeout: float = Field(
default=5.0,
alias="AUTOBOT_CACHE_REDIS_SOCKET_CONNECT_TIMEOUT",
description="Socket connection timeout in seconds",
)
class CacheL1Config(BaseSettings):
"""
L1 (in-memory) cache size configuration.
Controls maximum number of items stored in each in-memory LRU cache.
These are fast but consume RAM, so sizes should be tuned based on
available memory and usage patterns.
Issue: #743 - Memory Optimization (Phase 3.1)
"""
model_config = SettingsConfigDict(
env_file=str(PROJECT_ROOT / ".env"),
env_file_encoding="utf-8",
extra="ignore",
)
lru_memory: int = Field(
default=1000,
alias="AUTOBOT_CACHE_L1_LRU_MEMORY",
description="Max items in LRU memory cache",
)
embedding: int = Field(
default=1000,
alias="AUTOBOT_CACHE_L1_EMBEDDING",
description="Max items in embedding cache",
)
llm_response: int = Field(
default=100,
alias="AUTOBOT_CACHE_L1_LLM_RESPONSE",
description="Max items in LLM response cache",
)
ast: int = Field(default=1000, alias="AUTOBOT_CACHE_L1_AST", description="Max items in AST cache")
file_content: int = Field(
default=500,
alias="AUTOBOT_CACHE_L1_FILE_CONTENT",
description="Max items in file content cache",
)
weak_cache: int = Field(
default=128,
alias="AUTOBOT_CACHE_L1_WEAK_CACHE",
description="Max items in weak reference cache",
)
semantic_cache_max_size: int = Field(
default=10000,
alias="AUTOBOT_CACHE_L1_SEMANTIC_MAX_SIZE",
description="Max entries in semantic query cache ChromaDB collection",
)
search_result_cache_max_size: int = Field(
default=10000,
alias="AUTOBOT_SEARCH_RESULT_CACHE_SIZE",
description="Max entries in NPU semantic search result cache (#8154)",
)
search_result_cache_ttl: int = Field(
default=1800,
alias="AUTOBOT_SEARCH_RESULT_CACHE_TTL",
description="TTL in seconds for NPU search result cache entries (#8154)",
)
class CacheL2Config(BaseSettings):
"""
L2 (Redis) cache TTL configuration.
Controls time-to-live (in seconds) for different types of cached data in Redis.
Longer TTLs reduce recomputation but may serve stale data.
Shorter TTLs keep data fresh but increase computation load.
Issue: #743 - Memory Optimization (Phase 3.1)
"""
model_config = SettingsConfigDict(
env_file=str(PROJECT_ROOT / ".env"),
env_file_encoding="utf-8",
extra="ignore",
)
llm_response: int = Field(
default=300,
alias="AUTOBOT_CACHE_L2_LLM_RESPONSE",
description="TTL for LLM responses in seconds (5 minutes)",
)
knowledge: int = Field(
default=300,
alias="AUTOBOT_CACHE_L2_KNOWLEDGE",
description="TTL for knowledge base entries in seconds (5 minutes)",
)
session: int = Field(
default=300,
alias="AUTOBOT_CACHE_L2_SESSION",
description="TTL for session data in seconds (5 minutes)",
)
user_prefs: int = Field(
default=3600,
alias="AUTOBOT_CACHE_L2_USER_PREFS",
description="TTL for user preferences in seconds (1 hour)",
)
computed: int = Field(
default=7200,
alias="AUTOBOT_CACHE_L2_COMPUTED",
description="TTL for computed results in seconds (2 hours)",
)
semantic_cache: int = Field(
default=3600,
alias="AUTOBOT_CACHE_L2_SEMANTIC",
description="TTL for semantic query cache responses in seconds (1 hour)",
)
semantic_cache_threshold: float = Field(
default=0.95,
alias="AUTOBOT_CACHE_SEMANTIC_THRESHOLD",
description="Cosine similarity threshold for semantic cache hits (0.5-1.0)",
)
kb_dedup_threshold: float = Field(
default=0.92,
alias="AUTOBOT_KB_DEDUP_THRESHOLD",
description=(
"Cosine similarity threshold for KB fact deduplication (0.5-1.0). "
"Facts whose nearest ChromaDB neighbour exceeds this score are skipped."
),
)
class CacheConfig(BaseSettings):
"""
Master cache configuration for AutoBot.
Aggregates all cache-related settings including coordinator,
Redis connection pool, L1 (in-memory) sizes, and L2 (Redis) TTLs.
Usage:
from autobot_shared.ssot_config import config
# Access cache settings
pressure = config.cache.coordinator.pressure_threshold
max_conns = config.cache.redis.max_connections
lru_size = config.cache.l1.lru_memory
ttl = config.cache.l2.llm_response
Issue: #743 - Memory Optimization (Phase 3.1)
"""
model_config = SettingsConfigDict(
env_file=str(PROJECT_ROOT / ".env"),
env_file_encoding="utf-8",
extra="ignore",
)
# Sub-configurations
coordinator: CacheCoordinatorConfig = Field(default_factory=CacheCoordinatorConfig)
redis: CacheRedisConfig = Field(default_factory=CacheRedisConfig)
l1: CacheL1Config = Field(default_factory=CacheL1Config)
l2: CacheL2Config = Field(default_factory=CacheL2Config)
class AuthConfig(BaseSettings):
"""Authentication domain configuration.
Controls auth-level defaults that are shared across middleware and API layers.
Override via environment variable (e.g. AUTOBOT_AUTH_DOMAIN=corp.example.com).
"""
model_config = SettingsConfigDict(
env_file=str(PROJECT_ROOT / ".env"),
env_file_encoding="utf-8",
extra="ignore",
)
domain: str = Field(
default="autobot.local",
alias="AUTOBOT_AUTH_DOMAIN",
description=(
"Email domain used for synthetic/fallback user accounts. "
"Default 'autobot.local' is used for auth-disabled, single-user, "
"and dev-mode synthetic accounts."
),
)
sso_callback_hosts: str = Field(
default="localhost,127.0.0.1,autobot.local",
alias="AUTOBOT_SSO_CALLBACK_HOSTS",
description=(
"Comma-separated allowlist of valid hosts for OAuth2/OIDC callback URLs. "
"Prevents authorization code phishing via X-Forwarded-Host manipulation. "
"Production deployments MUST override this with actual domain(s). "
"Security: MVA-3396 (M-2)"
),
)
enforce_https_callbacks: bool = Field(
default=False,
alias="AUTOBOT_ENFORCE_HTTPS_CALLBACKS",
description=(
"Enforce HTTPS for OAuth2/OIDC callback URLs in production. "
"Set to true for production deployments. "
"Security: MVA-3396 (M-2)"
),
)
# ------------------------------------------------------------------
# Connector OAuth application credentials (ADR-007 / GH#9019)
#
# Per-provider OAuth *application* client_id/client_secret registered by the
# operator. Empty by default — a provider's "Connect" flow is disabled until
# its credentials are configured. These identify AutoBot's OAuth app; the
# resulting user refresh/access tokens are stored via SecretsService.
# ------------------------------------------------------------------
google_oauth_client_id: str = Field(
default="",
alias="AUTOBOT_GOOGLE_OAUTH_CLIENT_ID",
description="OAuth client_id for Google connectors (Drive). Empty disables the Google Connect flow.",
)
google_oauth_client_secret: str = Field(
default="",
alias="AUTOBOT_GOOGLE_OAUTH_CLIENT_SECRET",
description="OAuth client_secret for Google connectors (Drive).",
)
microsoft_oauth_client_id: str = Field(
default="",
alias="AUTOBOT_MICROSOFT_OAUTH_CLIENT_ID",
description="OAuth client_id for Microsoft connectors (OneDrive/SharePoint). Empty disables the flow.",
)