Blame view

config/schema.py 14 KB
86d8358b   tangwang   config optimize
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
  """
  Typed configuration schema for the unified application configuration.
  
  This module defines the normalized in-memory structure used by all services.
  """
  
  from __future__ import annotations
  
  from dataclasses import asdict, dataclass, field
  from pathlib import Path
  from typing import Any, Dict, List, Optional, Tuple
  
  
  @dataclass(frozen=True)
  class IndexConfig:
      """Deprecated compatibility shape for legacy diagnostics/tests."""
  
      name: str
      label: str
      fields: List[str]
      boost: float = 1.0
      example: Optional[str] = None
  
  
  @dataclass(frozen=True)
  class QueryConfig:
      """Configuration for query processing."""
  
      supported_languages: List[str] = field(default_factory=lambda: ["zh", "en"])
      default_language: str = "en"
      enable_text_embedding: bool = True
      enable_query_rewrite: bool = True
      rewrite_dictionary: Dict[str, str] = field(default_factory=dict)
      text_embedding_field: Optional[str] = "title_embedding"
      image_embedding_field: Optional[str] = None
      source_fields: Optional[List[str]] = None
ed13851c   tangwang   图片文本两个knn召回相关参数配置
37
38
39
40
41
42
43
44
45
      # 文本向量 KNN 与多模态(图片)向量 KNN 各自 boost;未在 YAML 中写时由 loader 用 legacy knn_boost 回填
      knn_text_boost: float = 20.0
      knn_image_boost: float = 20.0
      knn_text_k: int = 120
      knn_text_num_candidates: int = 400
      knn_text_k_long: int = 160
      knn_text_num_candidates_long: int = 500
      knn_image_k: int = 120
      knn_image_num_candidates: int = 400
86d8358b   tangwang   config optimize
46
      multilingual_fields: List[str] = field(
445496cd   tangwang   fix last up: 每个翻译...
47
          default_factory=lambda: []
86d8358b   tangwang   config optimize
48
49
      )
      shared_fields: List[str] = field(
445496cd   tangwang   fix last up: 每个翻译...
50
          default_factory=lambda: []
86d8358b   tangwang   config optimize
51
52
      )
      core_multilingual_fields: List[str] = field(
445496cd   tangwang   fix last up: 每个翻译...
53
          default_factory=lambda: []
86d8358b   tangwang   config optimize
54
      )
272aeabe   tangwang   调参
55
56
      base_minimum_should_match: str = "70%"
      translation_minimum_should_match: str = "70%"
86d8358b   tangwang   config optimize
57
      translation_boost: float = 0.4
86d8358b   tangwang   config optimize
58
      tie_breaker_base_query: float = 0.9
e756b18e   tangwang   重构了文本召回构建器,现在每个 b...
59
60
61
62
      best_fields: Dict[str, float] = field(default_factory=dict)
      best_fields_boost: float = 2.0
      phrase_fields: Dict[str, float] = field(default_factory=dict)
      phrase_match_boost: float = 3.0
86d8358b   tangwang   config optimize
63
64
65
      zh_to_en_model: str = "opus-mt-zh-en"
      en_to_zh_model: str = "opus-mt-en-zh"
      default_translation_model: str = "nllb-200-distilled-600m"
86d0e83d   tangwang   query翻译,根据源语言是否在索...
66
67
68
69
      # 检测语种不在租户 index_languages(无可直接命中的多语字段)时使用;None 表示与上一组同模型。
      zh_to_en_model_source_not_in_index: Optional[str] = None
      en_to_zh_model_source_not_in_index: Optional[str] = None
      default_translation_model_source_not_in_index: Optional[str] = None
1556989b   tangwang   query翻译等待超时逻辑
70
71
72
73
74
      # 查询阶段:翻译与向量生成并发提交后,共用同一等待预算(毫秒)。
      # 检测语言已在租户 index_languages 内:偏快返回,预算较短。
      # 检测语言不在 index_languages 内:翻译对召回更关键,预算较长。
      translation_embedding_wait_budget_ms_source_in_index: int = 80
      translation_embedding_wait_budget_ms_source_not_in_index: int = 200
