-
Notifications
You must be signed in to change notification settings - Fork 54.1k
Expand file tree
/
Copy pathconfig.py
More file actions
3755 lines (3391 loc) · 168 KB
/
Copy pathconfig.py
File metadata and controls
3755 lines (3391 loc) · 168 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
# -*- coding: utf-8 -*-
"""
===================================
A股自选股智能分析系统 - 配置管理模块
===================================
职责:
1. 使用单例模式管理全局配置
2. 从 .env 文件加载敏感配置
3. 提供类型安全的配置访问接口
"""
import json
import logging
import os
import re
from functools import lru_cache
from pathlib import Path
from typing import Any, Dict, List, Literal, Optional, Tuple
from urllib.parse import unquote, urlparse
from dotenv import load_dotenv, dotenv_values
from dataclasses import dataclass, field
from src.core.config_manager import unescape_compose_sensitive_env_value
from src.report_language import (
is_supported_report_language_value,
normalize_report_language,
)
from src.notification_routing import parse_notification_route_channels
from src.notification_noise import (
NOTIFICATION_SEVERITIES,
is_supported_notification_severity,
parse_notification_quiet_hours,
validate_notification_timezone,
)
from src.notification_contracts import (
is_feishu_app_bot_configured,
is_feishu_static_configured,
)
from src.services.stock_list_parser import split_stock_list
from src.llm.backend_registry import (
AUTO_AGENT_BACKEND_ID,
GENERATION_ONLY_BACKEND_IDS,
LOCAL_CLI_GENERATION_BACKEND_IDS,
LITELLM_BACKEND_ID,
OPENCODE_CLI_BACKEND_ID,
SUPPORTED_AGENT_GENERATION_BACKENDS,
SUPPORTED_AGENT_UI_BACKENDS,
SUPPORTED_GENERATION_BACKENDS,
)
from src.llm.local_cli_backend import (
DEFAULT_GENERATION_BACKEND_MAX_CONCURRENCY,
DEFAULT_LOCAL_CLI_BACKEND_MAX_CONCURRENCY,
DEFAULT_LOCAL_CLI_MAX_OUTPUT_BYTES,
DEFAULT_LOCAL_CLI_TIMEOUT_SECONDS,
MAX_GENERATION_BACKEND_MAX_CONCURRENCY,
MAX_LOCAL_CLI_BACKEND_MAX_CONCURRENCY,
MAX_LOCAL_CLI_OUTPUT_BYTES,
MAX_LOCAL_CLI_TIMEOUT_SECONDS,
)
from src.llm import generation_params as llm_generation_params
from src.llm.hermes import (
HERMES_DEFAULT_BASE_URL,
HERMES_DEFAULT_MODEL,
HERMES_DEFAULT_PROTOCOL,
HermesConfigIssue,
hermes_blocked_route_candidates,
hermes_model_info,
is_reserved_hermes_name,
parse_hermes_channel,
route_identity_candidates,
route_deployment_origins,
route_has_hermes,
)
from src.scheduler import normalize_schedule_times
from src.utils.market_review_region import normalize_market_review_region_lenient
logger = logging.getLogger(__name__)
@dataclass
class ConfigIssue:
"""Structured configuration validation issue with a severity level.
Attributes:
severity: One of "error", "warning", or "info".
message: Human-readable description of the issue.
field: The environment variable / config field name most relevant to
this issue (empty string when not applicable).
"""
severity: Literal["error", "warning", "info"]
message: str
field: str = ""
code: str = ""
def __str__(self) -> str: # noqa: D105
return self.message
_MANAGED_LITELLM_KEY_PROVIDERS = {"gemini", "vertex_ai", "anthropic", "openai", "deepseek"}
SUPPORTED_LLM_CHANNEL_PROTOCOLS = ("openai", "anthropic", "gemini", "vertex_ai", "deepseek", "ollama")
SUPPORTED_LLM_CHANNEL_API_SURFACES = ("chat_completions", "responses")
_FALLBACK_LITELLM_MODEL_PROVIDERS = _MANAGED_LITELLM_KEY_PROVIDERS | set(SUPPORTED_LLM_CHANNEL_PROTOCOLS) | {
"minimax",
"cohere",
"huggingface",
"bedrock",
"sagemaker",
"azure",
"replicate",
"together_ai",
"palm",
"text-completion-openai",
"command-r",
"groq",
"cerebras",
"fireworks_ai",
"friendliai",
"openrouter",
"xai",
}
_FALSEY_ENV_VALUES = {"0", "false", "no", "off"}
PROMPT_CACHE_DIAGNOSTICS_LEVELS = {"off", "basic", "debug"}
SUPPORTED_AGENT_BACKENDS = {"auto", "litellm", "codex_app_server"}
TICKFLOW_KLINE_ADJUST_VALUES = {"none", "forward", "backward", "forward_additive", "backward_additive"}
# Fallback defaults used when ANSPIRE_API_KEYS is reused as legacy OpenAI-compatible source.
# These are compatibility examples; actual availability should be validated by Anspire console/model entitlement.
ANSPIRE_LLM_BASE_URL_DEFAULT = "https://open-gateway.anspire.cn/v6"
ANSPIRE_LLM_MODEL_DEFAULT = "Doubao-Seed-2.0-lite"
def _has_ntfy_topic_endpoint(value: Optional[str]) -> bool:
"""Return whether an ntfy URL points at a concrete topic endpoint."""
raw_url = (value or "").strip()
if not raw_url:
return False
parsed = urlparse(raw_url)
if parsed.scheme.lower() not in {"http", "https"} or not parsed.netloc:
return False
return any(unquote(segment).strip() for segment in parsed.path.split("/") if segment)
def _has_gotify_base_url(value: Optional[str]) -> bool:
"""Return whether a Gotify URL points at a server base URL, not /message."""
raw_url = (value or "").strip().rstrip("/")
if not raw_url:
return False
parsed = urlparse(raw_url)
if parsed.scheme.lower() not in {"http", "https"} or not parsed.netloc:
return False
if parsed.query or parsed.fragment:
return False
path_segments = [segment for segment in parsed.path.split("/") if segment]
return not (path_segments and path_segments[-1].lower() == "message")
def normalize_tickflow_kline_adjust(value: Optional[str]) -> str:
"""Normalize TickFlow daily K-line adjustment mode."""
normalized = (value or "none").strip().lower()
if normalized in TICKFLOW_KLINE_ADJUST_VALUES:
return normalized
logger.warning(
"Invalid TICKFLOW_KLINE_ADJUST=%r; falling back to none",
value,
)
return "none"
def parse_prompt_cache_diagnostics_level(value: Optional[str]) -> str:
"""Parse prompt-cache diagnostics level with a conservative fallback."""
normalized = (value or "off").strip().lower()
if normalized in PROMPT_CACHE_DIAGNOSTICS_LEVELS:
return normalized
logger.warning(
"Invalid LLM_PROMPT_CACHE_DIAGNOSTICS_LEVEL=%r; falling back to off",
value,
)
return "off"
AGENT_MAX_STEPS_DEFAULT = 10
FUNDAMENTAL_STAGE_TIMEOUT_SECONDS_DEFAULT = 8.0
NEWS_STRATEGY_WINDOWS: Dict[str, int] = {
"ultra_short": 1,
"short": 3,
"medium": 7,
"long": 30,
}
@dataclass(frozen=True)
class AgentContextCompressionPreset:
"""Preset values for visible chat history compression."""
trigger_tokens: int
protected_turns: int
summary_target_tokens: int
# P1 reserves this budget for future prompt-size controls; it is not
# enforced by the current rolling-summary state table.
history_budget_tokens: int
AGENT_CONTEXT_COMPRESSION_DEFAULT_PROFILE = "balanced"
AGENT_CONTEXT_COMPRESSION_PROFILES: Dict[str, AgentContextCompressionPreset] = {
"cost": AgentContextCompressionPreset(
trigger_tokens=6000,
protected_turns=2,
summary_target_tokens=900,
history_budget_tokens=4000,
),
"balanced": AgentContextCompressionPreset(
trigger_tokens=12000,
protected_turns=4,
summary_target_tokens=1500,
history_budget_tokens=8000,
),
"long_context_raw_first": AgentContextCompressionPreset(
trigger_tokens=24000,
protected_turns=6,
summary_target_tokens=2600,
history_budget_tokens=14000,
),
}
def parse_env_bool(value: Optional[str], default: bool = False) -> bool:
"""Parse common truthy/falsey environment-style values."""
if value is None:
return default
normalized = value.strip().lower()
if not normalized:
return default
return normalized not in _FALSEY_ENV_VALUES
def parse_env_int(
value: Optional[str],
default: int,
*,
field_name: str,
minimum: Optional[int] = None,
maximum: Optional[int] = None,
) -> int:
"""Parse an integer env value with warning + fallback semantics."""
raw_value = value
if raw_value is None or not str(raw_value).strip():
parsed = int(default)
else:
try:
parsed = int(str(raw_value).strip())
except (TypeError, ValueError):
logger.warning(
"%s=%r is not a valid integer; falling back to %s",
field_name,
raw_value,
default,
)
parsed = int(default)
if minimum is not None and parsed < minimum:
logger.warning(
"%s=%r is below minimum %s; clamping to %s",
field_name,
parsed,
minimum,
minimum,
)
parsed = minimum
if maximum is not None and parsed > maximum:
logger.warning(
"%s=%r is above maximum %s; clamping to %s",
field_name,
parsed,
maximum,
maximum,
)
parsed = maximum
return parsed
def parse_env_float(
value: Optional[str],
default: float,
*,
field_name: str,
minimum: Optional[float] = None,
maximum: Optional[float] = None,
) -> float:
"""Parse a float env value with warning + fallback semantics."""
raw_value = value
if raw_value is None or not str(raw_value).strip():
parsed = float(default)
else:
try:
parsed = float(str(raw_value).strip())
except (TypeError, ValueError):
logger.warning(
"%s=%r is not a valid number; falling back to %s",
field_name,
raw_value,
default,
)
parsed = float(default)
if minimum is not None and parsed < minimum:
logger.warning(
"%s=%r is below minimum %s; clamping to %s",
field_name,
parsed,
minimum,
minimum,
)
parsed = minimum
if maximum is not None and parsed > maximum:
logger.warning(
"%s=%r is above maximum %s; clamping to %s",
field_name,
parsed,
maximum,
maximum,
)
parsed = maximum
return parsed
def normalize_news_strategy_profile(value: Optional[str]) -> str:
"""Normalize news strategy profile to known values."""
candidate = (value or "short").strip().lower()
return candidate if candidate in NEWS_STRATEGY_WINDOWS else "short"
def resolve_news_window_days(news_max_age_days: int, news_strategy_profile: Optional[str]) -> int:
"""Resolve effective news window days from profile and global max-age."""
profile = normalize_news_strategy_profile(news_strategy_profile)
profile_days = NEWS_STRATEGY_WINDOWS.get(profile, NEWS_STRATEGY_WINDOWS["short"])
return max(1, min(max(1, int(news_max_age_days)), profile_days))
def normalize_agent_context_compression_profile(value: Optional[str]) -> str:
"""Normalize visible-chat context compression profile values."""
candidate = (value or AGENT_CONTEXT_COMPRESSION_DEFAULT_PROFILE).strip().lower()
if candidate in AGENT_CONTEXT_COMPRESSION_PROFILES:
return candidate
logger.warning(
"Invalid AGENT_CONTEXT_COMPRESSION_PROFILE=%r; falling back to %s",
value,
AGENT_CONTEXT_COMPRESSION_DEFAULT_PROFILE,
)
return AGENT_CONTEXT_COMPRESSION_DEFAULT_PROFILE
def get_agent_context_compression_preset(profile: Optional[str]) -> AgentContextCompressionPreset:
"""Return the preset for a normalized profile, falling back to balanced."""
normalized = normalize_agent_context_compression_profile(profile)
return AGENT_CONTEXT_COMPRESSION_PROFILES[normalized]
def parse_agent_context_compression_int(
value: Optional[str],
default: int,
*,
field_name: str,
minimum: int,
maximum: int,
) -> int:
"""Parse compression integers; empty/invalid/out-of-range values follow preset defaults."""
raw_value = value
if raw_value is None or not str(raw_value).strip():
return int(default)
try:
parsed = int(str(raw_value).strip())
except (TypeError, ValueError):
logger.warning(
"%s=%r is not a valid integer; falling back to preset default %s",
field_name,
raw_value,
default,
)
return int(default)
if parsed < minimum or parsed > maximum:
logger.warning(
"%s=%r is outside supported range [%s, %s]; falling back to preset default %s",
field_name,
parsed,
minimum,
maximum,
default,
)
return int(default)
return parsed
def canonicalize_llm_channel_protocol(value: Optional[str]) -> str:
"""Normalize a protocol label into a LiteLLM provider identifier."""
candidate = (value or "").strip().lower().replace("-", "_")
aliases = {
"openai_compatible": "openai",
"openai_compat": "openai",
"claude": "anthropic",
"google": "gemini",
"vertex": "vertex_ai",
"vertexai": "vertex_ai",
}
return aliases.get(candidate, candidate)
def canonicalize_llm_channel_api_surface(value: Optional[str]) -> str:
"""Normalize an LLM channel endpoint surface label."""
candidate = (value or "").strip().lower().replace("-", "_")
aliases = {
"chat": "chat_completions",
"chat_completion": "chat_completions",
"completions": "chat_completions",
"response": "responses",
"responses_api": "responses",
}
return aliases.get(candidate, candidate)
def normalize_llm_channel_api_surface(value: Optional[str]) -> str:
"""Return a supported endpoint surface, defaulting to Chat Completions."""
normalized = canonicalize_llm_channel_api_surface(value)
if normalized in SUPPORTED_LLM_CHANNEL_API_SURFACES:
return normalized
return "chat_completions"
def is_supported_llm_channel_api_surface_value(value: Optional[str]) -> bool:
"""Return whether a raw API surface is blank or recognized."""
canonical = canonicalize_llm_channel_api_surface(value)
return not canonical or canonical in SUPPORTED_LLM_CHANNEL_API_SURFACES
@lru_cache(maxsize=1)
def get_litellm_model_providers() -> frozenset[str]:
"""Return provider identifiers from the installed LiteLLM routing enum.
LiteLLM adds direct providers independently of this repository. Loading
its enum keeps channel validation aligned with the actual router instead
of relying on a permanently incomplete local allow-list. The fallback is
only for lightweight test stubs or a broken optional import; a production
installation gets the complete provider set from its pinned LiteLLM.
"""
providers = set(_FALLBACK_LITELLM_MODEL_PROVIDERS)
try:
from litellm.types.utils import LlmProviders
providers.update(
str(provider.value).strip().lower()
for provider in LlmProviders
if str(getattr(provider, "value", "")).strip()
)
except (ImportError, AttributeError, TypeError):
logger.debug("LiteLLM provider metadata unavailable; using the compatibility fallback")
return frozenset(providers)
def get_explicit_llm_channel_model_provider(model: str) -> str:
"""Return the explicit LiteLLM provider prefix, if the model has one.
A slash alone does not establish a provider: OpenAI-compatible gateways
commonly expose provider-owned IDs such as ``Qwen/Qwen3`` or
``deepseek-ai/DeepSeek-V3``. Only prefixes understood as LiteLLM providers
are treated as routing declarations.
"""
normalized_model = (model or "").strip()
if "/" not in normalized_model:
return ""
raw_prefix = normalized_model.split("/", 1)[0].lower()
canonical_prefix = canonicalize_llm_channel_protocol(raw_prefix)
providers = get_litellm_model_providers()
if raw_prefix in providers:
return raw_prefix
if canonical_prefix in providers:
return canonical_prefix
return ""
def apply_litellm_api_surface(model: str, api_surface: Optional[str]) -> str:
"""Encode an explicit API surface in a LiteLLM wire model.
LiteLLM's ``provider/responses/model`` convention keeps the public Router
alias stable while letting ``completion()`` bridge messages, streaming,
tools, responses, and usage through the provider's Responses endpoint.
"""
normalized_model = (model or "").strip()
if not normalized_model or normalize_llm_channel_api_surface(api_surface) != "responses":
return normalized_model
provider = get_explicit_llm_channel_model_provider(normalized_model)
if provider != "openai":
raise ValueError(
"Responses API surface requires a normalized openai/<model> route; "
f"got {normalized_model!r}"
)
provider, remainder = normalized_model.split("/", 1)
if remainder.startswith("responses/"):
return normalized_model
return f"{provider}/responses/{remainder}"
def resolve_llm_channel_protocol(
protocol: Optional[str],
*,
base_url: Optional[str] = None,
models: Optional[List[str]] = None,
channel_name: Optional[str] = None,
) -> str:
"""Resolve the effective protocol for a channel."""
explicit = canonicalize_llm_channel_protocol(protocol)
if explicit in SUPPORTED_LLM_CHANNEL_PROTOCOLS:
return explicit
for model in models or []:
if "/" not in model:
continue
prefix = canonicalize_llm_channel_protocol(model.split("/", 1)[0])
if prefix in SUPPORTED_LLM_CHANNEL_PROTOCOLS:
return prefix
# Infer from channel name (e.g. "deepseek" -> deepseek, "gemini" -> gemini)
if channel_name:
name_protocol = canonicalize_llm_channel_protocol(channel_name)
if name_protocol in SUPPORTED_LLM_CHANNEL_PROTOCOLS:
return name_protocol
if base_url:
parsed = urlparse(base_url)
if parsed.hostname in {"127.0.0.1", "localhost", "0.0.0.0"}:
# Default to openai for local servers (vLLM, LM Studio, LocalAI, etc.).
# Ollama users should set PROTOCOL=ollama explicitly or name the channel "ollama".
return "openai"
return "openai"
return ""
def channel_allows_empty_api_key(protocol: Optional[str], base_url: Optional[str]) -> bool:
"""Return True when a channel can run without an API key."""
resolved_protocol = resolve_llm_channel_protocol(protocol, base_url=base_url)
if resolved_protocol == "ollama":
return True
parsed = urlparse(base_url or "")
return parsed.hostname in {"127.0.0.1", "localhost", "0.0.0.0"}
def normalize_llm_channel_model(model: str, protocol: Optional[str], base_url: Optional[str] = None) -> str:
"""Attach a provider prefix when the model omits it."""
normalized_model = model.strip()
if not normalized_model:
return normalized_model
resolved_protocol = resolve_llm_channel_protocol(protocol, base_url=base_url, models=[normalized_model])
if "/" in normalized_model:
# The model already has a slash, e.g. 'deepseek-ai/DeepSeek-V3'.
# Check if the prefix is a known LiteLLM provider; if so, keep it.
# Otherwise (e.g. HuggingFace-style IDs on SiliconFlow), prepend
# the resolved protocol so LiteLLM routes via the correct handler.
raw_prefix, remainder = normalized_model.split("/", 1)
prefix = raw_prefix.lower()
canonical_prefix = canonicalize_llm_channel_protocol(prefix)
providers = get_litellm_model_providers()
if prefix in providers:
return normalized_model
if canonical_prefix in providers:
return f"{canonical_prefix}/{remainder}"
# Not a real provider prefix — add one so LiteLLM routes correctly.
if resolved_protocol:
return f"{resolved_protocol}/{normalized_model}"
return normalized_model
if not resolved_protocol:
return normalized_model
return f"{resolved_protocol}/{normalized_model}"
def find_incompatible_llm_channel_models(
models: List[str],
protocol: Optional[str],
api_surface: Optional[str],
base_url: Optional[str] = None,
) -> List[str]:
"""Return models whose actual LiteLLM route conflicts with the surface.
Responses routing is implemented through LiteLLM's OpenAI bridge, so both
the channel protocol and every normalized model route must resolve to the
OpenAI provider. This is the shared invariant used by validation, runtime
loading, diagnostics, and screening.
"""
if normalize_llm_channel_api_surface(api_surface) != "responses":
return []
resolved_protocol = resolve_llm_channel_protocol(
protocol,
base_url=base_url,
models=models,
)
if resolved_protocol != "openai":
return [model for model in models if (model or "").strip()]
incompatible: List[str] = []
for model in models:
normalized_model = normalize_llm_channel_model(model, resolved_protocol, base_url)
if normalized_model and get_explicit_llm_channel_model_provider(normalized_model) != "openai":
incompatible.append(model)
return incompatible
def find_llm_channel_surface_conflicts(
channels: List[Dict[str, Any]],
) -> Dict[str, Tuple[str, ...]]:
"""Return public route aliases declared with more than one API surface."""
route_surfaces: Dict[str, set[str]] = {}
for channel in channels:
if not isinstance(channel, dict) or not channel.get("enabled", True):
continue
protocol = str(channel.get("protocol") or "")
base_url = str(channel.get("base_url") or "")
surface = normalize_llm_channel_api_surface(channel.get("api_surface"))
for raw_model in channel.get("models") or []:
model = normalize_llm_channel_model(str(raw_model), protocol, base_url)
if model:
route_surfaces.setdefault(model, set()).add(surface)
return {
model: tuple(sorted(surfaces))
for model, surfaces in route_surfaces.items()
if len(surfaces) > 1
}
def get_configured_llm_models(model_list: List[Dict[str, Any]]) -> List[str]:
"""Return non-legacy model names declared in Router model_list order.
Uses the top-level ``model_name`` (the routing alias that users set in
LITELLM_MODEL) rather than ``litellm_params.model`` (the wire-level
model identifier). For channel-built entries both are identical, but
YAML configs may define a friendly alias that differs from the
underlying provider/model path.
"""
models: List[str] = []
seen: set = set()
for entry in model_list or []:
# Prefer top-level model_name (router routing key); fall back to
# litellm_params.model for entries that omit it.
name = str(entry.get("model_name") or "").strip()
if not name:
params = entry.get("litellm_params", {}) or {}
name = str(params.get("model") or "").strip()
if not name or name.startswith("__legacy_") or name in seen:
continue
seen.add(name)
models.append(name)
return models
def resolve_litellm_wire_model(
model: str,
model_list: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""Resolve a router alias to its underlying LiteLLM wire model."""
return llm_generation_params.resolve_litellm_wire_model(model, model_list)
def resolve_litellm_thinking_enabled(
model: str,
model_list: Optional[List[Dict[str, Any]]] = None,
request_overrides: Optional[Dict[str, Any]] = None,
) -> Optional[bool]:
"""Resolve whether the outgoing LiteLLM request explicitly enables thinking."""
return llm_generation_params.resolve_litellm_thinking_enabled(
model,
model_list=model_list,
request_overrides=request_overrides,
)
def get_fixed_litellm_temperature(
model: str,
model_list: Optional[List[Dict[str, Any]]] = None,
request_overrides: Optional[Dict[str, Any]] = None,
) -> Optional[float]:
"""Return a provider-mandated temperature for known strict models."""
return llm_generation_params.get_fixed_litellm_temperature(
model,
model_list=model_list,
request_overrides=request_overrides,
)
def normalize_litellm_temperature(
model: str,
temperature: Optional[float],
*,
default: float = 0.7,
model_list: Optional[List[Dict[str, Any]]] = None,
request_overrides: Optional[Dict[str, Any]] = None,
) -> float:
"""Normalize temperature before sending a LiteLLM request."""
return llm_generation_params.normalize_litellm_temperature(
model,
temperature,
default=default,
model_list=model_list,
request_overrides=request_overrides,
)
def resolve_unified_llm_temperature(model: str) -> float:
"""Resolve the raw unified LLM temperature with backward-compatible fallbacks."""
llm_temperature_raw = os.getenv("LLM_TEMPERATURE")
if llm_temperature_raw and llm_temperature_raw.strip():
try:
return float(llm_temperature_raw)
except (ValueError, TypeError):
pass
provider_temperature_env = {
"gemini": "GEMINI_TEMPERATURE",
"vertex_ai": "GEMINI_TEMPERATURE",
"anthropic": "ANTHROPIC_TEMPERATURE",
"openai": "OPENAI_TEMPERATURE",
"deepseek": "OPENAI_TEMPERATURE",
}
preferred_env = provider_temperature_env.get(_get_litellm_provider(model))
if preferred_env:
preferred_value = os.getenv(preferred_env)
if preferred_value and preferred_value.strip():
try:
return float(preferred_value)
except (ValueError, TypeError):
pass
for env_name in ("GEMINI_TEMPERATURE", "ANTHROPIC_TEMPERATURE", "OPENAI_TEMPERATURE"):
env_value = os.getenv(env_name)
if env_value and env_value.strip():
try:
return float(env_value)
except (ValueError, TypeError):
continue
return 0.7
def _get_litellm_provider(model: str) -> str:
"""Extract the LiteLLM provider prefix from a model string."""
if not model:
return ""
if "/" in model:
return model.split("/", 1)[0]
return "openai"
def _uses_direct_env_provider(model: str) -> bool:
"""Whether runtime handles the model via direct litellm env/provider resolution."""
provider = _get_litellm_provider(model)
return bool(provider) and provider not in _MANAGED_LITELLM_KEY_PROVIDERS
def _matches_route_set(model: str, routes: set[str]) -> bool:
"""Loose safety match for Hermes/provenance checks, not normal route availability."""
return bool(route_identity_candidates(model) & set(routes or set()))
def _matches_exact_route(model: str, routes: set[str]) -> bool:
"""Match the Router's top-level model_name exactly for normal availability checks."""
normalized_model = str(model or "").strip()
return bool(normalized_model) and normalized_model in set(routes or set())
def normalize_agent_litellm_model(
model: str,
configured_models: Optional[set[str]] = None,
) -> str:
"""Normalize AGENT_LITELLM_MODEL while preserving configured router aliases."""
normalized_model = (model or "").strip()
if not normalized_model:
return ""
if "/" not in normalized_model:
if configured_models and normalized_model in configured_models:
return normalized_model
return f"openai/{normalized_model}"
return normalized_model
def get_effective_agent_primary_model(config: "Config") -> str:
"""Return the effective Agent primary model with fallback inheritance."""
configured_router_models = set(
get_configured_llm_models(getattr(config, "llm_model_list", []) or [])
)
configured_agent_model = normalize_agent_litellm_model(
getattr(config, "agent_litellm_model", ""),
configured_models=configured_router_models,
)
if configured_agent_model:
return configured_agent_model
return (getattr(config, "litellm_model", "") or "").strip()
def get_effective_agent_models_to_try(config: "Config") -> List[str]:
"""Return Agent model try-order: primary + global fallbacks (deduped)."""
configured_router_models = set(
get_configured_llm_models(getattr(config, "llm_model_list", []) or [])
)
raw_models = [get_effective_agent_primary_model(config)] + (
getattr(config, "litellm_fallback_models", []) or []
)
seen = set()
ordered_models: List[str] = []
for model in raw_models:
normalized_model = (model or "").strip()
if not normalized_model:
continue
dedupe_key = normalize_agent_litellm_model(
normalized_model,
configured_models=configured_router_models,
)
if dedupe_key in seen:
continue
seen.add(dedupe_key)
ordered_models.append(normalized_model)
return ordered_models
def setup_env(override: bool = False):
"""
Initialize environment variables from .env file.
Args:
override: If True, overwrite existing environment variables with values
from .env file. Set to True when reloading config after updates.
Default is False to preserve behavior on initial load where
system environment variables take precedence.
"""
Config._capture_bootstrap_runtime_env_overrides()
# src/config.py -> src/ -> root
env_file = os.getenv("ENV_FILE")
if env_file:
env_path = Path(env_file)
else:
env_path = Path(__file__).parent.parent / '.env'
compose_sensitive_keys = ("CUSTOM_WEBHOOK_BODY_TEMPLATE",)
preexisting_compose_sensitive_keys = {
key for key in compose_sensitive_keys if key in os.environ
}
load_dotenv(dotenv_path=env_path, override=override)
try:
raw_env_values = dotenv_values(env_path, interpolate=False)
except Exception as exc: # pragma: no cover - defensive branch
logger.warning("Failed to read raw .env values from %s: %s", env_path, exc)
return
key = "CUSTOM_WEBHOOK_BODY_TEMPLATE"
if key in raw_env_values and (
override or key not in preexisting_compose_sensitive_keys
):
raw_value = raw_env_values.get(key)
os.environ[key] = unescape_compose_sensitive_env_value(
key,
"" if raw_value is None else str(raw_value),
)
@dataclass
class Config:
"""
系统配置类 - 单例模式
设计说明:
- 使用 dataclass 简化配置属性定义
- 所有配置项从环境变量读取,支持默认值
- 类方法 get_instance() 实现单例访问
"""
# === 自选股配置 ===
stock_list: List[str] = field(default_factory=list)
# === 飞书云文档配置 ===
feishu_app_id: Optional[str] = None
feishu_app_secret: Optional[str] = None
feishu_folder_token: Optional[str] = None # 目标文件夹 Token
# === 数据源 API Token ===
tushare_token: Optional[str] = None
tickflow_api_key: Optional[str] = None
tickflow_kline_adjust: str = "none"
tickflow_priority: int = 2
tickflow_batch_daily_enabled: bool = True
tickflow_batch_size: int = 100
futu_opend_host: Optional[str] = None
futu_opend_port: int = 11111
futu_hk_realtime_source_priority: str = "futu,longbridge,akshare,yfinance"
finnhub_api_key: Optional[str] = None
alphavantage_api_key: Optional[str] = None
longbridge_app_key: Optional[str] = None
longbridge_app_secret: Optional[str] = None
longbridge_access_token: Optional[str] = None
longbridge_oauth_client_id: Optional[str] = None
stock_index_remote_update_enabled: bool = True
# === Built-in stock screening ===
screening_enabled: bool = False
# === AI 分析配置 ===
generation_backend: str = LITELLM_BACKEND_ID
generation_fallback_backend: str = LITELLM_BACKEND_ID
generation_backend_timeout_seconds: int = DEFAULT_LOCAL_CLI_TIMEOUT_SECONDS
generation_backend_max_output_bytes: int = DEFAULT_LOCAL_CLI_MAX_OUTPUT_BYTES
generation_backend_max_concurrency: int = DEFAULT_GENERATION_BACKEND_MAX_CONCURRENCY
local_cli_backend_max_concurrency: int = DEFAULT_LOCAL_CLI_BACKEND_MAX_CONCURRENCY
opencode_cli_model: str = ""
# LiteLLM unified model config (provider/model format, e.g. gemini/gemini-3.1-pro-preview)
litellm_model: str = "" # Primary model; must include provider prefix when set explicitly
litellm_fallback_models: List[str] = field(default_factory=list) # Cross-model fallback list
# Unified temperature for all LLM calls (LLM_TEMPERATURE); legacy per-provider temps are fallback only
llm_temperature: float = 0.7
# Provider prompt-cache controls. These do not control provider implicit cache.
llm_prompt_cache_telemetry_enabled: bool = True
llm_prompt_cache_hints_enabled: bool = False
llm_prompt_cache_diagnostics_level: str = "off"
# --- Multi-channel LLM config (new) ---
# LITELLM_CONFIG: path to a standard litellm_config.yaml file (most powerful)
litellm_config_path: Optional[str] = None
# Internal metadata: which config layer actually produced llm_model_list
llm_models_source: str = "legacy_env"
# LLM_CHANNELS: list of channel dicts, each with name/base_url/api_keys/models
llm_channels: List[Dict[str, Any]] = field(default_factory=list)
# Raw channel names requested through LLM_CHANNELS, including channels that
# were skipped during parsing because required channel fields were missing.
llm_channel_names: List[str] = field(default_factory=list)
# Structured parse issues raised while turning LLM_CHANNELS into deployments.
llm_channel_config_issues: List[Dict[str, str]] = field(default_factory=list)
# True when invalid explicit channel config must prevent legacy key inference.
llm_blocks_legacy_fallback: bool = False
# Canonical Hermes route names that were requested but blocked by atomic parse issues.
llm_blocked_hermes_routes: List[str] = field(default_factory=list)
# Pre-built LiteLLM Router model_list (populated from channels, YAML, or legacy keys)
llm_model_list: List[Dict[str, Any]] = field(default_factory=list)
# Multi-key support: each list is parsed from *_API_KEYS (comma-separated) with single-key fallback
gemini_api_keys: List[str] = field(default_factory=list)
anthropic_api_keys: List[str] = field(default_factory=list)
openai_api_keys: List[str] = field(default_factory=list)
deepseek_api_keys: List[str] = field(default_factory=list)
# Legacy single-key fields (kept for backward compatibility; gemini_api_keys[0] when set)
gemini_api_key: Optional[str] = None
gemini_model: str = "gemini-3.1-pro-preview" # 主模型
gemini_model_fallback: str = "gemini-3-flash-preview" # 备选模型
gemini_temperature: float = 0.7 # 温度参数(0.0-2.0,控制输出随机性,默认0.7)
# Gemini API 请求配置(防止 429 限流)
gemini_request_delay: float = 2.0 # 请求间隔(秒)
gemini_max_retries: int = 5 # 最大重试次数
gemini_retry_delay: float = 5.0 # 重试基础延时(秒)
# Anthropic Claude API(备选,当 Gemini 不可用时使用)
anthropic_api_key: Optional[str] = None
anthropic_model: str = "claude-sonnet-4-6" # Claude model name
anthropic_temperature: float = 0.7 # Anthropic temperature (0.0-1.0, default 0.7)
anthropic_max_tokens: int = 8192 # Max tokens for Anthropic responses
# OpenAI 兼容 API(备选,当 Gemini/Anthropic 不可用时使用)
openai_api_key: Optional[str] = None
openai_base_url: Optional[str] = None # 如: https://api.openai.com/v1
openai_model: str = "gpt-5.5" # OpenAI 兼容模型名称
openai_vision_model: Optional[str] = None # Deprecated: use VISION_MODEL instead
openai_temperature: float = 0.7 # OpenAI 温度参数(0.0-2.0,默认0.7)
# === Vision 配置 ===
# VISION_MODEL: litellm model string used for image understanding calls.
# Fallback chain: VISION_MODEL → OPENAI_VISION_MODEL → gemini/gemini-2.0-flash
vision_model: str = ""
# VISION_PROVIDER_PRIORITY: comma-separated provider order for Vision fallback.
vision_provider_priority: str = "gemini,anthropic,openai"
# === 搜索引擎配置(支持多 Key 负载均衡)===
anspire_api_keys: List[str] = field(default_factory=list) # Anspire Search API Keys
bocha_api_keys: List[str] = field(default_factory=list) # Bocha API Keys
minimax_api_keys: List[str] = field(default_factory=list) # MiniMax API Keys
tavily_api_keys: List[str] = field(default_factory=list) # Tavily API Keys
brave_api_keys: List[str] = field(default_factory=list) # Brave Search API Keys
serpapi_keys: List[str] = field(default_factory=list) # SerpAPI Keys
searxng_base_urls: List[str] = field(default_factory=list) # SearXNG instance URLs (self-hosted, no quota)
searxng_public_instances_enabled: bool = False # Opt in to public discovery when base URLs are absent
searxng_timeout_seconds: int = 10 # 自建 SearXNG 单次搜索超时(秒)
# === Social Sentiment (US stocks only, api.adanos.org) ===
social_sentiment_api_key: Optional[str] = None
social_sentiment_api_url: str = "https://api.adanos.org"
# === 新闻与分析筛选配置 ===
news_max_age_days: int = 3 # 新闻最大时效(天)
news_strategy_profile: str = "short" # 新闻窗口策略档位:ultra_short/short/medium/long
news_intel_retention_days: int = 30 # 本地资讯池保留天数
news_intel_fetch_timeout_sec: float = 8.0 # 单个资讯源拉取超时
news_intel_max_items_per_source: int = 50 # 单次每个资讯源最多采集条数
news_intel_auto_fetch_enabled: bool = False # 是否在分析前自动初始化并拉取本地资讯源
newsnow_base_url: str = "https://newsnow.busiyi.world" # NewsNow HTTP API base URL (数据源侧,不影响 LLM/provider base URL)
bias_threshold: float = 5.0 # 乖离率阈值(%),超过此值提示不追高