forked from ZhuLinsen/daily_stock_analysis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.py
More file actions
2597 lines (2305 loc) · 114 KB
/
Copy pathconfig.py
File metadata and controls
2597 lines (2305 loc) · 114 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 pathlib import Path
from typing import Any, Dict, List, Literal, Optional, Tuple
from urllib.parse import urlparse
from dotenv import load_dotenv, dotenv_values
from dataclasses import dataclass, field
from src.report_language import (
is_supported_report_language_value,
normalize_report_language,
)
from src.notification_routing import parse_notification_route_channels
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 = ""
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")
_FALSEY_ENV_VALUES = {"0", "false", "no", "off"}
# 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"
# Kimi K2.6 is consumed through Moonshot's OpenAI-compatible API in this
# repository. Official references:
# - https://platform.kimi.ai/docs/guide/kimi-k2-6-quickstart
# - https://platform.moonshot.ai/docs/guide/compatibility#parameters-differences-in-request-body
# - https://huggingface.co/moonshotai/Kimi-K2.6
# - https://docs.litellm.ai/docs/providers/openai_compatible
# Only the strict Kimi K2.6 family is normalized here; other models and
# fallbacks continue using the configured runtime temperature.
_FIXED_TEMPERATURE_LITELLM_MODELS: Dict[str, Dict[str, float]] = {
"kimi-k2.6": {
"thinking": 1.0,
"non_thinking": 0.6,
},
}
AGENT_MAX_STEPS_DEFAULT = 10
NEWS_STRATEGY_WINDOWS: Dict[str, int] = {
"ultra_short": 1,
"short": 3,
"medium": 7,
"long": 30,
}
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 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 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)
known_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",
}
if prefix in known_providers:
return normalized_model
if canonical_prefix in known_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 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."""
normalized_model = (model or "").strip()
if not normalized_model or not model_list:
return normalized_model
model_entry = _resolve_litellm_model_list_entry(normalized_model, model_list)
if not model_entry:
return normalized_model
params = model_entry.get("litellm_params", {}) or {}
wire_model = str(params.get("model") or "").strip()
if wire_model:
return wire_model
return normalized_model
def _resolve_litellm_model_list_entry(
model: str,
model_list: Optional[List[Dict[str, Any]]] = None,
) -> Optional[Dict[str, Any]]:
"""Return the Router model_list entry matching the configured alias."""
normalized_model = (model or "").strip()
if not normalized_model or not model_list:
return None
for entry in model_list:
model_name = str(entry.get("model_name") or "").strip()
if not model_name:
params = entry.get("litellm_params", {}) or {}
model_name = str(params.get("model") or "").strip()
if model_name == normalized_model:
return entry
return None
def _extract_thinking_config(payload: Optional[Dict[str, Any]]) -> Any:
"""Extract a thinking-mode flag from LiteLLM-style request kwargs."""
if not isinstance(payload, dict):
return None
extra_body = payload.get("extra_body")
if isinstance(extra_body, dict) and "thinking" in extra_body:
return extra_body.get("thinking")
if "thinking" in payload:
return payload.get("thinking")
return None
def _parse_thinking_enabled(value: Any) -> Optional[bool]:
"""Parse thinking-mode config into True/False/unknown."""
if value is None:
return None
if isinstance(value, bool):
return value
if isinstance(value, str):
normalized = value.strip().lower()
if normalized in {"enabled", "enable", "true", "1", "on", "thinking"}:
return True
if normalized in {"disabled", "disable", "false", "0", "off", "none", "non-thinking", "non_thinking"}:
return False
return None
if isinstance(value, dict):
if "enabled" in value:
return _parse_thinking_enabled(value.get("enabled"))
if "type" in value:
return _parse_thinking_enabled(value.get("type"))
return None
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."""
thinking_config = None
model_entry = _resolve_litellm_model_list_entry(model, model_list)
if model_entry:
thinking_config = _extract_thinking_config(model_entry)
entry_params = model_entry.get("litellm_params", {}) or {}
entry_thinking_config = _extract_thinking_config(entry_params)
if entry_thinking_config is not None:
thinking_config = entry_thinking_config
override_thinking_config = _extract_thinking_config(request_overrides)
if override_thinking_config is not None:
thinking_config = override_thinking_config
return _parse_thinking_enabled(thinking_config)
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."""
normalized_model = resolve_litellm_wire_model(model, model_list).lower()
if not normalized_model:
return None
thinking_enabled = resolve_litellm_thinking_enabled(
model,
model_list=model_list,
request_overrides=request_overrides,
)
model_parts = [part for part in re.split(r"[/:\s]+", normalized_model) if part]
for model_name, temperatures in _FIXED_TEMPERATURE_LITELLM_MODELS.items():
if any(part == model_name or part.startswith(f"{model_name}-") for part in model_parts):
if thinking_enabled is False and temperatures.get("non_thinking") is not None:
return temperatures["non_thinking"]
if temperatures.get("thinking") is not None:
return temperatures["thinking"]
if temperatures.get("non_thinking") is not None:
return temperatures["non_thinking"]
return None
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."""
fixed_temperature = get_fixed_litellm_temperature(
model,
model_list=model_list,
request_overrides=request_overrides,
)
if fixed_temperature is not None:
return fixed_temperature
if temperature is None:
return default
return float(temperature)
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 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'
load_dotenv(dotenv_path=env_path, override=override)
@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
longbridge_app_key: Optional[str] = None
longbridge_app_secret: Optional[str] = None
longbridge_access_token: Optional[str] = None
# === AI 分析配置 ===
# 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
# --- 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)
# 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 = True # Auto-discover public SearXNG instances when base URLs are absent
# === 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
bias_threshold: float = 5.0 # 乖离率阈值(%),超过此值提示不追高
# === Agent 模式配置 ===
agent_litellm_model: str = "" # Optional Agent-only primary model; empty inherits LITELLM_MODEL
agent_mode: bool = False
_agent_mode_explicit: bool = False # True when AGENT_MODE was explicitly set in env
agent_max_steps: int = AGENT_MAX_STEPS_DEFAULT
agent_skills: List[str] = field(default_factory=list)
agent_skill_dir: Optional[str] = None
agent_nl_routing: bool = False # Enable natural language routing in bot dispatcher
agent_arch: str = "single" # Agent architecture: 'single' (legacy) or 'multi' (orchestrator)
agent_orchestrator_mode: str = "standard" # Orchestrator mode: quick/standard/full/specialist
agent_orchestrator_timeout_s: int = 600 # Cooperative timeout budget for the whole multi-agent pipeline
agent_risk_override: bool = True # Allow risk agent to veto buy signals
agent_deep_research_budget: int = 30000 # Max token budget for deep research
agent_deep_research_timeout: int = 180 # Max seconds for /research command before returning timeout
agent_memory_enabled: bool = False # Enable memory & calibration system
agent_skill_autoweight: bool = True # Auto-weight skills by backtest performance
agent_skill_routing: str = "auto" # Skill routing: 'auto' (regime-based) or 'manual'
agent_event_monitor_enabled: bool = False # Enable periodic event-driven alert checks in schedule mode
agent_event_monitor_interval_minutes: int = 5 # Polling interval for event monitor background checks
agent_event_alert_rules_json: str = "" # JSON array of serialized EventMonitor rules
# === 通知配置(可同时配置多个,全部推送)===
# 企业微信 Webhook
wechat_webhook_url: Optional[str] = None
# 飞书 Webhook
feishu_webhook_url: Optional[str] = None
feishu_webhook_secret: Optional[str] = None # 自定义机器人签名密钥(可选)
feishu_webhook_keyword: Optional[str] = None # 自定义机器人关键词(可选)
# Telegram 配置(需要同时配置 Bot Token 和 Chat ID)
telegram_bot_token: Optional[str] = None # Bot Token(@BotFather 获取)
telegram_chat_id: Optional[str] = None # Chat ID
telegram_message_thread_id: Optional[str] = None # Topic ID (Message Thread ID) for groups
# 邮件配置(只需邮箱和授权码,SMTP 自动识别)
email_sender: Optional[str] = None # 发件人邮箱
email_sender_name: str = "daily_stock_analysis股票分析助手" # 发件人显示名称
email_password: Optional[str] = None # 邮箱密码/授权码
email_receivers: List[str] = field(default_factory=list) # 收件人列表(留空则发给自己)
# Stock-to-email group routing (Issue #268): STOCK_GROUP_N + EMAIL_GROUP_N
# When configured, each group's report is sent to that group's emails only.
stock_email_groups: List[Tuple[List[str], List[str]]] = field(default_factory=list)
# Pushover 配置(手机/桌面推送通知)
pushover_user_key: Optional[str] = None # 用户 Key(https://pushover.net 获取)
pushover_api_token: Optional[str] = None # 应用 API Token
# 自定义 Webhook(支持多个,逗号分隔)
# 适用于:钉钉、Discord、Slack、自建服务等任意支持 POST JSON 的 Webhook
custom_webhook_urls: List[str] = field(default_factory=list)
custom_webhook_bearer_token: Optional[str] = None # Bearer Token(用于需要认证的 Webhook)
custom_webhook_body_template: Optional[str] = None # 自定义 Webhook JSON body 模板
webhook_verify_ssl: bool = True # Webhook HTTPS 证书校验,false 可支持自签名(有 MITM 风险)
# Discord 通知配置
discord_bot_token: Optional[str] = None # Discord Bot Token
discord_main_channel_id: Optional[str] = None # Discord 主频道 ID
discord_webhook_url: Optional[str] = None # Discord Webhook URL
discord_interactions_public_key: Optional[str] = None # Discord Interaction 入站验签公钥
# Slack 通知配置
slack_webhook_url: Optional[str] = None # Slack Incoming Webhook URL
slack_bot_token: Optional[str] = None # Slack Bot Token (xoxb-...)
slack_channel_id: Optional[str] = None # Slack 频道 ID (Bot 模式必填)
# AstrBot 通知配置
astrbot_token: Optional[str] = None
astrbot_url: Optional[str] = None
# 通知路由策略(Issue #1200 P3):留空表示该类型使用全部已配置渠道
notification_report_channels: List[str] = field(default_factory=list)
notification_alert_channels: List[str] = field(default_factory=list)
notification_system_error_channels: List[str] = field(default_factory=list)
# 单股推送模式:每分析完一只股票立即推送,而不是汇总后推送
single_stock_notify: bool = False
# 报告类型:simple(精简) 或 full(完整)
report_type: str = "simple"
report_language: str = "zh"
# 仅分析结果摘要:true 时只推送汇总,不含个股详情(Issue #262)
report_summary_only: bool = False
# Report Engine P0: Jinja2 renderer and integrity checks
report_templates_dir: str = "templates" # Template directory (relative to project root)
report_renderer_enabled: bool = False # Enable Jinja2 rendering (default off for zero regression)
report_integrity_enabled: bool = True # Content integrity validation after LLM output
report_integrity_retry: int = 1 # Retry count when mandatory fields missing (0 = placeholder only)
report_history_compare_n: int = 0 # History comparison count (0 = disabled)
# PushPlus 推送配置
pushplus_token: Optional[str] = None # PushPlus Token
pushplus_topic: Optional[str] = None # PushPlus 群组编码(一对多推送)
# Server酱3 推送配置
serverchan3_sendkey: Optional[str] = None # Server酱3 SendKey
# 分析间隔时间(秒)- 用于避免API限流
analysis_delay: float = 0.0 # 个股分析与大盘分析之间的延迟
# Merge stock + market report into one notification (Issue #190)
merge_email_notification: bool = False
# 消息长度限制(字节)- 超长自动分批发送
feishu_max_bytes: int = 20000 # 飞书限制约 20KB,默认 20000 字节
wechat_max_bytes: int = 4000 # 企业微信限制 4096 字节,默认 4000 字节
discord_max_words: int = 2000 # Discord 限制 2000 字,默认 2000 字
wechat_msg_type: str = "markdown" # 企业微信消息类型,默认 markdown 类型
# Markdown 转图片(Issue #289):对不支持 Markdown 的渠道以图片发送
markdown_to_image_channels: List[str] = field(default_factory=list) # 逗号分隔:telegram,wechat,custom,email
markdown_to_image_max_chars: int = 15000 # 超过此长度不转换,避免超大图片
md2img_engine: str = "wkhtmltoimage" # wkhtmltoimage | markdown-to-file (Issue #455, better emoji support)
# 实时行情预取(Issue #455):设为 false 可禁用,避免 efinance/akshare_em 全市场拉取
prefetch_realtime_quotes: bool = True
# === 数据库配置 ===
database_path: str = "./data/stock_analysis.db"
sqlite_wal_enabled: bool = True
sqlite_busy_timeout_ms: int = 5000
sqlite_write_retry_max: int = 3
sqlite_write_retry_base_delay: float = 0.1
# 是否保存分析上下文快照(用于历史回溯)
save_context_snapshot: bool = True
# === 回测配置 ===
backtest_enabled: bool = True
backtest_eval_window_days: int = 10
backtest_min_age_days: int = 14
backtest_engine_version: str = "v1"
backtest_neutral_band_pct: float = 2.0
# === 日志配置 ===
log_dir: str = "./logs" # 日志文件目录
log_level: str = "INFO" # 日志级别
# === 系统配置 ===
max_workers: int = 3 # 低并发防封禁
debug: bool = False
http_proxy: Optional[str] = None # HTTP 代理 (例如: http://127.0.0.1:10809)
https_proxy: Optional[str] = None # HTTPS 代理
# === 定时任务配置 ===
schedule_enabled: bool = False # 是否启用定时任务
schedule_time: str = "18:00" # 每日推送时间(HH:MM 格式)
schedule_run_immediately: bool = True # 启动时是否立即执行一次
run_immediately: bool = True # 启动时是否立即执行一次(非定时模式)
market_review_enabled: bool = True # 是否启用大盘复盘
# 大盘复盘市场区域:cn(A股)、us(美股)、both(两者),us 适合仅关注美股的用户
market_review_region: str = "cn"
# 交易日检查:默认启用,非交易日跳过执行;设为 false 或 --force-run 可强制执行(Issue #373)
trading_day_check_enabled: bool = True
# === 实时行情增强数据配置 ===
# 实时行情开关(关闭后使用历史收盘价进行分析)
enable_realtime_quote: bool = True
# 盘中实时技术面:启用时用实时价计算 MA/多头排列(Issue #234);关闭则用昨日收盘
enable_realtime_technical_indicators: bool = True
# 筹码分布开关(该接口不稳定,云端部署建议关闭)
enable_chip_distribution: bool = True
# 东财接口补丁开关
enable_eastmoney_patch: bool = False
# 实时行情数据源优先级(逗号分隔)
# 推荐顺序:tencent > akshare_sina > efinance > akshare_em > tushare
# - tencent: 腾讯财经,有量比/换手率/市盈率等,单股查询稳定(推荐)
# - akshare_sina: 新浪财经,基本行情稳定,但无量比
# - efinance/akshare_em: 东财全量接口,数据最全但容易被封
# - tushare: Tushare Pro,需要2000积分,数据全面(付费用户可优先使用)
realtime_source_priority: str = "tencent,akshare_sina,efinance,akshare_em"
# 实时行情缓存时间(秒)
realtime_cache_ttl: int = 600
# 熔断器冷却时间(秒)
circuit_breaker_cooldown: int = 300
# === 基本面聚合开关与降级保护 ===
# 全局总开关;关闭时返回 not_supported 并保持主流程无变化
enable_fundamental_pipeline: bool = True
# 基本面阶段总预算(秒)
fundamental_stage_timeout_seconds: float = 1.5
# 单能力源调用超时(秒)
fundamental_fetch_timeout_seconds: float = 0.8
# 单能力失败重试次数(已包含首次)
fundamental_retry_max: int = 1
# 基本面上下文短 TTL(秒)
fundamental_cache_ttl_seconds: int = 120
# 基本面缓存最大条目数(避免长时间运行内存增长)
fundamental_cache_max_entries: int = 256
# === Portfolio PR2: import/risk/fx settings ===
portfolio_risk_concentration_alert_pct: float = 35.0
portfolio_risk_drawdown_alert_pct: float = 15.0
portfolio_risk_stop_loss_alert_pct: float = 10.0
portfolio_risk_stop_loss_near_ratio: float = 0.8
portfolio_risk_lookback_days: int = 180
portfolio_fx_update_enabled: bool = True
# Discord 机器人状态
discord_bot_status: str = "A股智能分析 | /help"
# === 流控配置(防封禁关键参数)===
# Akshare 请求间隔范围(秒)
akshare_sleep_min: float = 2.0
akshare_sleep_max: float = 5.0
# Tushare 每分钟最大请求数(免费配额)
tushare_rate_limit_per_minute: int = 80
# 重试配置
max_retries: int = 3
retry_base_delay: float = 1.0
retry_max_delay: float = 30.0
# === WebUI 配置 ===
webui_enabled: bool = False
webui_host: str = "127.0.0.1"
webui_port: int = 8000
# === 机器人配置 ===
bot_enabled: bool = True # 是否启用机器人功能
bot_command_prefix: str = "/" # 命令前缀
bot_rate_limit_requests: int = 10 # 频率限制:窗口内最大请求数
bot_rate_limit_window: int = 60 # 频率限制:窗口时间(秒)
bot_admin_users: List[str] = field(default_factory=list) # 管理员用户 ID 列表
# 飞书机器人(事件订阅)- 已有 feishu_app_id, feishu_app_secret
feishu_verification_token: Optional[str] = None # 事件订阅验证 Token
feishu_encrypt_key: Optional[str] = None # 消息加密密钥(可选)
feishu_stream_enabled: bool = False # 是否启用 Stream 长连接模式(无需公网IP)
# 钉钉机器人
dingtalk_app_key: Optional[str] = None # 应用 AppKey
dingtalk_app_secret: Optional[str] = None # 应用 AppSecret
dingtalk_stream_enabled: bool = False # 是否启用 Stream 模式(无需公网IP)
# 企业微信机器人(回调模式)
wecom_corpid: Optional[str] = None # 企业 ID
wecom_token: Optional[str] = None # 回调 Token
wecom_encoding_aes_key: Optional[str] = None # 消息加解密密钥
wecom_agent_id: Optional[str] = None # 应用 AgentId
# Telegram 机器人 - 已有 telegram_bot_token, telegram_chat_id
telegram_webhook_secret: Optional[str] = None # Webhook 密钥
# === 配置校验模式 ===
# CONFIG_VALIDATE_MODE=warn (default): log all issues but always continue startup
# CONFIG_VALIDATE_MODE=strict: exit(1) when any "error" severity issue is found
config_validate_mode: str = "warn"
# --- Post-init validation ---------------------------------------------------
_VALID_AGENT_ARCH = {"single", "multi"}
_VALID_ORCHESTRATOR_MODES = {"quick", "standard", "full", "specialist"}
_VALID_SKILL_ROUTING = {"auto", "manual"}
_WEBUI_RUNTIME_ENV_FILE_PRIORITY_KEYS = frozenset(
{
"STOCK_LIST",
"RUN_IMMEDIATELY",
"SCHEDULE_ENABLED",
"SCHEDULE_TIME",
"SCHEDULE_RUN_IMMEDIATELY",
}
)
_BOOTSTRAP_RUNTIME_ENV_OVERRIDES_CAPTURED = False
_BOOTSTRAP_RUNTIME_ENV_OVERRIDES = frozenset()
def __post_init__(self) -> None:
_log = logging.getLogger(__name__)
if self.agent_arch not in self._VALID_AGENT_ARCH:
_log.warning(
"Invalid AGENT_ARCH=%r, falling back to 'single'. Valid: %s",
self.agent_arch, self._VALID_AGENT_ARCH,
)
object.__setattr__(self, "agent_arch", "single")
if self.agent_orchestrator_mode in {"strategy", "skill"}:
_log.info(
"AGENT_ORCHESTRATOR_MODE=%s is deprecated; normalizing to 'specialist'",
self.agent_orchestrator_mode,
)
object.__setattr__(self, "agent_orchestrator_mode", "specialist")
if self.agent_orchestrator_mode not in self._VALID_ORCHESTRATOR_MODES:
_log.warning(
"Invalid AGENT_ORCHESTRATOR_MODE=%r, falling back to 'standard'. Valid: %s",
self.agent_orchestrator_mode, self._VALID_ORCHESTRATOR_MODES,
)
object.__setattr__(self, "agent_orchestrator_mode", "standard")
if self.agent_skill_routing not in self._VALID_SKILL_ROUTING:
_log.warning(
"Invalid AGENT_SKILL_ROUTING=%r, falling back to 'auto'. Valid: %s",
self.agent_skill_routing, self._VALID_SKILL_ROUTING,
)
object.__setattr__(self, "agent_skill_routing", "auto")
# 单例实例存储
_instance: Optional['Config'] = None
@classmethod
def get_instance(cls) -> 'Config':
"""
获取配置单例实例
单例模式确保:
1. 全局只有一个配置实例
2. 配置只从环境变量加载一次
3. 所有模块共享相同配置
"""
if cls._instance is None:
cls._instance = cls._load_from_env()
return cls._instance
@classmethod
def _load_from_env(cls) -> 'Config':
"""
从 .env 文件加载配置
加载优先级:
1. 大多数配置保持系统环境变量优先
2. WebUI 可写的运行期关键键优先复用持久化 `.env`,但保留启动时显式进程环境变量的 override