cda1cd62   tangwang   意图分析&应用 baseline
75
      style_intent_enabled: bool = True
87cacb1b   tangwang   融合公式优化。加入意图匹配因子
76
      style_intent_selected_sku_boost: float = 1.2
b712a831   tangwang   意图识别策略和性能优化
77
      style_intent_terms: Dict[str, List[Dict[str, List[str]]]] = field(default_factory=dict)
cda1cd62   tangwang   意图分析&应用 baseline
78
      style_intent_dimension_aliases: Dict[str, List[str]] = field(default_factory=dict)
74fdf9bd   tangwang   1.
79
80
      product_title_exclusion_enabled: bool = True
      product_title_exclusion_rules: List[Dict[str, List[str]]] = field(default_factory=list)
86d8358b   tangwang   config optimize
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
  
  
  @dataclass(frozen=True)
  class SPUConfig:
      """SPU aggregation/search configuration."""
  
      enabled: bool = False
      spu_field: Optional[str] = None
      inner_hits_size: int = 3
      searchable_option_dimensions: List[str] = field(
          default_factory=lambda: ["option1", "option2", "option3"]
      )
  
  
  @dataclass(frozen=True)
  class FunctionScoreConfig:
      """Function score configuration."""
  
      score_mode: str = "sum"
      boost_mode: str = "multiply"
      functions: List[Dict[str, Any]] = field(default_factory=list)
  
  
  @dataclass(frozen=True)
814e352b   tangwang   乘法公式配置化
105
106
107
  class RerankFusionConfig:
      """
      Multiplicative fusion: fused = Π (max(score_i, 0) + bias_i) ** exponent_i
9df421ed   tangwang   基于eval框架开始调参
108
      for es / rerank / fine / text / knn terms respectively.
814e352b   tangwang   乘法公式配置化
109
110
      """
  
9df421ed   tangwang   基于eval框架开始调参
111
112
      es_bias: float = 0.1
      es_exponent: float = 0.0
814e352b   tangwang   乘法公式配置化
113
114
115
116
      rerank_bias: float = 0.00001
      rerank_exponent: float = 1.0
      text_bias: float = 0.1
      text_exponent: float = 0.35
24edc208   tangwang   修改_extract_combin...
117
118
119
      knn_text_weight: float = 1.0
      knn_image_weight: float = 1.0
      knn_tie_breaker: float = 0.0
814e352b   tangwang   乘法公式配置化
120
121
      knn_bias: float = 0.6
      knn_exponent: float = 0.2
8c8b9d84   tangwang   ES 拉取 coarse_rank...
122
123
      fine_bias: float = 0.00001
      fine_exponent: float = 1.0
de98daa3   tangwang   多模态召回优化
124
125
      #: 翻译子句 named query 分数相对原文 base_query 的权重(加权后再与原文做 dismax 融合)
      text_translation_weight: float = 0.8
8c8b9d84   tangwang   ES 拉取 coarse_rank...
126
127
128
129
130
131
  
  
  @dataclass(frozen=True)
  class CoarseRankFusionConfig:
      """
      Multiplicative fusion without model score:
9df421ed   tangwang   基于eval框架开始调参
132
133
      fused = (max(es, 0) + es_bias) ** es_exponent
              * (max(text, 0) + text_bias) ** text_exponent
8c8b9d84   tangwang   ES 拉取 coarse_rank...
134
135
136
              * (max(knn, 0) + knn_bias) ** knn_exponent
      """
  
9df421ed   tangwang   基于eval框架开始调参
137
138
      es_bias: float = 0.1
      es_exponent: float = 0.0
8c8b9d84   tangwang   ES 拉取 coarse_rank...
139
140
141
142
143
144
145
      text_bias: float = 0.1
      text_exponent: float = 0.35
      knn_text_weight: float = 1.0
      knn_image_weight: float = 1.0
      knn_tie_breaker: float = 0.0
      knn_bias: float = 0.6
      knn_exponent: float = 0.2
