ingest_contract.py
8.32 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
from __future__ import annotations
import functools
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import yaml
CONTRACT_START = "<!-- INGEST_CONTRACT_START -->"
CONTRACT_END = "<!-- INGEST_CONTRACT_END -->"
# #5: Planner 每个 page 必须包含的字段
_PLANNER_PAGE_REQUIRED = ("type", "slug", "file_path", "title")
@dataclass(frozen=True)
class IngestContract:
schema_version: str
required_fields: tuple[str, ...]
canonical_types: dict[str, dict[str, Any]]
type_aliases: dict[str, str]
source_tracked_exclude: tuple[str, ...]
list_merge_fields: tuple[str, ...]
business_categories: tuple[str, ...]
vehicle_brands: tuple[str, ...]
ecosystem_names: tuple[str, ...]
dim_defaults: dict[str, str] # #9: Planner 维度兜底默认值
prompt_text: str
def _default_schema_path() -> Path:
return Path(__file__).resolve().parents[2] / "skills" / "llm-ingest" / "references" / "schema.md"
def _extract_contract_yaml(schema_text: str) -> str:
if CONTRACT_START not in schema_text or CONTRACT_END not in schema_text:
raise ValueError("schema.md 缺少 INGEST_CONTRACT 标记")
block = schema_text.split(CONTRACT_START, 1)[1].split(CONTRACT_END, 1)[0].strip()
if block.startswith("```"):
lines = block.splitlines()
if lines and lines[0].startswith("```"):
lines = lines[1:]
if lines and lines[-1].strip() == "```":
lines = lines[:-1]
block = "\n".join(lines).strip()
return block
def _flatten_vehicle_brands(raw: dict[str, Any]) -> tuple[str, ...]:
out: list[str] = []
for values in raw.values():
if not isinstance(values, list):
continue
for item in values:
if item and item not in out:
out.append(str(item))
return tuple(out)
def _build_type_aliases(canonical_types: dict[str, dict[str, Any]]) -> dict[str, str]:
aliases: dict[str, str] = {}
for canonical, spec in canonical_types.items():
aliases[canonical] = canonical
for alias in spec.get("aliases", []) or []:
aliases[str(alias)] = canonical
return aliases
@functools.lru_cache(maxsize=None)
def load_ingest_contract(schema_path: str | None = None) -> IngestContract:
path = Path(schema_path) if schema_path else _default_schema_path()
schema_text = path.read_text(encoding="utf-8")
raw = yaml.safe_load(_extract_contract_yaml(schema_text)) or {}
canonical_types = raw.get("canonical_types") or {}
if not canonical_types:
raise ValueError("schema contract 缺少 canonical_types")
# #9: 解析 dim_defaults,不存在时使用空字典(代码内有硬编码兜底)
dim_defaults_raw = raw.get("dim_defaults") or {}
dim_defaults = {str(k): str(v) for k, v in dim_defaults_raw.items()}
return IngestContract(
schema_version=str(raw.get("schema_version") or "").strip(),
required_fields=tuple(raw.get("required_fields") or ()),
canonical_types=canonical_types,
type_aliases=_build_type_aliases(canonical_types),
source_tracked_exclude=tuple(raw.get("source_tracked_exclude") or ()),
list_merge_fields=tuple(raw.get("list_merge_fields") or ()),
business_categories=tuple(raw.get("business_categories") or ()),
vehicle_brands=_flatten_vehicle_brands(raw.get("vehicle_brands") or {}),
ecosystem_names=tuple(raw.get("ecosystem_names") or ()),
dim_defaults=dim_defaults,
prompt_text=schema_text,
)
def current_schema_version() -> str:
return load_ingest_contract().schema_version
def canonicalize_type(raw_type: Any, contract: IngestContract | None = None) -> str:
value = str(raw_type or "").strip()
active_contract = contract or load_ingest_contract()
canonical = active_contract.type_aliases.get(value)
if not canonical:
raise ValueError(f"非法页面 type: {value}")
return canonical
def brand_baseline_set() -> set[str]:
return set(load_ingest_contract().vehicle_brands)
def ecosystem_name_set() -> set[str]:
return set(load_ingest_contract().ecosystem_names)
def contract_prompt_text() -> str:
return load_ingest_contract().prompt_text
def as_value_list(value: Any) -> list[Any]:
if isinstance(value, list):
return list(value)
if value in (None, ""):
return []
return [value]
def merge_field_sources(
target_md: dict[str, Any],
new_md: dict[str, Any],
canonical_source: str,
contract: IngestContract | None = None,
) -> None:
active_contract = contract or load_ingest_contract()
exclude = set(active_contract.source_tracked_exclude)
list_fields = set(active_contract.list_merge_fields)
fs = target_md.get("field_sources", {}) or {}
for key, value in new_md.items():
if key in exclude:
continue
new_values = as_value_list(value)
if not new_values:
continue
is_list = key in list_fields or isinstance(value, list) or isinstance(target_md.get(key), list)
fs.setdefault(key, {})
for item in new_values:
fs[key].setdefault(item, [])
if canonical_source not in fs[key][item]:
fs[key][item].append(canonical_source)
if is_list:
merged = as_value_list(target_md.get(key))
for item in new_values:
if item not in merged:
merged.append(item)
target_md[key] = merged
elif target_md.get(key) in (None, ""):
target_md[key] = new_values[0]
target_md["field_sources"] = fs
def recompute_after_source_removal(
md: dict[str, Any],
removed_source: str,
contract: IngestContract | None = None,
) -> None:
active_contract = contract or load_ingest_contract()
list_fields = set(active_contract.list_merge_fields)
fs = md.get("field_sources", {}) or {}
for field, srcmap in list(fs.items()):
for item in list(srcmap.keys()):
if removed_source in srcmap.get(item, []):
srcmap[item] = [s for s in srcmap[item] if s != removed_source]
if not srcmap.get(item):
srcmap.pop(item, None)
surviving = list(srcmap.keys())
if not surviving:
fs.pop(field, None)
md.pop(field, None)
elif isinstance(md.get(field), list) or field in list_fields:
md[field] = surviving
elif md.get(field) not in surviving:
md[field] = surviving[0]
if fs:
md["field_sources"] = fs
else:
md.pop("field_sources", None)
def validate_planner_output(plan_data: dict) -> tuple[dict, list[dict]]:
"""#5: 校验 Planner JSON 输出结构,返回 (global_dims, pages)。
格式不合规时抛 ValueError,让 Phase 1 直接终止或触发重试,
而非静默地将格式错误延迟到 Phase 2/3 才暴露。
"""
if not isinstance(plan_data, dict):
raise ValueError(
f"Planner 输出必须是 JSON 对象,实际类型为 {type(plan_data).__name__}"
)
pages = plan_data.get("pages")
if not isinstance(pages, list) or len(pages) == 0:
raise ValueError(
f"Planner 输出的 pages 必须是非空数组,"
f"实际类型为 {type(pages).__name__ if pages is not None else 'null'}"
)
for i, page in enumerate(pages):
if not isinstance(page, dict):
raise ValueError(
f"pages[{i}] 必须是 JSON 对象,实际类型为 {type(page).__name__}"
)
missing = [f for f in _PLANNER_PAGE_REQUIRED if not page.get(f)]
if missing:
raise ValueError(
f"pages[{i}](slug={page.get('slug', '?')})缺少必填字段: {missing}"
)
global_dims = plan_data.get("global_dims")
if global_dims is not None and not isinstance(global_dims, dict):
raise ValueError(
f"global_dims 必须是 JSON 对象或 null,实际类型为 {type(global_dims).__name__}"
)
# 必须包含至少 1 个 sources 类型页面
has_sources = any(
isinstance(p, dict) and str(p.get("type", "")).strip() in ("sources", "source")
for p in pages
)
if not has_sources:
raise ValueError(
"Planner 规划必须包含至少 1 个 type=sources 的来源摘要页"
)
return global_dims or {}, pages