context.py
4.71 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
"""按 token 预算装配上下文。
v1 的做法是 `edges[:80]` / `evidence[:12]` —— 直接数组切片,而且切之前根本没排序。
在 `门店`(度 110)这种枢纽节点上,一跳就有上百条边,前 80 条纯粹是 networkx
的遍历顺序,等于给大模型喂随机三元组。
这里改成:先按相关度排序,再在 实体/关系/原文/主题摘要 四类之间按比例分配
token 预算,每类内部按排名逐条装入直到用完额度。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from ..core.llm import count_tokens, truncate_to_tokens
DEFAULT_RATIO = (0.25, 0.30, 0.40, 0.05) # 实体 / 关系 / 原文 / 社区报告
def parse_ratio(raw: str) -> tuple[float, float, float, float]:
try:
parts = [float(x) for x in (raw or "").split(",")]
if len(parts) != 4 or sum(parts) <= 0:
raise ValueError
total = sum(parts)
return tuple(p / total for p in parts) # type: ignore[return-value]
except Exception:
return DEFAULT_RATIO
@dataclass
class ContextBundle:
entities: list[dict] = field(default_factory=list)
relations: list[dict] = field(default_factory=list)
chunks: list[dict] = field(default_factory=list)
communities: list[dict] = field(default_factory=list)
text: str = ""
used_tokens: int = 0
dropped: dict = field(default_factory=dict)
def _fill(items: list[dict], render, budget: int) -> tuple[list[str], list[dict], int]:
"""按顺序装入,直到超预算。返回 (渲染行, 实际装入的条目, 用掉的 token)。"""
lines, kept, used = [], [], 0
for it in items:
line = render(it)
cost = count_tokens(line)
if used + cost > budget:
continue # 跳过这条继续试下一条:短条目还有机会挤进来
lines.append(line)
kept.append(it)
used += cost
return lines, kept, used
def _entity_line(e: dict) -> str:
desc = (e.get("description") or "").strip()
alias = "、".join(e.get("aliases") or [])
head = f"- {e.get('label', e.get('id', ''))}({e.get('type', '其他')}"
if alias:
head += f",别名:{alias}"
head += ")"
return head + (f":{desc}" if desc else "")
def _relation_line(r: dict) -> str:
desc = (r.get("description") or "").strip()
occ = r.get("occurrence", 1)
line = f"- {r.get('source', '')} —[{r.get('relation', '关联')}]→ {r.get('target', '')}"
if occ and int(occ) > 1:
line += f"({occ} 处佐证)"
return line + (f":{desc}" if desc else "")
def _chunk_line(c: dict, per_chunk_tokens: int) -> str:
head = c.get("heading") or "正文"
body = truncate_to_tokens(c.get("text", ""), per_chunk_tokens)
return f"[{c.get('id', '')}]【{head}】\n{body}"
def _community_line(c: dict) -> str:
return f"- 【{c.get('title', '')}】{c.get('summary', '')}"
def build_context(entities: list[dict], relations: list[dict], chunks: list[dict],
communities: list[dict], budget: int,
ratio: tuple[float, float, float, float] = DEFAULT_RATIO) -> ContextBundle:
b_ent = int(budget * ratio[0])
b_rel = int(budget * ratio[1])
b_chunk = int(budget * ratio[2])
b_comm = int(budget * ratio[3])
ent_lines, ent_kept, ent_used = _fill(entities, _entity_line, b_ent)
rel_lines, rel_kept, rel_used = _fill(relations, _relation_line, b_rel)
comm_lines, comm_kept, comm_used = _fill(communities, _community_line, b_comm)
# 没用完的额度让给原文 —— 原文是最终作答的依据,能多给就多给
spare = (b_ent - ent_used) + (b_rel - rel_used) + (b_comm - comm_used)
b_chunk += max(0, spare)
per_chunk = max(150, b_chunk // max(1, min(len(chunks), 12)))
chunk_lines, chunk_kept, chunk_used = _fill(
chunks, lambda c: _chunk_line(c, per_chunk), b_chunk)
parts = []
if ent_lines:
parts.append("【相关实体】\n" + "\n".join(ent_lines))
if rel_lines:
parts.append("【子图关系】\n" + "\n".join(rel_lines))
if comm_lines:
parts.append("【主题摘要】\n" + "\n".join(comm_lines))
if chunk_lines:
parts.append("【原文证据】(方括号内是可引用的 chunk_id)\n" + "\n\n".join(chunk_lines))
text = "\n\n".join(parts)
return ContextBundle(
entities=ent_kept, relations=rel_kept, chunks=chunk_kept, communities=comm_kept,
text=text, used_tokens=ent_used + rel_used + chunk_used + comm_used,
dropped={"entities": len(entities) - len(ent_kept),
"relations": len(relations) - len(rel_kept),
"chunks": len(chunks) - len(chunk_kept),
"communities": len(communities) - len(comm_kept)})