de98daa3   tangwang   多模态召回优化
146
147
      #: 翻译子句 named query 分数相对原文 base_query 的权重(加权后再与原文做 dismax 融合)
      text_translation_weight: float = 0.8
8c8b9d84   tangwang   ES 拉取 coarse_rank...
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
  
  
  @dataclass(frozen=True)
  class CoarseRankConfig:
      """Search-time coarse ranking configuration."""
  
      enabled: bool = True
      input_window: int = 700
      output_window: int = 240
      fusion: CoarseRankFusionConfig = field(default_factory=CoarseRankFusionConfig)
  
  
  @dataclass(frozen=True)
  class FineRankConfig:
      """Search-time lightweight rerank configuration."""
  
      enabled: bool = True
      input_window: int = 240
      output_window: int = 80
      timeout_sec: float = 10.0
      rerank_query_template: str = "{query}"
      rerank_doc_template: str = "{title}"
      service_profile: Optional[str] = "fine"
814e352b   tangwang   乘法公式配置化
171
172
173
  
  
  @dataclass(frozen=True)
86d8358b   tangwang   config optimize
174
175
176
177
178
179
180
181
182
183
  class RerankConfig:
      """Search-time rerank configuration."""
  
      enabled: bool = True
      rerank_window: int = 384
      timeout_sec: float = 15.0
      weight_es: float = 0.4
      weight_ai: float = 0.6
      rerank_query_template: str = "{query}"
      rerank_doc_template: str = "{title}"
8c8b9d84   tangwang   ES 拉取 coarse_rank...
184
      service_profile: Optional[str] = None
814e352b   tangwang   乘法公式配置化
185
      fusion: RerankFusionConfig = field(default_factory=RerankFusionConfig)
86d8358b   tangwang   config optimize
186
187
188
189
190
191
192
193
194
195
  
  
  @dataclass(frozen=True)
  class SearchConfig:
      """Search behavior configuration shared by backend and indexer."""
  
      field_boosts: Dict[str, float]
      indexes: List[IndexConfig] = field(default_factory=list)
      query_config: QueryConfig = field(default_factory=QueryConfig)
      function_score: FunctionScoreConfig = field(default_factory=FunctionScoreConfig)
8c8b9d84   tangwang   ES 拉取 coarse_rank...
196
197
      coarse_rank: CoarseRankConfig = field(default_factory=CoarseRankConfig)
      fine_rank: FineRankConfig = field(default_factory=FineRankConfig)
86d8358b   tangwang   config optimize
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
      rerank: RerankConfig = field(default_factory=RerankConfig)
      spu_config: SPUConfig = field(default_factory=SPUConfig)
      es_index_name: str = "search_products"
      es_settings: Dict[str, Any] = field(default_factory=dict)
  
  
  @dataclass(frozen=True)
  class TranslationServiceConfig:
      """Translator service configuration."""
  
      endpoint: str
      timeout_sec: float
      default_model: str
      default_scene: str
      cache: Dict[str, Any]
      capabilities: Dict[str, Dict[str, Any]]
  
      def as_dict(self) -> Dict[str, Any]:
          return {
              "service_url": self.endpoint,
              "timeout_sec": self.timeout_sec,
              "default_model": self.default_model,
              "default_scene": self.default_scene,
              "cache": self.cache,
              "capabilities": self.capabilities,
          }
  
  
  @dataclass(frozen=True)
  class EmbeddingServiceConfig:
      """Embedding service configuration."""
  
      provider: str
      providers: Dict[str, Any]
      backend: str
      backends: Dict[str, Dict[str, Any]]
      image_backend: str
      image_backends: Dict[str, Dict[str, Any]]
  
      def get_provider_config(self) -> Dict[str, Any]:
          return dict(self.providers.get(self.provider, {}) or {})
  
      def get_backend_config(self) -> Dict[str, Any]:
          return dict(self.backends.get(self.backend, {}) or {})
  
      def get_image_backend_config(self) -> Dict[str, Any]:
          return dict(self.image_backends.get(self.image_backend, {}) or {})
  
  
  @dataclass(frozen=True)
