alphasift 0.3.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- alphasift/__init__.py +52 -0
- alphasift/__main__.py +7 -0
- alphasift/audit.py +191 -0
- alphasift/candidate_context.py +738 -0
- alphasift/cli.py +2797 -0
- alphasift/config.py +705 -0
- alphasift/context.py +672 -0
- alphasift/daily.py +1256 -0
- alphasift/daily_brief.py +593 -0
- alphasift/daily_report.py +1115 -0
- alphasift/daily_report_html.py +1257 -0
- alphasift/doctor.py +1123 -0
- alphasift/dsa.py +302 -0
- alphasift/dsa_adapter.py +178 -0
- alphasift/dsa_provider.py +192 -0
- alphasift/evaluate.py +2418 -0
- alphasift/filter.py +517 -0
- alphasift/hotspot.py +1713 -0
- alphasift/industry.py +959 -0
- alphasift/llm_client.py +349 -0
- alphasift/market_digest.py +284 -0
- alphasift/market_news.py +446 -0
- alphasift/market_regime.py +578 -0
- alphasift/markets.py +160 -0
- alphasift/mcp.py +720 -0
- alphasift/models.py +315 -0
- alphasift/normalize.py +113 -0
- alphasift/notify.py +2608 -0
- alphasift/overview.py +225 -0
- alphasift/pack.py +1470 -0
- alphasift/pack_features.py +431 -0
- alphasift/pattern_replay.py +1449 -0
- alphasift/patterns/bottom_volume_yang.yaml +32 -0
- alphasift/patterns/box_breakout.yaml +36 -0
- alphasift/patterns/double_bottom_breakout.yaml +38 -0
- alphasift/patterns/ma20_shrink_pullback.yaml +37 -0
- alphasift/patterns/shooting_star_confirm.yaml +49 -0
- alphasift/patterns/single_yang_hold.yaml +44 -0
- alphasift/patterns/steady_trend_breakout.yaml +39 -0
- alphasift/patterns/three_white_soldiers.yaml +72 -0
- alphasift/patterns/three_white_soldiers_pullback.yaml +91 -0
- alphasift/patterns.py +1233 -0
- alphasift/performance_history.py +297 -0
- alphasift/pipeline.py +1010 -0
- alphasift/post_analysis.py +337 -0
- alphasift/ranker.py +990 -0
- alphasift/report.py +379 -0
- alphasift/result_schema.py +179 -0
- alphasift/risk.py +452 -0
- alphasift/run_history.py +164 -0
- alphasift/scorer.py +597 -0
- alphasift/server.py +680 -0
- alphasift/snapshot.py +1025 -0
- alphasift/snapshot_us.py +280 -0
- alphasift/snapshot_yahoo.py +358 -0
- alphasift/source_guard.py +70 -0
- alphasift/source_history.py +306 -0
- alphasift/store.py +294 -0
- alphasift/strategies/balanced_alpha.yaml +76 -0
- alphasift/strategies/blue_chip_income.yaml +87 -0
- alphasift/strategies/capital_heat.yaml +74 -0
- alphasift/strategies/dual_low.yaml +80 -0
- alphasift/strategies/global_value.yaml +65 -0
- alphasift/strategies/low_volatility_quality.yaml +95 -0
- alphasift/strategies/momentum_quality.yaml +81 -0
- alphasift/strategies/oversold_reversal.yaml +75 -0
- alphasift/strategies/quality_value.yaml +80 -0
- alphasift/strategies/shrink_pullback.yaml +77 -0
- alphasift/strategies/us_momentum_quality.yaml +74 -0
- alphasift/strategies/volume_breakout.yaml +78 -0
- alphasift/strategy.py +1090 -0
- alphasift/strategy_cards.py +424 -0
- alphasift/strategy_templates.py +291 -0
- alphasift/timeutil.py +38 -0
- alphasift/valuation_kr.py +149 -0
- alphasift/workbench_ui.py +1051 -0
- alphasift-0.3.1.data/data/.env.example +151 -0
- alphasift-0.3.1.data/data/LICENSE +184 -0
- alphasift-0.3.1.data/data/SKILL.md +190 -0
- alphasift-0.3.1.data/data/agents/openai.yaml +7 -0
- alphasift-0.3.1.dist-info/METADATA +312 -0
- alphasift-0.3.1.dist-info/RECORD +86 -0
- alphasift-0.3.1.dist-info/WHEEL +5 -0
- alphasift-0.3.1.dist-info/entry_points.txt +2 -0
- alphasift-0.3.1.dist-info/licenses/LICENSE +184 -0
- alphasift-0.3.1.dist-info/top_level.txt +1 -0
alphasift/config.py
ADDED
|
@@ -0,0 +1,705 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Configuration."""
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from alphasift.llm_client import (
|
|
10
|
+
DEFAULT_LLM_MAX_TOKENS,
|
|
11
|
+
gateway_api_keys,
|
|
12
|
+
gateway_base_url,
|
|
13
|
+
normalize_model,
|
|
14
|
+
split_model,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
_PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
|
18
|
+
_PACKAGE_DIR = Path(__file__).resolve().parent
|
|
19
|
+
DEFAULT_POST_ANALYZERS = ["scorecard"]
|
|
20
|
+
DEFAULT_LLM_MODEL = "gemini/gemini-3.8-flash"
|
|
21
|
+
DEFAULT_GEMINI_FALLBACK_MODELS = ["gemini/gemini-4-hydrogen"]
|
|
22
|
+
DEFAULT_SNAPSHOT_SOURCE_PRIORITY = ["em_datacenter", "sina", "efinance", "akshare_em"]
|
|
23
|
+
TUSHARE_FIRST_SOURCE_PRIORITY = ["tushare", "em_datacenter", "sina", "efinance", "akshare_em"]
|
|
24
|
+
_ENV_FILE_CACHE: dict[Path, tuple[tuple[int, int], dict[str, str]]] = {}
|
|
25
|
+
_APPLIED_ENV_FILE_VALUES: dict[str, str] = {}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _load_env_file() -> None:
|
|
29
|
+
"""Load .env from cwd or project root if present."""
|
|
30
|
+
candidates = [
|
|
31
|
+
*_env_file_candidates_from_env(),
|
|
32
|
+
Path.cwd() / ".env",
|
|
33
|
+
_PROJECT_ROOT / ".env",
|
|
34
|
+
]
|
|
35
|
+
seen: set[Path] = set()
|
|
36
|
+
file_values: dict[str, str] = {}
|
|
37
|
+
for path in candidates:
|
|
38
|
+
resolved = path.resolve()
|
|
39
|
+
if resolved in seen or not path.is_file():
|
|
40
|
+
continue
|
|
41
|
+
seen.add(resolved)
|
|
42
|
+
for key, value in _read_env_file_values(path).items():
|
|
43
|
+
file_values.setdefault(key, value)
|
|
44
|
+
_apply_env_file_values(file_values)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _read_env_file_values(path: Path) -> dict[str, str]:
|
|
48
|
+
resolved = path.resolve()
|
|
49
|
+
stat = path.stat()
|
|
50
|
+
signature = (stat.st_mtime_ns, stat.st_size)
|
|
51
|
+
cached = _ENV_FILE_CACHE.get(resolved)
|
|
52
|
+
if cached is not None and cached[0] == signature:
|
|
53
|
+
return dict(cached[1])
|
|
54
|
+
|
|
55
|
+
values: dict[str, str] = {}
|
|
56
|
+
for line in path.read_text(encoding="utf-8").splitlines():
|
|
57
|
+
line = line.strip()
|
|
58
|
+
if not line or line.startswith("#") or "=" not in line:
|
|
59
|
+
continue
|
|
60
|
+
key, value = line.split("=", 1)
|
|
61
|
+
cleaned = value.strip().strip("'\"")
|
|
62
|
+
if cleaned == "":
|
|
63
|
+
continue
|
|
64
|
+
values.setdefault(key.strip(), cleaned)
|
|
65
|
+
_ENV_FILE_CACHE[resolved] = (signature, dict(values))
|
|
66
|
+
return values
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _apply_env_file_values(file_values: dict[str, str]) -> None:
|
|
70
|
+
for key, old_value in list(_APPLIED_ENV_FILE_VALUES.items()):
|
|
71
|
+
if os.environ.get(key) == old_value and file_values.get(key) != old_value:
|
|
72
|
+
os.environ.pop(key, None)
|
|
73
|
+
if os.environ.get(key) != old_value:
|
|
74
|
+
_APPLIED_ENV_FILE_VALUES.pop(key, None)
|
|
75
|
+
|
|
76
|
+
for key, value in file_values.items():
|
|
77
|
+
if key not in os.environ:
|
|
78
|
+
os.environ[key] = value
|
|
79
|
+
_APPLIED_ENV_FILE_VALUES[key] = value
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _env_file_candidates_from_env() -> list[Path]:
|
|
83
|
+
raw_values = [
|
|
84
|
+
os.getenv("ALPHASIFT_ENV_FILE", ""),
|
|
85
|
+
os.getenv("ALPHASIFT_ENV_FILES", ""),
|
|
86
|
+
]
|
|
87
|
+
paths: list[Path] = []
|
|
88
|
+
for raw in raw_values:
|
|
89
|
+
for item in raw.replace(os.pathsep, ",").split(","):
|
|
90
|
+
value = item.strip()
|
|
91
|
+
if value:
|
|
92
|
+
paths.append(Path(value))
|
|
93
|
+
return paths
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _parse_bool_env(name: str, default: bool) -> bool:
|
|
97
|
+
value = os.getenv(name)
|
|
98
|
+
if value is None:
|
|
99
|
+
return default
|
|
100
|
+
return value.strip().lower() in {"1", "true", "yes", "on"}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _parse_csv_env(name: str, default: list[str] | None = None) -> list[str]:
|
|
104
|
+
value = os.getenv(name)
|
|
105
|
+
if value is None:
|
|
106
|
+
return list(default or [])
|
|
107
|
+
if value.strip().lower() in {"", "0", "false", "none", "off"}:
|
|
108
|
+
return []
|
|
109
|
+
return [item.strip() for item in value.split(",") if item.strip()]
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _parse_optional_path_env(name: str) -> Path | None:
|
|
113
|
+
value = os.getenv(name, "").strip()
|
|
114
|
+
return Path(value) if value else None
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _has_tushare_token() -> bool:
|
|
118
|
+
return bool(
|
|
119
|
+
os.getenv("TUSHARE_TOKEN", "").strip()
|
|
120
|
+
or os.getenv("TUSHARE_API_TOKEN", "").strip()
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _resolve_snapshot_source_priority() -> list[str]:
|
|
125
|
+
explicit = os.getenv("SNAPSHOT_SOURCE_PRIORITY")
|
|
126
|
+
if explicit is not None:
|
|
127
|
+
return [s.strip() for s in explicit.split(",") if s.strip()]
|
|
128
|
+
if _has_tushare_token():
|
|
129
|
+
return list(TUSHARE_FIRST_SOURCE_PRIORITY)
|
|
130
|
+
return list(DEFAULT_SNAPSHOT_SOURCE_PRIORITY)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _resolve_fallback_snapshot_path(data_dir: Path) -> Path | None:
|
|
134
|
+
for name in ("ALPHASIFT_FALLBACK_SNAPSHOT_PATH", "FALLBACK_SNAPSHOT_PATH"):
|
|
135
|
+
raw = os.getenv(name)
|
|
136
|
+
if raw is None:
|
|
137
|
+
continue
|
|
138
|
+
value = raw.strip()
|
|
139
|
+
if value.lower() in {"", "0", "false", "none", "off"}:
|
|
140
|
+
return None
|
|
141
|
+
return Path(value)
|
|
142
|
+
return data_dir / "snapshot.last_good.json"
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _resolve_source_health_path(data_dir: Path) -> Path | None:
|
|
146
|
+
raw = os.getenv("ALPHASIFT_SOURCE_HEALTH_PATH")
|
|
147
|
+
if raw is None:
|
|
148
|
+
return data_dir / "source_health.json"
|
|
149
|
+
value = raw.strip()
|
|
150
|
+
if value.lower() in {"", "0", "false", "none", "off"}:
|
|
151
|
+
return None
|
|
152
|
+
return Path(value)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _is_source_checkout(root: Path | None = None) -> bool:
|
|
156
|
+
base = root or _PROJECT_ROOT
|
|
157
|
+
return (base / "pyproject.toml").is_file() and (base / "alphasift").is_dir()
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def default_data_dir() -> Path:
|
|
161
|
+
"""Return repo-local ``data/`` in editable checkouts, else a writable user data dir."""
|
|
162
|
+
env_val = os.getenv("ALPHASIFT_DATA_DIR", "").strip()
|
|
163
|
+
if env_val:
|
|
164
|
+
return Path(env_val)
|
|
165
|
+
if _is_source_checkout():
|
|
166
|
+
return _PROJECT_ROOT / "data"
|
|
167
|
+
xdg = os.getenv("XDG_DATA_HOME", "").strip()
|
|
168
|
+
if xdg:
|
|
169
|
+
return Path(xdg) / "alphasift"
|
|
170
|
+
return Path.home() / ".alphasift" / "data"
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _default_strategies_dir() -> Path:
|
|
174
|
+
"""Find strategies directory: env var > project root > package bundled."""
|
|
175
|
+
env_dir = os.getenv("STRATEGIES_DIR")
|
|
176
|
+
if env_dir:
|
|
177
|
+
return Path(env_dir)
|
|
178
|
+
# Dev mode: project root
|
|
179
|
+
project_dir = _PROJECT_ROOT / "strategies"
|
|
180
|
+
if project_dir.is_dir():
|
|
181
|
+
return project_dir
|
|
182
|
+
# Installed: inside package
|
|
183
|
+
return _PACKAGE_DIR / "strategies"
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
@dataclass
|
|
187
|
+
class Config:
|
|
188
|
+
"""Runtime configuration, loaded from env vars."""
|
|
189
|
+
|
|
190
|
+
# LLM
|
|
191
|
+
llm_api_key: str = ""
|
|
192
|
+
llm_model: str = DEFAULT_LLM_MODEL
|
|
193
|
+
llm_base_url: str = ""
|
|
194
|
+
llm_config_path: Path | None = None
|
|
195
|
+
llm_fallback_models: list[str] = field(default_factory=list)
|
|
196
|
+
llm_channels: list[dict[str, object]] = field(default_factory=list)
|
|
197
|
+
llm_context: str = ""
|
|
198
|
+
llm_candidate_context_enabled: bool = False
|
|
199
|
+
llm_candidate_context_max_candidates: int = 8
|
|
200
|
+
llm_candidate_context_providers: list[str] = field(default_factory=lambda: ["news", "fund_flow", "announcement", "quote"])
|
|
201
|
+
llm_candidate_context_news_limit: int = 3
|
|
202
|
+
llm_candidate_context_announcement_limit: int = 3
|
|
203
|
+
llm_candidate_context_cache_enabled: bool = True
|
|
204
|
+
llm_candidate_context_cache_ttl_hours: int = 24
|
|
205
|
+
llm_candidate_context_cache_dir: Path | None = None
|
|
206
|
+
llm_temperature: float = 0.2
|
|
207
|
+
llm_json_mode: bool = True
|
|
208
|
+
llm_silent: bool = True
|
|
209
|
+
llm_rank_weight: float = 0.40
|
|
210
|
+
llm_candidate_multiplier: int = 6
|
|
211
|
+
llm_max_candidates: int = 30
|
|
212
|
+
llm_max_retries: int = 1
|
|
213
|
+
llm_min_coverage: float = 0.60
|
|
214
|
+
llm_context_max_chars: int = 4000
|
|
215
|
+
llm_timeout_sec: float = 60.0
|
|
216
|
+
llm_max_tokens: int = DEFAULT_LLM_MAX_TOKENS
|
|
217
|
+
|
|
218
|
+
# Snapshot data source priority
|
|
219
|
+
snapshot_source_priority: list[str] = field(
|
|
220
|
+
default_factory=lambda: list(DEFAULT_SNAPSHOT_SOURCE_PRIORITY)
|
|
221
|
+
)
|
|
222
|
+
fallback_snapshot_path: Path | None = field(
|
|
223
|
+
default_factory=lambda: default_data_dir() / "snapshot.last_good.json"
|
|
224
|
+
)
|
|
225
|
+
# Cross-run snapshot source health; None disables persisted reordering.
|
|
226
|
+
source_health_path: Path | None = None
|
|
227
|
+
|
|
228
|
+
# Strategy directory
|
|
229
|
+
strategies_dir: Path = field(default_factory=_default_strategies_dir)
|
|
230
|
+
|
|
231
|
+
# Optional deterministic industry/concept enrichment.
|
|
232
|
+
industry_map_files: list[Path] = field(default_factory=list)
|
|
233
|
+
industry_provider: str = "none"
|
|
234
|
+
# Backfill A-share industry labels when the snapshot source has none, so
|
|
235
|
+
# portfolio diversity control is not silently disabled.
|
|
236
|
+
industry_auto_backfill: bool = True
|
|
237
|
+
industry_provider_max_boards: int = 80
|
|
238
|
+
industry_provider_cache_dir: Path | None = field(
|
|
239
|
+
default_factory=lambda: default_data_dir() / "industry_provider_cache"
|
|
240
|
+
)
|
|
241
|
+
industry_provider_cache_ttl_hours: int = 24
|
|
242
|
+
|
|
243
|
+
# Optional: DSA API for L3 deep analysis
|
|
244
|
+
dsa_api_url: str = ""
|
|
245
|
+
dsa_report_type: str = "detailed"
|
|
246
|
+
dsa_max_picks: int = 3
|
|
247
|
+
dsa_timeout_sec: float = 120.0
|
|
248
|
+
dsa_force_refresh: bool = False
|
|
249
|
+
dsa_notify: bool = False
|
|
250
|
+
|
|
251
|
+
# L3/post-ranking analyzers. scorecard is the default local scorer; DSA is
|
|
252
|
+
# one optional backend, not the pipeline's default or only final stage.
|
|
253
|
+
post_analyzers: list[str] = field(default_factory=lambda: list(DEFAULT_POST_ANALYZERS))
|
|
254
|
+
post_analysis_max_picks: int = 3
|
|
255
|
+
post_analyzer_url: str = ""
|
|
256
|
+
post_analyzer_timeout_sec: float = 120.0
|
|
257
|
+
|
|
258
|
+
# Optional daily K-line enrichment after snapshot hard filters.
|
|
259
|
+
daily_enrich_enabled: bool = False
|
|
260
|
+
daily_enrich_max_candidates: int = 100
|
|
261
|
+
daily_lookback_days: int = 120
|
|
262
|
+
daily_source: str = "auto"
|
|
263
|
+
daily_fetch_retries: int = 2
|
|
264
|
+
daily_fetch_max_workers: int = 1
|
|
265
|
+
daily_history_cache_dir: Path | None = None
|
|
266
|
+
daily_history_cache_ttl_hours: int = 24
|
|
267
|
+
daily_pack_enabled: bool = True
|
|
268
|
+
daily_pack_dir: Path | None = None
|
|
269
|
+
|
|
270
|
+
# Independent risk layer.
|
|
271
|
+
risk_enabled: bool = True
|
|
272
|
+
risk_max_penalty: float = 12.0
|
|
273
|
+
risk_veto_high: bool = False
|
|
274
|
+
|
|
275
|
+
# Portfolio diversity layer driven by LLM sector/theme risk buckets.
|
|
276
|
+
portfolio_diversity_enabled: bool = True
|
|
277
|
+
portfolio_max_same_llm_sector: int = 1
|
|
278
|
+
portfolio_concentration_penalty: float = 4.0
|
|
279
|
+
|
|
280
|
+
# Evaluation overlay.
|
|
281
|
+
evaluation_cost_bps: float = 0.0
|
|
282
|
+
evaluation_follow_through_pct: float = 3.0
|
|
283
|
+
evaluation_failed_breakout_pct: float = -3.0
|
|
284
|
+
evaluation_price_path_enabled: bool = False
|
|
285
|
+
evaluation_price_path_lookback_days: int = 90
|
|
286
|
+
|
|
287
|
+
# Data directory
|
|
288
|
+
data_dir: Path = field(default_factory=default_data_dir)
|
|
289
|
+
|
|
290
|
+
# Optional notification webhooks / 1-line NOTIFY_URLS (idle unless explicitly configured).
|
|
291
|
+
notify_urls: list[str] = field(default_factory=list)
|
|
292
|
+
wecom_webhook_url: str = ""
|
|
293
|
+
feishu_webhook_url: str = ""
|
|
294
|
+
feishu_webhook_secret: str = ""
|
|
295
|
+
dingtalk_webhook_url: str = ""
|
|
296
|
+
dingtalk_webhook_secret: str = ""
|
|
297
|
+
pushplus_token: str = ""
|
|
298
|
+
pushplus_topic: str = ""
|
|
299
|
+
serverchan_sendkey: str = ""
|
|
300
|
+
bark_url: str = ""
|
|
301
|
+
telegram_bot_token: str = ""
|
|
302
|
+
telegram_chat_id: str = ""
|
|
303
|
+
discord_webhook_url: str = ""
|
|
304
|
+
slack_webhook_url: str = ""
|
|
305
|
+
ntfy_url: str = ""
|
|
306
|
+
email_sender: str = ""
|
|
307
|
+
email_password: str = ""
|
|
308
|
+
email_receivers: str = ""
|
|
309
|
+
email_smtp_host: str = ""
|
|
310
|
+
email_smtp_port: int = 0
|
|
311
|
+
custom_webhook_url: str = ""
|
|
312
|
+
custom_webhook_token: str = ""
|
|
313
|
+
# Notification safety caps & UX URL
|
|
314
|
+
notify_state_path: Path = field(default_factory=lambda: default_data_dir() / "notify_state.json")
|
|
315
|
+
notify_timeout_sec: float = 10.0
|
|
316
|
+
dashboard_url: str = ""
|
|
317
|
+
tavily_api_keys: list[str] = field(default_factory=list)
|
|
318
|
+
serpapi_api_keys: list[str] = field(default_factory=list)
|
|
319
|
+
|
|
320
|
+
# Optional guardrail for last-good snapshot fallback freshness.
|
|
321
|
+
snapshot_fallback_max_age_hours: float | None = None
|
|
322
|
+
|
|
323
|
+
def has_llm_config(self) -> bool:
|
|
324
|
+
"""Return whether LLM ranking is configured, including legacy YAML to diagnose."""
|
|
325
|
+
return any([
|
|
326
|
+
bool(self.llm_api_key),
|
|
327
|
+
bool(self.llm_base_url and self.llm_model.startswith("ollama/")),
|
|
328
|
+
bool(self.llm_config_path),
|
|
329
|
+
bool(self.llm_channels),
|
|
330
|
+
self.llm_model.startswith("ollama/"),
|
|
331
|
+
])
|
|
332
|
+
|
|
333
|
+
def has_usable_llm_config(self) -> bool:
|
|
334
|
+
"""Return whether a supported non-legacy LLM route is usable."""
|
|
335
|
+
from alphasift.llm_client import configuration_error
|
|
336
|
+
|
|
337
|
+
if configuration_error(self.llm_channels, str(self.llm_config_path or "")):
|
|
338
|
+
return False
|
|
339
|
+
has_channels_with_models = any(
|
|
340
|
+
bool(ch.get("models"))
|
|
341
|
+
and (
|
|
342
|
+
str(ch.get("protocol", "")).lower() == "ollama"
|
|
343
|
+
or bool(ch.get("api_keys"))
|
|
344
|
+
or bool(self.llm_api_key)
|
|
345
|
+
or bool(gateway_api_keys(str(ch.get("protocol", "")).lower()))
|
|
346
|
+
)
|
|
347
|
+
for ch in self.llm_channels
|
|
348
|
+
)
|
|
349
|
+
return any([
|
|
350
|
+
bool(self.llm_api_key),
|
|
351
|
+
has_channels_with_models,
|
|
352
|
+
self.llm_model.startswith("ollama/"),
|
|
353
|
+
])
|
|
354
|
+
|
|
355
|
+
@classmethod
|
|
356
|
+
def from_env(cls) -> "Config":
|
|
357
|
+
_load_env_file()
|
|
358
|
+
channels = _parse_llm_channels_env()
|
|
359
|
+
llm_model = _resolve_llm_model(channels)
|
|
360
|
+
data_dir = default_data_dir()
|
|
361
|
+
fallback_snapshot_path = _resolve_fallback_snapshot_path(data_dir)
|
|
362
|
+
daily_history_cache_dir = (
|
|
363
|
+
_parse_optional_path_env("ALPHASIFT_DAILY_HISTORY_CACHE_DIR")
|
|
364
|
+
or _parse_optional_path_env("DAILY_HISTORY_CACHE_DIR")
|
|
365
|
+
or data_dir / "daily_history"
|
|
366
|
+
)
|
|
367
|
+
industry_provider_cache_dir = (
|
|
368
|
+
_parse_optional_path_env("ALPHASIFT_INDUSTRY_PROVIDER_CACHE_DIR")
|
|
369
|
+
or _parse_optional_path_env("INDUSTRY_PROVIDER_CACHE_DIR")
|
|
370
|
+
or data_dir / "industry_provider_cache"
|
|
371
|
+
)
|
|
372
|
+
return cls(
|
|
373
|
+
llm_api_key=_resolve_llm_api_key(llm_model),
|
|
374
|
+
llm_model=llm_model,
|
|
375
|
+
llm_base_url=_resolve_llm_base_url(llm_model),
|
|
376
|
+
llm_config_path=_parse_optional_path_env("LITELLM_CONFIG"),
|
|
377
|
+
llm_fallback_models=_resolve_llm_fallback_models(llm_model),
|
|
378
|
+
llm_channels=channels,
|
|
379
|
+
llm_context=os.getenv("LLM_CONTEXT", ""),
|
|
380
|
+
llm_candidate_context_enabled=_parse_bool_env("LLM_CANDIDATE_CONTEXT_ENABLED", False),
|
|
381
|
+
llm_candidate_context_max_candidates=max(
|
|
382
|
+
1,
|
|
383
|
+
int(os.getenv("LLM_CANDIDATE_CONTEXT_MAX_CANDIDATES", "8")),
|
|
384
|
+
),
|
|
385
|
+
llm_candidate_context_providers=_parse_csv_env(
|
|
386
|
+
"LLM_CANDIDATE_CONTEXT_PROVIDERS",
|
|
387
|
+
["news", "fund_flow", "announcement", "quote"],
|
|
388
|
+
),
|
|
389
|
+
llm_candidate_context_news_limit=max(1, int(os.getenv("LLM_CANDIDATE_CONTEXT_NEWS_LIMIT", "3"))),
|
|
390
|
+
llm_candidate_context_announcement_limit=max(
|
|
391
|
+
1,
|
|
392
|
+
int(os.getenv("LLM_CANDIDATE_CONTEXT_ANNOUNCEMENT_LIMIT", "3")),
|
|
393
|
+
),
|
|
394
|
+
llm_candidate_context_cache_enabled=_parse_bool_env("LLM_CANDIDATE_CONTEXT_CACHE_ENABLED", True),
|
|
395
|
+
llm_candidate_context_cache_ttl_hours=max(
|
|
396
|
+
0,
|
|
397
|
+
int(os.getenv("LLM_CANDIDATE_CONTEXT_CACHE_TTL_HOURS", "24")),
|
|
398
|
+
),
|
|
399
|
+
llm_candidate_context_cache_dir=(
|
|
400
|
+
_parse_optional_path_env("ALPHASIFT_CANDIDATE_CONTEXT_CACHE_DIR")
|
|
401
|
+
or _parse_optional_path_env("LLM_CANDIDATE_CONTEXT_CACHE_DIR")
|
|
402
|
+
),
|
|
403
|
+
llm_temperature=_parse_float_env("LLM_TEMPERATURE", 0.2),
|
|
404
|
+
llm_json_mode=_parse_bool_env("LLM_JSON_MODE", True),
|
|
405
|
+
llm_silent=_parse_bool_env("LLM_SILENT", True),
|
|
406
|
+
llm_rank_weight=_parse_float_env("LLM_RANK_WEIGHT", 0.40),
|
|
407
|
+
llm_candidate_multiplier=max(1, int(os.getenv("LLM_CANDIDATE_MULTIPLIER", "6"))),
|
|
408
|
+
llm_max_candidates=max(1, int(os.getenv("LLM_MAX_CANDIDATES", "30"))),
|
|
409
|
+
llm_max_retries=max(0, int(os.getenv("LLM_MAX_RETRIES", "1"))),
|
|
410
|
+
llm_min_coverage=_parse_float_env("LLM_MIN_COVERAGE", 0.60),
|
|
411
|
+
llm_context_max_chars=max(500, int(os.getenv("LLM_CONTEXT_MAX_CHARS", "4000"))),
|
|
412
|
+
llm_timeout_sec=max(1.0, _parse_float_env("LLM_TIMEOUT_SEC", 60.0)),
|
|
413
|
+
llm_max_tokens=max(1, int(os.getenv("LLM_MAX_TOKENS", str(DEFAULT_LLM_MAX_TOKENS)))),
|
|
414
|
+
snapshot_source_priority=_resolve_snapshot_source_priority(),
|
|
415
|
+
fallback_snapshot_path=fallback_snapshot_path,
|
|
416
|
+
source_health_path=_resolve_source_health_path(data_dir),
|
|
417
|
+
snapshot_fallback_max_age_hours=_parse_optional_float_env(
|
|
418
|
+
"SNAPSHOT_FALLBACK_MAX_AGE_HOURS"
|
|
419
|
+
),
|
|
420
|
+
strategies_dir=_default_strategies_dir(),
|
|
421
|
+
industry_map_files=[
|
|
422
|
+
Path(item)
|
|
423
|
+
for item in _parse_csv_env("INDUSTRY_MAP_FILES", [])
|
|
424
|
+
],
|
|
425
|
+
industry_provider=os.getenv("INDUSTRY_PROVIDER", "none"),
|
|
426
|
+
industry_auto_backfill=_parse_bool_env("INDUSTRY_AUTO_BACKFILL", True),
|
|
427
|
+
industry_provider_max_boards=max(1, int(os.getenv("INDUSTRY_PROVIDER_MAX_BOARDS", "80"))),
|
|
428
|
+
industry_provider_cache_dir=industry_provider_cache_dir,
|
|
429
|
+
industry_provider_cache_ttl_hours=max(
|
|
430
|
+
0,
|
|
431
|
+
int(
|
|
432
|
+
os.getenv(
|
|
433
|
+
"ALPHASIFT_INDUSTRY_PROVIDER_CACHE_TTL_HOURS",
|
|
434
|
+
os.getenv("INDUSTRY_PROVIDER_CACHE_TTL_HOURS", "24"),
|
|
435
|
+
)
|
|
436
|
+
),
|
|
437
|
+
),
|
|
438
|
+
dsa_api_url=os.getenv("DSA_API_URL", ""),
|
|
439
|
+
dsa_report_type=os.getenv("DSA_REPORT_TYPE", "detailed"),
|
|
440
|
+
dsa_max_picks=max(1, int(os.getenv("DSA_MAX_PICKS", "3"))),
|
|
441
|
+
dsa_timeout_sec=float(os.getenv("DSA_TIMEOUT_SEC", "120")),
|
|
442
|
+
dsa_force_refresh=_parse_bool_env("DSA_FORCE_REFRESH", False),
|
|
443
|
+
dsa_notify=_parse_bool_env("DSA_NOTIFY", False),
|
|
444
|
+
post_analyzers=_parse_csv_env("POST_ANALYZERS", DEFAULT_POST_ANALYZERS),
|
|
445
|
+
post_analysis_max_picks=max(
|
|
446
|
+
1,
|
|
447
|
+
int(os.getenv("POST_ANALYSIS_MAX_PICKS", os.getenv("DSA_MAX_PICKS", "3"))),
|
|
448
|
+
),
|
|
449
|
+
post_analyzer_url=os.getenv("POST_ANALYZER_URL", ""),
|
|
450
|
+
post_analyzer_timeout_sec=float(os.getenv("POST_ANALYZER_TIMEOUT_SEC", "120")),
|
|
451
|
+
daily_enrich_enabled=_parse_bool_env("DAILY_ENRICH_ENABLED", False),
|
|
452
|
+
daily_enrich_max_candidates=max(1, int(os.getenv("DAILY_ENRICH_MAX_CANDIDATES", "100"))),
|
|
453
|
+
daily_lookback_days=max(30, int(os.getenv("DAILY_LOOKBACK_DAYS", "120"))),
|
|
454
|
+
daily_source=os.getenv("DAILY_SOURCE", "auto"),
|
|
455
|
+
daily_fetch_retries=max(0, int(os.getenv("DAILY_FETCH_RETRIES", "2"))),
|
|
456
|
+
daily_fetch_max_workers=max(1, int(os.getenv("DAILY_FETCH_MAX_WORKERS", "1"))),
|
|
457
|
+
daily_history_cache_dir=daily_history_cache_dir,
|
|
458
|
+
daily_history_cache_ttl_hours=max(
|
|
459
|
+
0,
|
|
460
|
+
int(
|
|
461
|
+
os.getenv(
|
|
462
|
+
"ALPHASIFT_DAILY_HISTORY_CACHE_TTL_HOURS",
|
|
463
|
+
os.getenv("DAILY_HISTORY_CACHE_TTL_HOURS", "24"),
|
|
464
|
+
)
|
|
465
|
+
),
|
|
466
|
+
),
|
|
467
|
+
daily_pack_enabled=_parse_bool_env("ALPHASIFT_DAILY_PACK_ENABLED", True),
|
|
468
|
+
daily_pack_dir=_parse_optional_path_env("ALPHASIFT_PACK_DIR"),
|
|
469
|
+
risk_enabled=_parse_bool_env("RISK_ENABLED", True),
|
|
470
|
+
risk_max_penalty=_parse_float_env("RISK_MAX_PENALTY", 12.0),
|
|
471
|
+
risk_veto_high=_parse_bool_env("RISK_VETO_HIGH", False),
|
|
472
|
+
portfolio_diversity_enabled=_parse_bool_env("PORTFOLIO_DIVERSITY_ENABLED", True),
|
|
473
|
+
portfolio_max_same_llm_sector=max(
|
|
474
|
+
1,
|
|
475
|
+
int(os.getenv("PORTFOLIO_MAX_SAME_LLM_SECTOR", "1")),
|
|
476
|
+
),
|
|
477
|
+
portfolio_concentration_penalty=_parse_float_env("PORTFOLIO_CONCENTRATION_PENALTY", 4.0),
|
|
478
|
+
evaluation_cost_bps=_parse_float_env("EVALUATION_COST_BPS", 0.0),
|
|
479
|
+
evaluation_follow_through_pct=_parse_float_env("EVALUATION_FOLLOW_THROUGH_PCT", 3.0),
|
|
480
|
+
evaluation_failed_breakout_pct=_parse_float_env("EVALUATION_FAILED_BREAKOUT_PCT", -3.0),
|
|
481
|
+
evaluation_price_path_enabled=_parse_bool_env("EVALUATION_PRICE_PATH_ENABLED", False),
|
|
482
|
+
evaluation_price_path_lookback_days=max(
|
|
483
|
+
30,
|
|
484
|
+
int(os.getenv("EVALUATION_PRICE_PATH_LOOKBACK_DAYS", "90")),
|
|
485
|
+
),
|
|
486
|
+
data_dir=data_dir,
|
|
487
|
+
notify_urls=_parse_notify_urls_env(),
|
|
488
|
+
wecom_webhook_url=(
|
|
489
|
+
os.getenv("ALPHASIFT_WECOM_WEBHOOK_URL") or os.getenv("WECOM_WEBHOOK_URL", "")
|
|
490
|
+
).strip(),
|
|
491
|
+
feishu_webhook_url=(
|
|
492
|
+
os.getenv("ALPHASIFT_FEISHU_WEBHOOK_URL") or os.getenv("FEISHU_WEBHOOK_URL", "")
|
|
493
|
+
).strip(),
|
|
494
|
+
feishu_webhook_secret=(
|
|
495
|
+
os.getenv("ALPHASIFT_FEISHU_WEBHOOK_SECRET") or os.getenv("FEISHU_WEBHOOK_SECRET", "")
|
|
496
|
+
).strip(),
|
|
497
|
+
dingtalk_webhook_url=(
|
|
498
|
+
os.getenv("ALPHASIFT_DINGTALK_WEBHOOK_URL") or os.getenv("DINGTALK_WEBHOOK_URL", "")
|
|
499
|
+
).strip(),
|
|
500
|
+
dingtalk_webhook_secret=(
|
|
501
|
+
os.getenv("ALPHASIFT_DINGTALK_WEBHOOK_SECRET") or os.getenv("DINGTALK_WEBHOOK_SECRET", "")
|
|
502
|
+
).strip(),
|
|
503
|
+
pushplus_token=(
|
|
504
|
+
os.getenv("ALPHASIFT_PUSHPLUS_TOKEN") or os.getenv("PUSHPLUS_TOKEN", "")
|
|
505
|
+
).strip(),
|
|
506
|
+
pushplus_topic=(
|
|
507
|
+
os.getenv("ALPHASIFT_PUSHPLUS_TOPIC") or os.getenv("PUSHPLUS_TOPIC", "")
|
|
508
|
+
).strip(),
|
|
509
|
+
serverchan_sendkey=(
|
|
510
|
+
os.getenv("ALPHASIFT_SERVERCHAN_SENDKEY")
|
|
511
|
+
or os.getenv("SERVERCHAN_SENDKEY")
|
|
512
|
+
or os.getenv("SERVERCHAN3_SENDKEY", "")
|
|
513
|
+
).strip(),
|
|
514
|
+
bark_url=(
|
|
515
|
+
os.getenv("ALPHASIFT_BARK_URL") or os.getenv("BARK_URL", "")
|
|
516
|
+
).strip(),
|
|
517
|
+
telegram_bot_token=(
|
|
518
|
+
os.getenv("ALPHASIFT_TELEGRAM_BOT_TOKEN") or os.getenv("TELEGRAM_BOT_TOKEN", "")
|
|
519
|
+
).strip(),
|
|
520
|
+
telegram_chat_id=(
|
|
521
|
+
os.getenv("ALPHASIFT_TELEGRAM_CHAT_ID") or os.getenv("TELEGRAM_CHAT_ID", "")
|
|
522
|
+
).strip(),
|
|
523
|
+
discord_webhook_url=(
|
|
524
|
+
os.getenv("ALPHASIFT_DISCORD_WEBHOOK_URL") or os.getenv("DISCORD_WEBHOOK_URL", "")
|
|
525
|
+
).strip(),
|
|
526
|
+
slack_webhook_url=(
|
|
527
|
+
os.getenv("ALPHASIFT_SLACK_WEBHOOK_URL") or os.getenv("SLACK_WEBHOOK_URL", "")
|
|
528
|
+
).strip(),
|
|
529
|
+
ntfy_url=(
|
|
530
|
+
os.getenv("ALPHASIFT_NTFY_URL") or os.getenv("NTFY_URL", "")
|
|
531
|
+
).strip(),
|
|
532
|
+
email_sender=(
|
|
533
|
+
os.getenv("ALPHASIFT_EMAIL_SENDER") or os.getenv("EMAIL_SENDER", "")
|
|
534
|
+
).strip(),
|
|
535
|
+
email_password=(
|
|
536
|
+
os.getenv("ALPHASIFT_EMAIL_PASSWORD") or os.getenv("EMAIL_PASSWORD", "")
|
|
537
|
+
).strip(),
|
|
538
|
+
email_receivers=(
|
|
539
|
+
os.getenv("ALPHASIFT_EMAIL_RECEIVERS") or os.getenv("EMAIL_RECEIVERS", "")
|
|
540
|
+
).strip(),
|
|
541
|
+
email_smtp_host=(
|
|
542
|
+
os.getenv("ALPHASIFT_EMAIL_SMTP_HOST") or os.getenv("EMAIL_SMTP_HOST", "")
|
|
543
|
+
).strip(),
|
|
544
|
+
email_smtp_port=max(
|
|
545
|
+
0,
|
|
546
|
+
int(os.getenv("ALPHASIFT_EMAIL_SMTP_PORT") or os.getenv("EMAIL_SMTP_PORT", "0") or "0"),
|
|
547
|
+
),
|
|
548
|
+
custom_webhook_url=(
|
|
549
|
+
os.getenv("ALPHASIFT_CUSTOM_WEBHOOK_URL") or os.getenv("CUSTOM_WEBHOOK_URL", "")
|
|
550
|
+
).strip(),
|
|
551
|
+
custom_webhook_token=(
|
|
552
|
+
os.getenv("ALPHASIFT_CUSTOM_WEBHOOK_TOKEN") or os.getenv("CUSTOM_WEBHOOK_TOKEN", "")
|
|
553
|
+
).strip(),
|
|
554
|
+
notify_state_path=(
|
|
555
|
+
_parse_optional_path_env("ALPHASIFT_NOTIFY_STATE_PATH")
|
|
556
|
+
or (data_dir / "notify_state.json")
|
|
557
|
+
),
|
|
558
|
+
notify_timeout_sec=max(1.0, _parse_float_env("ALPHASIFT_NOTIFY_TIMEOUT_SEC", 10.0)),
|
|
559
|
+
dashboard_url=_resolve_dashboard_url(),
|
|
560
|
+
tavily_api_keys=_parse_csv_env("TAVILY_API_KEYS", []) or _parse_csv_env("TAVILY_API_KEY", []),
|
|
561
|
+
serpapi_api_keys=_parse_csv_env("SERPAPI_API_KEYS", []) or _parse_csv_env("SERPAPI_API_KEY", []),
|
|
562
|
+
)
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
def _resolve_dashboard_url() -> str:
|
|
566
|
+
"""Resolve user/Fork-safe dashboard URL without leaking upstream URL to third-party pushes."""
|
|
567
|
+
explicit = os.getenv("ALPHASIFT_DASHBOARD_URL")
|
|
568
|
+
if explicit is not None:
|
|
569
|
+
cleaned = explicit.strip()
|
|
570
|
+
if cleaned.lower() in {"", "none", "off", "false"}:
|
|
571
|
+
return ""
|
|
572
|
+
return cleaned
|
|
573
|
+
gh_repo = os.getenv("GITHUB_REPOSITORY", "").strip()
|
|
574
|
+
if gh_repo:
|
|
575
|
+
if gh_repo == "ZhuLinsen/alphasift":
|
|
576
|
+
return "https://alphasift.zhulinsen.tech/"
|
|
577
|
+
if _parse_bool_env("ALPHASIFT_ENABLE_PAGES", False) and "/" in gh_repo:
|
|
578
|
+
owner, repo = gh_repo.split("/", 1)
|
|
579
|
+
return f"https://{owner.lower()}.github.io/{repo}/"
|
|
580
|
+
return ""
|
|
581
|
+
return ""
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def _parse_float_env(name: str, default: float) -> float:
|
|
585
|
+
value = os.getenv(name)
|
|
586
|
+
if value is None or value == "":
|
|
587
|
+
return default
|
|
588
|
+
return float(value)
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
def _parse_notify_urls_env() -> list[str]:
|
|
592
|
+
raw = (os.getenv("ALPHASIFT_NOTIFY_URLS") or os.getenv("NOTIFY_URLS") or "").strip()
|
|
593
|
+
if not raw:
|
|
594
|
+
return []
|
|
595
|
+
urls: list[str] = []
|
|
596
|
+
# Split on newlines/semicolons, or commas before another scheme:// (preserves mailto://...?to=a,b).
|
|
597
|
+
for block in re.split(r"[\r\n;]+", raw):
|
|
598
|
+
for chunk in re.split(r"(?:\s*,\s*)+(?=[A-Za-z][A-Za-z0-9+.-]*://)", block):
|
|
599
|
+
cleaned = chunk.strip().strip(",").strip()
|
|
600
|
+
if cleaned and cleaned not in urls:
|
|
601
|
+
urls.append(cleaned)
|
|
602
|
+
return urls
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
def _parse_optional_float_env(name: str) -> float | None:
|
|
606
|
+
value = os.getenv(name)
|
|
607
|
+
if value is None:
|
|
608
|
+
return None
|
|
609
|
+
cleaned = value.strip()
|
|
610
|
+
if cleaned.lower() in {"", "none", "off", "false"}:
|
|
611
|
+
return None
|
|
612
|
+
return float(cleaned)
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def _parse_llm_channels_env() -> list[dict[str, object]]:
|
|
616
|
+
channels = []
|
|
617
|
+
for raw_name in _parse_csv_env("LLM_CHANNELS", []):
|
|
618
|
+
name = raw_name.strip()
|
|
619
|
+
if not name:
|
|
620
|
+
continue
|
|
621
|
+
key = name.upper()
|
|
622
|
+
enabled = _parse_bool_env(f"LLM_{key}_ENABLED", True)
|
|
623
|
+
api_keys = (
|
|
624
|
+
_parse_csv_env(f"LLM_{key}_API_KEYS", [])
|
|
625
|
+
or _parse_csv_env(f"LLM_{key}_API_KEY", [])
|
|
626
|
+
)
|
|
627
|
+
channels.append({
|
|
628
|
+
"name": name.lower(),
|
|
629
|
+
"protocol": (os.getenv(f"LLM_{key}_PROTOCOL") or "").strip().lower() or "openai",
|
|
630
|
+
"base_url": os.getenv(f"LLM_{key}_BASE_URL", "").strip(),
|
|
631
|
+
"api_keys": api_keys,
|
|
632
|
+
"models": _parse_csv_env(f"LLM_{key}_MODELS", []),
|
|
633
|
+
"enabled": enabled,
|
|
634
|
+
})
|
|
635
|
+
return [channel for channel in channels if channel["enabled"]]
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
def _resolve_llm_model(channels: list[dict[str, object]]) -> str:
|
|
639
|
+
explicit = (
|
|
640
|
+
os.getenv("LITELLM_MODEL")
|
|
641
|
+
or os.getenv("LLM_MODEL")
|
|
642
|
+
or os.getenv("AGENT_LITELLM_MODEL")
|
|
643
|
+
or ""
|
|
644
|
+
).strip()
|
|
645
|
+
if explicit:
|
|
646
|
+
return normalize_model(explicit)
|
|
647
|
+
|
|
648
|
+
for channel in channels:
|
|
649
|
+
models = channel.get("models", [])
|
|
650
|
+
if isinstance(models, list) and models:
|
|
651
|
+
return normalize_model(str(models[0]), str(channel.get("protocol", "openai")))
|
|
652
|
+
|
|
653
|
+
if os.getenv("OLLAMA_API_BASE"):
|
|
654
|
+
ollama_model = os.getenv("OLLAMA_MODEL", "").strip()
|
|
655
|
+
return f"ollama/{ollama_model}" if ollama_model else DEFAULT_LLM_MODEL
|
|
656
|
+
if os.getenv("DEEPSEEK_API_KEY"):
|
|
657
|
+
return "deepseek/deepseek-chat"
|
|
658
|
+
if os.getenv("GEMINI_API_KEY") or os.getenv("GEMINI_API_KEYS"):
|
|
659
|
+
gemini_model = (os.getenv("GEMINI_MODEL") or "").strip() or DEFAULT_LLM_MODEL
|
|
660
|
+
return normalize_model(gemini_model, "gemini")
|
|
661
|
+
if os.getenv("OPENAI_API_KEY") or os.getenv("AIHUBMIX_KEY"):
|
|
662
|
+
openai_model = (os.getenv("OPENAI_MODEL") or "").strip() or "gpt-4o-mini"
|
|
663
|
+
return normalize_model(openai_model)
|
|
664
|
+
return DEFAULT_LLM_MODEL
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
def _resolve_llm_fallback_models(llm_model: str) -> list[str]:
|
|
668
|
+
raw_fb = os.getenv("LITELLM_FALLBACK_MODELS")
|
|
669
|
+
if raw_fb is not None:
|
|
670
|
+
cleaned = raw_fb.strip()
|
|
671
|
+
if not cleaned or cleaned.lower() in {"none", "off", "false", "0"}:
|
|
672
|
+
return []
|
|
673
|
+
return _parse_csv_env("LITELLM_FALLBACK_MODELS", [])
|
|
674
|
+
if llm_model == DEFAULT_LLM_MODEL:
|
|
675
|
+
return list(DEFAULT_GEMINI_FALLBACK_MODELS)
|
|
676
|
+
return []
|
|
677
|
+
|
|
678
|
+
|
|
679
|
+
def _resolve_llm_api_key(model: str) -> str:
|
|
680
|
+
explicit = os.getenv("LLM_API_KEY", "").strip()
|
|
681
|
+
if explicit:
|
|
682
|
+
return explicit
|
|
683
|
+
provider, _ = split_model(model)
|
|
684
|
+
if provider == "openai" and os.getenv("AIHUBMIX_KEY"):
|
|
685
|
+
return os.getenv("AIHUBMIX_KEY", "")
|
|
686
|
+
keys = gateway_api_keys(provider)
|
|
687
|
+
return keys[0] if keys else ""
|
|
688
|
+
|
|
689
|
+
|
|
690
|
+
def _resolve_llm_base_url(model: str) -> str:
|
|
691
|
+
explicit = os.getenv("LLM_BASE_URL", "").strip()
|
|
692
|
+
if explicit:
|
|
693
|
+
return explicit
|
|
694
|
+
provider, _ = split_model(model)
|
|
695
|
+
if provider == "ollama":
|
|
696
|
+
return os.getenv("OLLAMA_API_BASE", "")
|
|
697
|
+
if provider == "openai":
|
|
698
|
+
if os.getenv("AIHUBMIX_KEY"):
|
|
699
|
+
return gateway_base_url("aihubmix")
|
|
700
|
+
return os.getenv("OPENAI_BASE_URL", "")
|
|
701
|
+
# Never route non-OpenAI provider keys (e.g. GEMINI_API_KEY / DEEPSEEK_API_KEY)
|
|
702
|
+
# to OPENAI_BASE_URL unless LLM_API_KEY explicitly overrides credentials too.
|
|
703
|
+
if provider in {"gemini", "deepseek", "anthropic"} and os.getenv("LLM_API_KEY", "").strip():
|
|
704
|
+
return os.getenv("OPENAI_BASE_URL", "")
|
|
705
|
+
return ""
|