-
Notifications
You must be signed in to change notification settings - Fork 54.3k
Expand file tree
/
Copy pathsystem_config_service.py
More file actions
3491 lines (3237 loc) · 142 KB
/
Copy pathsystem_config_service.py
File metadata and controls
3491 lines (3237 loc) · 142 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 -*-
"""System configuration service for `.env` based settings."""
from __future__ import annotations
import io
import logging
import json
import os
import re
import time
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Set, Tuple
from urllib.parse import urljoin, urlparse, urlunparse
import requests
from src.config import (
ANSPIRE_LLM_BASE_URL_DEFAULT,
ANSPIRE_LLM_MODEL_DEFAULT,
SUPPORTED_LLM_CHANNEL_PROTOCOLS,
Config,
_get_litellm_provider,
_uses_direct_env_provider,
canonicalize_llm_channel_protocol,
channel_allows_empty_api_key,
get_configured_llm_models,
normalize_agent_litellm_model,
normalize_litellm_temperature,
normalize_news_strategy_profile,
normalize_llm_channel_model,
parse_env_bool,
parse_env_int,
resolve_news_window_days,
resolve_llm_channel_protocol,
setup_env,
)
from src.core.config_manager import ConfigManager
from src.core.config_registry import (
build_schema_response,
get_category_definitions,
get_field_definition,
get_registered_field_keys,
)
logger = logging.getLogger(__name__)
class ConfigValidationError(Exception):
"""Raised when one or more submitted fields fail validation."""
def __init__(self, issues: List[Dict[str, Any]]):
super().__init__("Configuration validation failed")
self.issues = issues
class ConfigConflictError(Exception):
"""Raised when submitted config_version is stale."""
def __init__(self, current_version: str):
super().__init__("Configuration version conflict")
self.current_version = current_version
class ConfigImportError(Exception):
"""Raised when an imported `.env` payload is invalid."""
def __init__(self, message: str):
super().__init__(message)
self.message = message
@dataclass(frozen=True)
class _LLMDiagnostic:
"""Internal structured diagnosis for LLM test and discovery failures."""
error_code: str
retryable: bool
message: str
reason: Optional[str] = None
details: Dict[str, Any] = field(default_factory=dict)
class SystemConfigService:
"""Service layer for reading, validating, and updating runtime configuration."""
_LLM_CAPABILITY_ORDER: Tuple[str, ...] = ("json", "tools", "stream", "vision")
_LLM_STREAM_CHUNK_LIMIT = 8
# 仅对现有复现与回归样本中的上游拦截文案做 best-effort 识别(来源:Issue #1223 复现日志 + 回归覆盖);
# 该分类只用于诊断展示,不作为配置迁移或清理触发条件。
_LLM_PROVIDER_BLOCKED_TOKENS: Tuple[str, ...] = (
"your request was blocked",
"request was blocked",
"request was blocked by safety",
"request was blocked by policy",
"request has been blocked by provider safety",
"blocked by safety",
"blocked by policy",
"blocked by content",
"moderation_blocked",
)
_LLM_CAPABILITY_PROBE_IMAGE = (
"data:image/png;base64,"
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII="
)
_DISPLAY_KEY_ALIASES: Dict[str, Tuple[str, ...]] = {
"AGENT_SKILL_DIR": ("AGENT_SKILL_DIR", "AGENT_STRATEGY_DIR"),
"AGENT_SKILL_AUTOWEIGHT": ("AGENT_SKILL_AUTOWEIGHT", "AGENT_STRATEGY_AUTOWEIGHT"),
"AGENT_SKILL_ROUTING": ("AGENT_SKILL_ROUTING", "AGENT_STRATEGY_ROUTING"),
}
_DISPLAY_VALUE_ALIASES: Dict[str, Dict[str, str]] = {
"AGENT_ORCHESTRATOR_MODE": {
"strategy": "specialist",
"skill": "specialist",
}
}
_NOTIFICATION_TEST_CHANNELS: Tuple[str, ...] = (
"wechat",
"feishu",
"telegram",
"email",
"pushover",
"pushplus",
"serverchan3",
"custom",
"discord",
"slack",
"astrbot",
)
_NOTIFICATION_TEST_KEY_MAP: Dict[str, Tuple[str, str]] = {
"WECHAT_WEBHOOK_URL": ("wechat_webhook_url", "string"),
"WECHAT_MSG_TYPE": ("wechat_msg_type", "string"),
"WECHAT_MAX_BYTES": ("wechat_max_bytes", "int"),
"FEISHU_WEBHOOK_URL": ("feishu_webhook_url", "string"),
"FEISHU_WEBHOOK_SECRET": ("feishu_webhook_secret", "string"),
"FEISHU_WEBHOOK_KEYWORD": ("feishu_webhook_keyword", "string"),
"FEISHU_MAX_BYTES": ("feishu_max_bytes", "int"),
"TELEGRAM_BOT_TOKEN": ("telegram_bot_token", "string"),
"TELEGRAM_CHAT_ID": ("telegram_chat_id", "string"),
"TELEGRAM_MESSAGE_THREAD_ID": ("telegram_message_thread_id", "string"),
"EMAIL_SENDER": ("email_sender", "string"),
"EMAIL_SENDER_NAME": ("email_sender_name", "string"),
"EMAIL_PASSWORD": ("email_password", "string"),
"EMAIL_RECEIVERS": ("email_receivers", "csv"),
"PUSHOVER_USER_KEY": ("pushover_user_key", "string"),
"PUSHOVER_API_TOKEN": ("pushover_api_token", "string"),
"PUSHPLUS_TOKEN": ("pushplus_token", "string"),
"PUSHPLUS_TOPIC": ("pushplus_topic", "string"),
"SERVERCHAN3_SENDKEY": ("serverchan3_sendkey", "string"),
"CUSTOM_WEBHOOK_URLS": ("custom_webhook_urls", "csv"),
"CUSTOM_WEBHOOK_BEARER_TOKEN": ("custom_webhook_bearer_token", "string"),
"CUSTOM_WEBHOOK_BODY_TEMPLATE": ("custom_webhook_body_template", "string"),
"WEBHOOK_VERIFY_SSL": ("webhook_verify_ssl", "bool"),
"DISCORD_WEBHOOK_URL": ("discord_webhook_url", "string"),
"DISCORD_BOT_TOKEN": ("discord_bot_token", "string"),
"DISCORD_MAIN_CHANNEL_ID": ("discord_main_channel_id", "string"),
"DISCORD_CHANNEL_ID": ("discord_main_channel_id", "string"),
"DISCORD_MAX_WORDS": ("discord_max_words", "int"),
"SLACK_WEBHOOK_URL": ("slack_webhook_url", "string"),
"SLACK_BOT_TOKEN": ("slack_bot_token", "string"),
"SLACK_CHANNEL_ID": ("slack_channel_id", "string"),
"ASTRBOT_URL": ("astrbot_url", "string"),
"ASTRBOT_TOKEN": ("astrbot_token", "string"),
}
_NOTIFICATION_REQUIRED_KEY_GROUPS: Dict[str, Tuple[Tuple[str, ...], ...]] = {
"wechat": (("WECHAT_WEBHOOK_URL",),),
"feishu": (("FEISHU_WEBHOOK_URL",),),
"telegram": (("TELEGRAM_BOT_TOKEN", "TELEGRAM_CHAT_ID"),),
"email": (("EMAIL_SENDER", "EMAIL_PASSWORD"),),
"pushover": (("PUSHOVER_USER_KEY", "PUSHOVER_API_TOKEN"),),
"pushplus": (("PUSHPLUS_TOKEN",),),
"serverchan3": (("SERVERCHAN3_SENDKEY",),),
"custom": (("CUSTOM_WEBHOOK_URLS",),),
"discord": (("DISCORD_WEBHOOK_URL",), ("DISCORD_BOT_TOKEN", "DISCORD_MAIN_CHANNEL_ID"), ("DISCORD_BOT_TOKEN", "DISCORD_CHANNEL_ID")),
"slack": (("SLACK_WEBHOOK_URL",), ("SLACK_BOT_TOKEN", "SLACK_CHANNEL_ID")),
"astrbot": (("ASTRBOT_URL",),),
}
_NOTIFICATION_TEST_TARGET_KEYS: Dict[str, Tuple[str, ...]] = {
"wechat": ("WECHAT_WEBHOOK_URL",),
"feishu": ("FEISHU_WEBHOOK_URL",),
"telegram": ("TELEGRAM_BOT_TOKEN",),
"email": ("EMAIL_RECEIVERS", "EMAIL_SENDER"),
"pushover": ("PUSHOVER_USER_KEY",),
"pushplus": ("PUSHPLUS_TOPIC",),
"serverchan3": ("SERVERCHAN3_SENDKEY",),
"custom": ("CUSTOM_WEBHOOK_URLS",),
"discord": ("DISCORD_WEBHOOK_URL", "DISCORD_MAIN_CHANNEL_ID", "DISCORD_CHANNEL_ID"),
"slack": ("SLACK_WEBHOOK_URL", "SLACK_CHANNEL_ID"),
"astrbot": ("ASTRBOT_URL",),
}
def __init__(self, manager: Optional[ConfigManager] = None):
self._manager = manager or ConfigManager()
def get_schema(self) -> Dict[str, Any]:
"""Return grouped schema metadata for UI rendering."""
return build_schema_response()
@staticmethod
def _reload_runtime_singletons() -> None:
"""Reset runtime singleton services after config reload."""
from src.agent.tools.data_tools import reset_fetcher_manager
from src.search_service import reset_search_service
reset_fetcher_manager()
reset_search_service()
@classmethod
def _normalize_display_value(cls, key: str, value: str) -> str:
alias_map = cls._DISPLAY_VALUE_ALIASES.get(key.upper())
if not alias_map:
return value
return alias_map.get(value.strip().lower(), value)
@classmethod
def _build_display_config_map(cls, raw_config_map: Dict[str, str]) -> Dict[str, str]:
raw_upper = {key.upper(): value for key, value in raw_config_map.items()}
aliased_keys = {
alias
for candidates in cls._DISPLAY_KEY_ALIASES.values()
for alias in candidates
}
display_map: Dict[str, str] = {}
for key, value in raw_upper.items():
if key in aliased_keys:
continue
display_map[key] = cls._normalize_display_value(key, value)
for canonical_key, candidates in cls._DISPLAY_KEY_ALIASES.items():
canonical_env_key = candidates[0]
if canonical_env_key in raw_upper:
display_map[canonical_key] = cls._normalize_display_value(
canonical_key,
raw_upper[canonical_env_key],
)
continue
selected_value: Optional[str] = None
candidate_seen = False
for candidate_key in candidates[1:]:
if candidate_key not in raw_upper:
continue
candidate_seen = True
candidate_value = raw_upper[candidate_key]
if candidate_value:
selected_value = candidate_value
break
if candidate_seen:
if selected_value is None:
for candidate_key in candidates[1:]:
if candidate_key in raw_upper:
selected_value = raw_upper[candidate_key]
break
if selected_value is None:
selected_value = ""
display_map[canonical_key] = cls._normalize_display_value(
canonical_key,
selected_value,
)
return display_map
def get_config(self, include_schema: bool = True, mask_token: str = "******") -> Dict[str, Any]:
"""Return current config values without server-side secret masking."""
config_map = self._build_display_config_map(self._manager.read_config_map())
registered_keys = set(get_registered_field_keys())
all_keys = set(config_map.keys()) | registered_keys
category_orders = {
item["category"]: item["display_order"]
for item in get_category_definitions()
}
schema_by_key: Dict[str, Dict[str, Any]] = {
key: get_field_definition(key, config_map.get(key, ""))
for key in all_keys
}
items: List[Dict[str, Any]] = []
for key in all_keys:
raw_value = config_map.get(key, "")
field_schema = schema_by_key[key]
item: Dict[str, Any] = {
"key": key,
"value": raw_value,
"raw_value_exists": bool(raw_value),
"is_masked": False,
}
if include_schema:
item["schema"] = field_schema
items.append(item)
items.sort(
key=lambda item: (
category_orders.get(schema_by_key[item["key"]].get("category", "uncategorized"), 999),
schema_by_key[item["key"]].get("display_order", 9999),
item["key"],
)
)
return {
"config_version": self._manager.get_config_version(),
"mask_token": mask_token,
"items": items,
"updated_at": self._manager.get_updated_at(),
}
def validate(self, items: Sequence[Dict[str, str]], mask_token: str = "******") -> Dict[str, Any]:
"""Validate submitted items without writing to `.env`."""
issues = self._collect_issues(items=items, mask_token=mask_token)
valid = not any(issue["severity"] == "error" for issue in issues)
return {
"valid": valid,
"issues": issues,
}
def test_notification_channel(
self,
*,
channel: str,
items: Sequence[Dict[str, str]],
mask_token: str = "******",
title: str = "DSA 通知测试",
content: str = "这是一条来自 DSA Web 设置页的通知测试消息。",
timeout_seconds: float = 20.0,
) -> Dict[str, Any]:
"""Send one real notification test without persisting submitted values."""
normalized_channel = (channel or "").strip().lower()
if normalized_channel not in self._NOTIFICATION_TEST_CHANNELS:
raise ValueError(f"Unsupported notification channel: {channel}")
effective_map = self._build_notification_test_effective_map(
items=items,
mask_token=mask_token,
)
missing = self._get_missing_notification_test_keys(normalized_channel, effective_map)
if missing:
return self._build_notification_test_result(
success=False,
message=f"通知渠道配置不完整,缺少: {', '.join(missing)}",
error_code="config_missing",
stage="config_validation",
retryable=False,
latency_ms=None,
attempts=[],
)
config = self._build_notification_test_config(effective_map)
try:
return self._dispatch_notification_test(
channel=normalized_channel,
config=config,
effective_map=effective_map,
title=title.strip(),
content=content.strip(),
timeout_seconds=float(timeout_seconds),
)
except Exception as exc:
logger.warning("Notification channel test failed for %s: %s", normalized_channel, exc)
error_code, retryable = self._classify_notification_exception(exc)
return self._build_notification_test_result(
success=False,
message=f"通知测试异常: {exc}",
error_code=error_code,
stage="notification_send",
retryable=retryable,
latency_ms=None,
attempts=[
{
"channel": normalized_channel,
"success": False,
"message": str(exc),
"target": self._resolve_notification_test_target(normalized_channel, effective_map),
"error_code": error_code,
"stage": "notification_send",
"retryable": retryable,
"latency_ms": None,
}
],
)
def get_setup_status(self) -> Dict[str, Any]:
"""Return read-only first-run setup status without mutating runtime state."""
effective_map = self._build_setup_effective_config_map()
llm_check = self._build_setup_primary_llm_check(effective_map)
agent_check = self._build_setup_agent_llm_check(effective_map, llm_check)
checks = [
llm_check,
agent_check,
self._build_setup_stock_list_check(effective_map),
self._build_setup_notification_check(effective_map),
self._build_setup_storage_check(effective_map),
]
required_missing = [
check["key"]
for check in checks
if check["required"] and check["status"] == "needs_action"
]
return {
"is_complete": not required_missing,
"ready_for_smoke": not required_missing,
"required_missing_keys": required_missing,
"next_step_key": required_missing[0] if required_missing else None,
"checks": checks,
}
def export_desktop_env(self) -> Dict[str, Any]:
"""Return the raw active `.env` content for desktop-only backup."""
if self._manager.env_path.exists():
content = self._manager.env_path.read_text(encoding="utf-8")
else:
content = ""
return {
"content": content,
"config_version": self._manager.get_config_version(),
"updated_at": self._manager.get_updated_at(),
}
def import_desktop_env(
self,
*,
config_version: str,
content: str,
reload_now: bool = True,
) -> Dict[str, Any]:
"""Merge imported `.env` assignments into the active config."""
current_version = self._manager.get_config_version()
if current_version != config_version:
raise ConfigConflictError(current_version=current_version)
updates = self._parse_imported_env_content(content)
return self.update(
config_version=config_version,
items=updates,
mask_token="__DSA_IMPORT_LITERAL_MASK__",
reload_now=reload_now,
)
def discover_llm_channel_models(
self,
*,
name: str,
protocol: str,
base_url: str,
api_key: str,
models: Sequence[str] = (),
timeout_seconds: float = 20.0,
) -> Dict[str, Any]:
"""Discover available models from an OpenAI-compatible `/models` endpoint."""
channel_name = name.strip() or "channel"
existing_models = [str(m).strip() for m in models if str(m).strip()]
validation_issues, resolved_protocol = self._validate_llm_channel_connection(
channel_name=channel_name,
protocol_value=protocol,
base_url_value=base_url,
api_key_value=api_key,
model_values=existing_models,
field_prefix="discover_channel",
require_base_url=True,
)
if not resolved_protocol and existing_models:
resolved_protocol = resolve_llm_channel_protocol(
protocol,
base_url=base_url,
models=existing_models,
channel_name=channel_name,
)
errors = [issue for issue in validation_issues if issue["severity"] == "error"]
if errors:
return self._build_llm_channel_result(
success=False,
message="LLM channel configuration is invalid",
error=errors[0]["message"],
stage="model_discovery",
error_code="invalid_config",
retryable=False,
details={
"issue_key": errors[0]["key"],
"issue_code": errors[0]["code"],
"reason": errors[0]["code"],
},
resolved_protocol=resolved_protocol or None,
models=[],
latency_ms=None,
)
if resolved_protocol not in {"openai", "deepseek"}:
return self._build_llm_channel_result(
success=False,
message="Model discovery is not supported for this protocol",
error=(
f"LLM channel '{channel_name}' protocol '{resolved_protocol}' "
"does not support /models discovery yet"
),
stage="model_discovery",
error_code="unsupported_protocol",
retryable=False,
details={"protocol": resolved_protocol or None},
resolved_protocol=resolved_protocol or None,
models=[],
latency_ms=None,
)
api_keys = [segment.strip() for segment in api_key.split(",") if segment.strip()]
selected_api_key = api_keys[0] if api_keys else ""
request_headers = {"Accept": "application/json"}
if selected_api_key:
request_headers["Authorization"] = f"Bearer {selected_api_key}"
models_url = self._build_llm_models_url(base_url)
try:
started_at = time.perf_counter()
response = requests.get(
models_url,
headers=request_headers,
timeout=max(5.0, float(timeout_seconds)),
allow_redirects=False,
)
latency_ms = int((time.perf_counter() - started_at) * 1000)
except requests.RequestException as exc:
logger.warning("LLM channel model discovery failed for %s: %s", channel_name, exc)
diagnostic = self._classify_llm_exception(exc)
return self._build_llm_channel_result(
success=False,
message=diagnostic.message,
error=str(exc),
stage="model_discovery",
error_code=diagnostic.error_code,
retryable=diagnostic.retryable,
details=self._merge_llm_diagnostic_details({"endpoint": models_url}, diagnostic),
resolved_protocol=resolved_protocol or None,
models=[],
latency_ms=None,
)
if 300 <= response.status_code < 400:
return self._build_llm_channel_result(
success=False,
message="Model discovery request was redirected",
error="Redirect responses are not allowed for model discovery",
stage="model_discovery",
error_code="network_error",
retryable=False,
details={"endpoint": models_url, "http_status": response.status_code},
resolved_protocol=resolved_protocol or None,
models=[],
latency_ms=latency_ms,
)
if not response.ok:
error_text = self._extract_llm_discovery_error(response)
diagnostic = self._classify_llm_http_error(
status_code=response.status_code,
error_text=error_text,
)
return self._build_llm_channel_result(
success=False,
message=diagnostic.message,
error=error_text,
stage="model_discovery",
error_code=diagnostic.error_code,
retryable=diagnostic.retryable,
details=self._merge_llm_diagnostic_details(
{"endpoint": models_url, "http_status": response.status_code},
diagnostic,
),
resolved_protocol=resolved_protocol or None,
models=[],
latency_ms=latency_ms,
)
try:
payload = response.json()
except ValueError:
return self._build_llm_channel_result(
success=False,
message="Model discovery returned invalid JSON",
error="The /models endpoint did not return valid JSON",
stage="response_parse",
error_code="format_error",
retryable=False,
details={"endpoint": models_url, "http_status": response.status_code, "reason": "non_json"},
resolved_protocol=resolved_protocol or None,
models=[],
latency_ms=latency_ms,
)
models = self._extract_discovered_llm_models(payload)
if not models:
return self._build_llm_channel_result(
success=False,
message="Model discovery returned no models",
error="The /models endpoint did not return any model IDs",
stage="response_parse",
error_code="empty_response",
retryable=False,
details={"endpoint": models_url, "http_status": response.status_code, "reason": "empty_models"},
resolved_protocol=resolved_protocol or None,
models=[],
latency_ms=latency_ms,
)
return self._build_llm_channel_result(
success=True,
message="LLM channel model discovery succeeded",
error=None,
stage="model_discovery",
error_code=None,
retryable=False,
details={"endpoint": models_url, "model_count": len(models)},
resolved_protocol=resolved_protocol or None,
models=models,
latency_ms=latency_ms,
)
def test_llm_channel(
self,
*,
name: str,
protocol: str,
base_url: str,
api_key: str,
models: Sequence[str],
enabled: bool = True,
timeout_seconds: float = 20.0,
capability_checks: Sequence[str] = (),
) -> Dict[str, Any]:
"""Run a minimal completion call against one channel definition."""
requested_capabilities = self._normalize_llm_capability_checks(capability_checks)
raw_models = [str(model).strip() for model in models if str(model).strip()]
channel_name = name.strip() or "channel"
validation_issues = self._validate_llm_channel_definition(
channel_name=channel_name,
protocol_value=protocol,
base_url_value=base_url,
api_key_value=api_key,
model_values=raw_models,
enabled=enabled,
field_prefix="test_channel",
require_complete=True,
)
errors = [issue for issue in validation_issues if issue["severity"] == "error"]
if errors:
return self._build_llm_channel_result(
success=False,
message="LLM channel configuration is invalid",
error=errors[0]["message"],
stage="chat_completion",
error_code="invalid_config",
retryable=False,
details={
"issue_key": errors[0]["key"],
"issue_code": errors[0]["code"],
"reason": errors[0]["code"],
},
resolved_protocol=None,
resolved_model=None,
latency_ms=None,
capability_results=self._build_skipped_capability_results(
requested_capabilities,
"base_test_failed",
"Skipped because the base channel test did not pass",
),
)
resolved_protocol = resolve_llm_channel_protocol(protocol, base_url=base_url, models=raw_models, channel_name=name)
resolved_models = [normalize_llm_channel_model(model, resolved_protocol, base_url) for model in raw_models]
resolved_model = resolved_models[0]
api_keys = [segment.strip() for segment in api_key.split(",") if segment.strip()]
selected_api_key = api_keys[0] if api_keys else ""
call_kwargs: Dict[str, Any] = {
"model": resolved_model,
"messages": [{"role": "user", "content": "Reply with OK"}],
"temperature": normalize_litellm_temperature(
resolved_model,
self._get_runtime_llm_temperature(),
),
"max_tokens": 256, # Increased to allow MiniMax-M2.7 thinking process + response
"timeout": max(5.0, float(timeout_seconds)),
}
if selected_api_key:
call_kwargs["api_key"] = selected_api_key
if base_url.strip():
call_kwargs["api_base"] = base_url.strip()
try:
import litellm
from src.agent.llm_adapter import LLMToolAdapter
# Register custom model pricing for MiniMax models not in LiteLLM's built-in list
# This must be done before litellm.completion() to prevent cost calculation errors
# Reuses the registration logic from LLMToolAdapter to avoid code duplication
LLMToolAdapter._register_custom_model_pricing()
started_at = time.perf_counter()
response = litellm.completion(**call_kwargs)
latency_ms = int((time.perf_counter() - started_at) * 1000)
content, parse_error_code, parse_error, parse_reason = self._extract_llm_completion_content(response)
if parse_error_code:
message = (
"LLM channel returned an empty response"
if parse_error_code == "empty_response"
else "LLM channel returned an unexpected response format"
)
return self._build_llm_channel_result(
success=False,
message=message,
error=parse_error,
stage="response_parse",
error_code=parse_error_code,
retryable=False,
details={"response_error": parse_error, "reason": parse_reason},
resolved_protocol=resolved_protocol or None,
resolved_model=resolved_model,
latency_ms=latency_ms,
capability_results=self._build_skipped_capability_results(
requested_capabilities,
"base_test_failed",
"Skipped because the base channel test did not pass",
),
)
capability_results = (
self._run_llm_capability_checks(
litellm_module=litellm,
resolved_model=resolved_model,
selected_api_key=selected_api_key,
base_url=base_url,
timeout_seconds=timeout_seconds,
capability_checks=requested_capabilities,
)
if requested_capabilities
else {}
)
return self._build_llm_channel_result(
success=True,
message="LLM channel test succeeded",
error=None,
stage="chat_completion",
error_code=None,
retryable=False,
details={"response_preview": content[:80]},
resolved_protocol=resolved_protocol or None,
resolved_model=resolved_model,
latency_ms=latency_ms,
capability_results=capability_results,
)
except Exception as exc:
logger.warning("LLM channel test failed for %s: %s", channel_name, exc)
diagnostic = self._classify_llm_exception(exc)
return self._build_llm_channel_result(
success=False,
message=diagnostic.message,
error=str(exc),
stage="chat_completion",
error_code=diagnostic.error_code,
retryable=diagnostic.retryable,
details=self._merge_llm_diagnostic_details({"model": resolved_model}, diagnostic),
resolved_protocol=resolved_protocol or None,
resolved_model=resolved_model,
latency_ms=None,
capability_results=self._build_skipped_capability_results(
requested_capabilities,
"base_test_failed",
"Skipped because the base channel test did not pass",
),
)
@classmethod
def _normalize_llm_capability_checks(cls, capability_checks: Sequence[str]) -> List[str]:
requested = {str(check).strip().lower() for check in capability_checks if str(check).strip()}
return [check for check in cls._LLM_CAPABILITY_ORDER if check in requested]
@classmethod
def _build_skipped_capability_results(
cls,
capability_checks: Sequence[str],
reason: str,
message: str,
) -> Dict[str, Dict[str, Any]]:
return {
capability: cls._build_llm_capability_result(
capability=capability,
status="skipped",
message=message,
error_code="skipped",
retryable=False,
details={"reason": reason},
)
for capability in capability_checks
}
@classmethod
def _run_llm_capability_checks(
cls,
*,
litellm_module: Any,
resolved_model: str,
selected_api_key: str,
base_url: str,
timeout_seconds: float,
capability_checks: Sequence[str],
) -> Dict[str, Dict[str, Any]]:
results: Dict[str, Dict[str, Any]] = {}
for capability in capability_checks:
if capability == "json":
results[capability] = cls._run_json_capability_check(
litellm_module=litellm_module,
resolved_model=resolved_model,
selected_api_key=selected_api_key,
base_url=base_url,
timeout_seconds=timeout_seconds,
)
elif capability == "tools":
results[capability] = cls._run_tools_capability_check(
litellm_module=litellm_module,
resolved_model=resolved_model,
selected_api_key=selected_api_key,
base_url=base_url,
timeout_seconds=timeout_seconds,
)
elif capability == "stream":
results[capability] = cls._run_stream_capability_check(
litellm_module=litellm_module,
resolved_model=resolved_model,
selected_api_key=selected_api_key,
base_url=base_url,
timeout_seconds=timeout_seconds,
)
elif capability == "vision":
results[capability] = cls._run_vision_capability_check(
litellm_module=litellm_module,
resolved_model=resolved_model,
selected_api_key=selected_api_key,
base_url=base_url,
timeout_seconds=timeout_seconds,
)
return results
@classmethod
def _run_json_capability_check(
cls,
*,
litellm_module: Any,
resolved_model: str,
selected_api_key: str,
base_url: str,
timeout_seconds: float,
) -> Dict[str, Any]:
try:
started_at = time.perf_counter()
response = litellm_module.completion(
**cls._build_llm_capability_completion_kwargs(
resolved_model=resolved_model,
selected_api_key=selected_api_key,
base_url=base_url,
timeout_seconds=timeout_seconds,
messages=[{"role": "user", "content": 'Return exactly this JSON object: {"status":"ok"}'}],
max_tokens=64,
extra={"response_format": {"type": "json_object"}},
)
)
latency_ms = int((time.perf_counter() - started_at) * 1000)
content, parse_error_code, parse_error, parse_reason = cls._extract_llm_completion_content(response)
if parse_error_code:
return cls._build_llm_capability_result(
capability="json",
status="failed",
message="JSON capability check returned no parseable content",
error_code=parse_error_code,
retryable=False,
latency_ms=latency_ms,
details={"reason": parse_reason, "response_error": parse_error},
)
try:
payload = json.loads(content)
except ValueError:
return cls._build_llm_capability_result(
capability="json",
status="failed",
message="JSON capability check returned non-JSON content",
error_code="format_error",
retryable=False,
latency_ms=latency_ms,
details={"reason": "non_json", "response_preview": content[:80]},
)
if not isinstance(payload, dict) or payload.get("status") != "ok":
return cls._build_llm_capability_result(
capability="json",
status="failed",
message="JSON capability check returned unexpected JSON",
error_code="format_error",
retryable=False,
latency_ms=latency_ms,
details={"reason": "non_json", "response_preview": content[:80]},
)
return cls._build_llm_capability_result(
capability="json",
status="passed",
message="JSON output capability check passed",
latency_ms=latency_ms,
details={"reason": "json_valid"},
)
except Exception as exc:
diagnostic = cls._classify_llm_capability_exception(exc, "json")
return cls._build_llm_capability_result_from_diagnostic("json", diagnostic, str(exc))
@classmethod
def _run_tools_capability_check(
cls,
*,
litellm_module: Any,
resolved_model: str,
selected_api_key: str,
base_url: str,
timeout_seconds: float,
) -> Dict[str, Any]:
tools = [
{
"type": "function",
"function": {
"name": "dsa_probe_echo",
"description": "Return the provided text.",
"parameters": {
"type": "object",
"properties": {"text": {"type": "string"}},
"required": ["text"],
},
},
}
]
try:
started_at = time.perf_counter()
response = litellm_module.completion(
**cls._build_llm_capability_completion_kwargs(
resolved_model=resolved_model,
selected_api_key=selected_api_key,
base_url=base_url,
timeout_seconds=timeout_seconds,
messages=[{"role": "user", "content": "Call the dsa_probe_echo tool with text set to ok."}],
max_tokens=64,
extra={
"tools": tools,
"tool_choice": {"type": "function", "function": {"name": "dsa_probe_echo"}},
},
)
)
latency_ms = int((time.perf_counter() - started_at) * 1000)
tool_names = cls._extract_llm_tool_call_names(response)
if "dsa_probe_echo" not in tool_names:
return cls._build_llm_capability_result(
capability="tools",
status="failed",
message="Tool calling capability check did not return the probe tool call",
error_code="capability_unsupported",
retryable=False,
latency_ms=latency_ms,
details={"reason": "tool_calls_missing", "tool_calls": tool_names},
)
return cls._build_llm_capability_result(
capability="tools",
status="passed",
message="Tool calling capability check passed",
latency_ms=latency_ms,
details={"reason": "tool_call_returned"},
)
except Exception as exc:
diagnostic = cls._classify_llm_capability_exception(exc, "tools")
return cls._build_llm_capability_result_from_diagnostic("tools", diagnostic, str(exc))
@classmethod
def _run_stream_capability_check(
cls,
*,
litellm_module: Any,
resolved_model: str,
selected_api_key: str,
base_url: str,
timeout_seconds: float,
) -> Dict[str, Any]:
stream = None
started_at = time.perf_counter()
try:
stream = litellm_module.completion(
**cls._build_llm_capability_completion_kwargs(
resolved_model=resolved_model,
selected_api_key=selected_api_key,
base_url=base_url,
timeout_seconds=timeout_seconds,
messages=[{"role": "user", "content": "Reply with OK"}],
max_tokens=32,
extra={"stream": True},
)