daa2690b   tangwang   漏斗参数调优&呈现优化
248
249
250
251
252
253
254
255
256
257
258
259
  class RerankServiceInstanceConfig:
      """One named reranker service instance."""
  
      host: str = "0.0.0.0"
      port: int = 6007
      backend: str = "qwen3_vllm_score"
      runtime_dir: Optional[str] = None
      base_url: Optional[str] = None
      service_url: Optional[str] = None
  
  
  @dataclass(frozen=True)
86d8358b   tangwang   config optimize
260
261
262
263
264
  class RerankServiceConfig:
      """Reranker service configuration."""
  
      provider: str
      providers: Dict[str, Any]
daa2690b   tangwang   漏斗参数调优&呈现优化
265
266
      default_instance: str
      instances: Dict[str, RerankServiceInstanceConfig]
86d8358b   tangwang   config optimize
267
268
269
270
271
272
      backends: Dict[str, Dict[str, Any]]
      request: Dict[str, Any]
  
      def get_provider_config(self) -> Dict[str, Any]:
          return dict(self.providers.get(self.provider, {}) or {})
  
daa2690b   tangwang   漏斗参数调优&呈现优化
273
274
275
276
277
278
279
280
281
282
      def get_instance(self, name: Optional[str] = None) -> RerankServiceInstanceConfig:
          instance_name = str(name or self.default_instance).strip() or self.default_instance
          instance = self.instances.get(instance_name)
          if instance is None:
              raise KeyError(f"Unknown rerank service instance: {instance_name!r}")
          return instance
  
      def get_backend_config(self, name: Optional[str] = None) -> Dict[str, Any]:
          instance = self.get_instance(name)
          return dict(self.backends.get(instance.backend, {}) or {})
86d8358b   tangwang   config optimize
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
  
  
  @dataclass(frozen=True)
  class ServicesConfig:
      """All service-level configuration."""
  
      translation: TranslationServiceConfig
      embedding: EmbeddingServiceConfig
      rerank: RerankServiceConfig
  
  
  @dataclass(frozen=True)
  class TenantCatalogConfig:
      """Tenant catalog configuration."""
  
      default: Dict[str, Any]
      tenants: Dict[str, Dict[str, Any]]
  
      def get_raw(self) -> Dict[str, Any]:
          return {
              "default": dict(self.default),
              "tenants": {str(key): dict(value) for key, value in self.tenants.items()},
          }
  
  
  @dataclass(frozen=True)
  class ElasticsearchSettings:
      host: str = "http://localhost:9200"
      username: Optional[str] = None
      password: Optional[str] = None
  
  
  @dataclass(frozen=True)
  class RedisSettings:
      host: str = "localhost"
      port: int = 6479
      snapshot_db: int = 0
      password: Optional[str] = None
      socket_timeout: int = 1
      socket_connect_timeout: int = 1
      retry_on_timeout: bool = False
      cache_expire_days: int = 720
      embedding_cache_prefix: str = "embedding"
86d8358b   tangwang   config optimize
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
  
  
  @dataclass(frozen=True)
  class DatabaseSettings:
      host: Optional[str] = None
      port: int = 3306
      database: Optional[str] = None
      username: Optional[str] = None
      password: Optional[str] = None
  
  
  @dataclass(frozen=True)
  class SecretsConfig:
      dashscope_api_key: Optional[str] = None
      deepl_auth_key: Optional[str] = None
  
  
  @dataclass(frozen=True)
  class InfrastructureConfig:
      elasticsearch: ElasticsearchSettings
      redis: RedisSettings
      database: DatabaseSettings
      secrets: SecretsConfig
  
  
  @dataclass(frozen=True)
86d8358b   tangwang   config optimize
352
353
354
355
356
357
358
  class RuntimeConfig:
      environment: str = "prod"
      index_namespace: str = ""
      api_host: str = "0.0.0.0"
      api_port: int = 6002
      indexer_host: str = "0.0.0.0"
      indexer_port: int = 6004
fe80e80e   tangwang   fix host config
359
      embedding_host: str = "0.0.0.0"
86d8358b   tangwang   config optimize
360
361
362
      embedding_port: int = 6005
      embedding_text_port: int = 6005
      embedding_image_port: int = 6008
fe80e80e   tangwang   fix host config
363
      translator_host: str = "0.0.0.0"
86d8358b   tangwang   config optimize
364
      translator_port: int = 6006
fe80e80e   tangwang   fix host config
365
      reranker_host: str = "0.0.0.0"
86d8358b   tangwang   config optimize
366
367
368
369
370
371
372
373
374
      reranker_port: int = 6007
  
  
  @dataclass(frozen=True)
  class AssetsConfig:
      query_rewrite_dictionary_path: Path
  
  
  @dataclass(frozen=True)
331861d5   tangwang   eval框架配置化
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
  class SearchEvaluationConfig:
      """Offline / web UI search evaluation (YAML: ``search_evaluation``)."""
  
      artifact_root: Path
      queries_file: Path
      eval_log_dir: Path
      default_tenant_id: str
      search_base_url: str
      web_host: str
      web_port: int
      judge_model: str
      judge_enable_thinking: bool
      judge_dashscope_batch: bool
      intent_model: str
      intent_enable_thinking: bool
      judge_batch_completion_window: str
      judge_batch_poll_interval_sec: float
      build_search_depth: int
      build_rerank_depth: int
      annotate_search_top_k: int
      annotate_rerank_top_k: int
      batch_top_k: int
      audit_top_k: int
      audit_limit_suspicious: int
      default_language: str
      search_recall_top_k: int
      rerank_high_threshold: float
      rerank_high_skip_count: int
      rebuild_llm_batch_size: int
      rebuild_min_llm_batches: int
      rebuild_max_llm_batches: int
      rebuild_irrelevant_stop_ratio: float
      rebuild_irrel_low_combined_stop_ratio: float
      rebuild_irrelevant_stop_streak: int
  
  
  @dataclass(frozen=True)
86d8358b   tangwang   config optimize
412
413
414
415
416
417
418
419
420
421
422
423
  class ConfigMetadata:
      loaded_files: Tuple[str, ...]
      config_hash: str
      deprecated_keys: Tuple[str, ...] = field(default_factory=tuple)
  
  
  @dataclass(frozen=True)
  class AppConfig:
      """Root application configuration."""
  
      runtime: RuntimeConfig
      infrastructure: InfrastructureConfig
86d8358b   tangwang   config optimize
424
425
426
427
      search: SearchConfig
      services: ServicesConfig
      tenants: TenantCatalogConfig
      assets: AssetsConfig
331861d5   tangwang   eval框架配置化
428
      search_evaluation: SearchEvaluationConfig
86d8358b   tangwang   config optimize
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
      metadata: ConfigMetadata
  
      def sanitized_dict(self) -> Dict[str, Any]:
          data = asdict(self)
          data["infrastructure"]["elasticsearch"]["password"] = _mask_secret(
              data["infrastructure"]["elasticsearch"].get("password")
          )
          data["infrastructure"]["database"]["password"] = _mask_secret(
              data["infrastructure"]["database"].get("password")
          )
          data["infrastructure"]["redis"]["password"] = _mask_secret(
              data["infrastructure"]["redis"].get("password")
          )
          data["infrastructure"]["secrets"]["dashscope_api_key"] = _mask_secret(
              data["infrastructure"]["secrets"].get("dashscope_api_key")
          )
          data["infrastructure"]["secrets"]["deepl_auth_key"] = _mask_secret(
              data["infrastructure"]["secrets"].get("deepl_auth_key")
          )
          return data
  
  
  def _mask_secret(value: Optional[str]) -> Optional[str]:
      if not value:
          return value
      return "***"