Skip to content

Commit 7174d9d

Browse files
Leon-Algoclaude
andauthored
feat: add opt-in event_entity KG builder, event_join partitioner and event extraction profiles (#195)
- kg_method: event_entity builds an EVENT star graph via a profile-driven extractor (graphgen/templates/event_profile_loader.py, fail-closed validation, SHA-256 lineage); ships generic_event.v1 only, no default profile. - partition.method: event_join groups events sharing participants; require_same_anchor defaults to False so the shipped profile works out of the box. - External profile paths are passed through to the builder; membership edges carry event_member and role from extraction. - Example config and docs under examples/generate/generate_event_qa/. - Default light_rag + ECE route is untouched. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
1 parent 5689674 commit 7174d9d

19 files changed

Lines changed: 1328 additions & 1 deletion

File tree

‎MANIFEST.in‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@ include requirements.txt
22
include graphgen/configs/*.yaml
33
recursive-include graphgen/configs *.yaml
44
recursive-include graphgen/templates/profiles *.json
5+
recursive-include graphgen/templates/event_profiles *
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Generate QAs from an Event-Entity Graph
2+
3+
An opt-in alternative to the default LightRAG entity/relation graph. Instead of
4+
entities linked by relations, `build_kg` extracts **events** and their
5+
**participants** into a star graph (one event node, one membership edge per
6+
participant), and `partition` groups events that share participants into
7+
communities. Any generator can then run on those communities; this example
8+
uses `multi_hop`.
9+
10+
```bash
11+
bash examples/generate/generate_event_qa/generate_event.sh
12+
```
13+
14+
## Configuration
15+
16+
`build_kg` node:
17+
18+
| key | value |
19+
|-----------------|--------------------------------------------------------------------------------------------------------------------------------------------------------|
20+
| `kg_method` | `event_entity` (default `light_rag`, which ignores the keys below) |
21+
| `event_profile` | **required**. Built-in profile id (`generic_event.v1`) or a filesystem path to a `profile.json`; the prompt file named in the manifest must sit next to it |
22+
23+
`partition` node, `method: event_join`, `method_params`:
24+
25+
| key | default | meaning |
26+
|----------------------------|---------|-----------------------------------------------------------------------------------------------------------|
27+
| `max_events_per_community` | 6 | stop growing a community after this many events |
28+
| `min_events_per_community` | 1 | drop communities with fewer events |
29+
| `max_tokens_per_community` | 4096 | token budget per community (event `length` attributes) |
30+
| `require_same_anchor` | false | only join events whose `anchor` attribute matches; set `true` only with a profile whose `anchor.required` is true |
31+
| `event_entity_type` | `EVENT` | node `entity_type` that marks event nodes; must match `graph.event_entity_type` of the profile |
32+
| `anchor_attribute` | `anchor`| node attribute holding the anchor |
33+
34+
## Event profiles
35+
36+
A profile is a directory with `profile.json` and the prompt file it names
37+
(see `graphgen/templates/event_profiles/generic_event.v1/`). The manifest
38+
declares the allowed participant `entity_types`, an optional `anchor` regex
39+
(e.g. a ticket or project id that every event must mention), whether numbers
40+
in extracted events must appear in the source chunk (`grounding`), and the
41+
`entity_type` used for event nodes. Validation is fail-closed: a malformed
42+
manifest or prompt raises at service construction time, and there is no
43+
default profile.
44+
45+
To use your own profile, copy the built-in directory, edit it, and point
46+
`event_profile` at the new `profile.json` path.
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
global_params:
2+
working_dir: cache
3+
graph_backend: kuzu # graph database backend, support: kuzu, networkx
4+
kv_backend: rocksdb # key-value store backend, support: rocksdb, json_kv
5+
6+
nodes:
7+
- id: read
8+
op_name: read
9+
type: source
10+
dependencies: []
11+
params:
12+
input_path:
13+
- examples/input_examples/csv_demo.csv
14+
15+
- id: chunk
16+
op_name: chunk
17+
type: map_batch
18+
dependencies:
19+
- read
20+
execution_params:
21+
replicas: 4
22+
params:
23+
chunk_size: 1024
24+
chunk_overlap: 100
25+
26+
- id: build_kg
27+
op_name: build_kg
28+
type: map_batch
29+
dependencies:
30+
- chunk
31+
execution_params:
32+
replicas: 1
33+
batch_size: 128
34+
params:
35+
kg_method: event_entity # opt-in; default is light_rag
36+
# built-in profile id, or a path to a profile.json (prompt.txt next to it)
37+
event_profile: generic_event.v1
38+
39+
- id: partition
40+
op_name: partition
41+
type: aggregate
42+
dependencies:
43+
- build_kg
44+
params:
45+
method: event_join
46+
method_params:
47+
max_events_per_community: 6
48+
min_events_per_community: 1
49+
max_tokens_per_community: 4096
50+
# set to true only with a profile whose anchor.required is true
51+
require_same_anchor: false
52+
53+
- id: generate
54+
op_name: generate
55+
type: map_batch
56+
dependencies:
57+
- partition
58+
execution_params:
59+
replicas: 1
60+
batch_size: 128
61+
save_output: true
62+
params:
63+
method: multi_hop
64+
data_format: ChatML
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
python3 -m graphgen.run \
2+
--config_file examples/generate/generate_event_qa/event_config.yaml

‎graphgen/models/__init__.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,14 @@
2323
TrueFalseGenerator,
2424
VQAGenerator,
2525
)
26-
from .kg_builder import LightRAGKGBuilder, MMKGBuilder
26+
from .kg_builder import EventEntityKGBuilder, LightRAGKGBuilder, MMKGBuilder
2727
from .llm import HTTPClient, OllamaClient, OpenAIClient
2828
from .partitioner import (
2929
AnchorBFSPartitioner,
3030
BFSPartitioner,
3131
DFSPartitioner,
3232
ECEPartitioner,
33+
EventJoinPartitioner,
3334
LeidenPartitioner,
3435
QuintuplePartitioner,
3536
TriplePartitioner,
@@ -80,6 +81,7 @@
8081
# KG Builder
8182
"LightRAGKGBuilder": ".kg_builder",
8283
"MMKGBuilder": ".kg_builder",
84+
"EventEntityKGBuilder": ".kg_builder",
8385
# LLM
8486
"HTTPClient": ".llm",
8587
"OllamaClient": ".llm",
@@ -89,6 +91,7 @@
8991
"BFSPartitioner": ".partitioner",
9092
"DFSPartitioner": ".partitioner",
9193
"ECEPartitioner": ".partitioner",
94+
"EventJoinPartitioner": ".partitioner",
9295
"LeidenPartitioner": ".partitioner",
9396
"TriplePartitioner": ".partitioner",
9497
"QuintuplePartitioner": ".partitioner",
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
1+
from .event_entity_kg_builder import EventEntityKGBuilder
12
from .light_rag_kg_builder import LightRAGKGBuilder
23
from .mm_kg_builder import MMKGBuilder
Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
"""Pure stdlib contracts for profile-driven event extraction.
2+
3+
All domain policy (entity types, anchor rules, number grounding) is supplied
4+
explicitly by a validated event extraction profile; no implicit defaults.
5+
"""
6+
7+
from __future__ import annotations
8+
9+
import hashlib
10+
import json
11+
import re
12+
from collections import defaultdict
13+
from typing import Optional
14+
15+
_ALLOWED_EVENT_KEYS = {"title", "content", "entities", "is_valid"}
16+
_ALLOWED_ENTITY_KEYS = {"type", "name", "description"}
17+
_NUMBER_RE = re.compile(
18+
r"(?<![A-Za-z0-9_.])[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?%?(?![A-Za-z0-9_.])"
19+
)
20+
21+
22+
def numbers_in(text: str) -> set[str]:
23+
"""Return numeric strings using the deterministic grounding policy."""
24+
return set(_NUMBER_RE.findall(text or ""))
25+
26+
27+
def event_anchor(content: str, pattern: Optional[str]) -> Optional[str]:
28+
"""Return the first configured anchor match, if any."""
29+
if pattern is None:
30+
return None
31+
match = re.compile(pattern).search(content or "")
32+
if match is None:
33+
return None
34+
if match.lastindex:
35+
return match.group(1)
36+
return match.group(0)
37+
38+
39+
def event_node_name(anchor: Optional[str], title: str, content: str, *, legacy: bool = False) -> str:
40+
"""Create a deterministic event node ID."""
41+
if legacy:
42+
digest = hashlib.sha256(f"{anchor}\n{title}\n{content}".encode("utf-8")).hexdigest()[:12]
43+
return f"event:{anchor}:{digest}"
44+
digest = hashlib.sha256(
45+
json.dumps([anchor, title, content], ensure_ascii=False, separators=(",", ":")).encode("utf-8")
46+
).hexdigest()[:20]
47+
return f"event:{digest}"
48+
49+
50+
def _parse_entity(entity: dict, allowed_types: set[str], dropped: dict) -> Optional[dict]:
51+
"""Validate a single participant entity under the profile policy."""
52+
if not isinstance(entity, dict):
53+
dropped["entity_not_object"] += 1
54+
return None
55+
if set(entity) - _ALLOWED_ENTITY_KEYS:
56+
dropped["entity_extra_fields"] += 1
57+
return None
58+
etype = str(entity.get("type") or "").strip().upper()
59+
ename = str(entity.get("name") or "").strip()
60+
edesc = str(entity.get("description") or "").strip()
61+
if not etype or not ename or not edesc:
62+
dropped["entity_blank"] += 1
63+
return None
64+
if etype not in allowed_types:
65+
dropped["entity_type_unknown"] += 1
66+
return None
67+
return {"type": etype, "name": ename, "description": edesc}
68+
69+
70+
def _event_rejection_reason(
71+
item: dict,
72+
*,
73+
evidence_numbers: set[str],
74+
anchor_pattern: Optional[str],
75+
anchor_required: bool,
76+
number_grounding: bool,
77+
) -> Optional[str]:
78+
"""Return the first contract violation of an event item, if any."""
79+
if not isinstance(item, dict):
80+
return "event_not_object"
81+
title = str(item.get("title") or "").strip()
82+
content = str(item.get("content") or "").strip()
83+
violations = (
84+
("event_extra_fields", bool(set(item) - _ALLOWED_EVENT_KEYS)),
85+
("event_blank", not title or not content),
86+
("event_self_invalid", item.get("is_valid") is False),
87+
("event_missing_anchor", anchor_required and event_anchor(content, anchor_pattern) is None),
88+
(
89+
"event_number_not_grounded",
90+
number_grounding
91+
and any(number not in evidence_numbers for number in numbers_in(f"{title} {content}")),
92+
),
93+
("event_entities_invalid", not isinstance(item.get("entities") or [], list)),
94+
)
95+
for reason, violated in violations:
96+
if violated:
97+
return reason
98+
return None
99+
100+
101+
def _parse_event(
102+
item: dict,
103+
*,
104+
evidence_numbers: set[str],
105+
allowed_types: set[str],
106+
anchor_pattern: Optional[str],
107+
anchor_required: bool,
108+
number_grounding: bool,
109+
dropped: dict,
110+
) -> Optional[dict]:
111+
"""Validate a single extracted event under the profile policy."""
112+
reason = _event_rejection_reason(
113+
item,
114+
evidence_numbers=evidence_numbers,
115+
anchor_pattern=anchor_pattern,
116+
anchor_required=anchor_required,
117+
number_grounding=number_grounding,
118+
)
119+
if reason:
120+
dropped[reason] += 1
121+
return None
122+
title = str(item.get("title") or "").strip()
123+
content = str(item.get("content") or "").strip()
124+
entities = [
125+
parsed
126+
for entity in item.get("entities") or []
127+
if (parsed := _parse_entity(entity, allowed_types, dropped)) is not None
128+
]
129+
return {
130+
"title": title,
131+
"content": content,
132+
"anchor": event_anchor(content, anchor_pattern),
133+
"entities": entities,
134+
}
135+
136+
137+
def parse_extraction_response(
138+
response: str,
139+
*,
140+
chunk_content: str,
141+
entity_types: list[dict],
142+
anchor_pattern: Optional[str] = None,
143+
anchor_required: bool = False,
144+
number_grounding: bool = True,
145+
) -> tuple[list[dict], dict[str, int]]:
146+
"""Parse the strict event response contract under an explicit profile policy.
147+
148+
:param response: raw LLM response
149+
:param chunk_content: source chunk text used for number grounding
150+
:param entity_types: allowed entity types from the event profile
151+
:param anchor_pattern: optional regex applied to the event content
152+
:param anchor_required: whether an event without an anchor is dropped
153+
:param number_grounding: whether numbers must appear in the chunk content
154+
:return: (valid_events, dropped_counters)
155+
"""
156+
dropped: dict[str, int] = defaultdict(int)
157+
text = (response or "").strip()
158+
if text.startswith("```"):
159+
text = text.strip("`")
160+
if text.startswith("json"):
161+
text = text[4:]
162+
text = text.strip()
163+
try:
164+
payload = json.loads(text)
165+
except json.JSONDecodeError:
166+
dropped["response_not_json"] += 1
167+
return [], dict(dropped)
168+
if not isinstance(payload, dict) or set(payload) != {"type", "data"}:
169+
dropped["response_contract_invalid"] += 1
170+
return [], dict(dropped)
171+
data = payload.get("data")
172+
if not isinstance(data, dict) or set(data) != {"items"} or not isinstance(data["items"], list):
173+
dropped["response_contract_invalid"] += 1
174+
return [], dict(dropped)
175+
176+
allowed_types = {str(item["type"]).strip().upper() for item in entity_types}
177+
evidence_numbers = numbers_in(chunk_content) if number_grounding else set()
178+
valid_events = [
179+
event
180+
for item in data["items"]
181+
if (
182+
event := _parse_event(
183+
item,
184+
evidence_numbers=evidence_numbers,
185+
allowed_types=allowed_types,
186+
anchor_pattern=anchor_pattern,
187+
anchor_required=anchor_required,
188+
number_grounding=number_grounding,
189+
dropped=dropped,
190+
)
191+
)
192+
is not None
193+
]
194+
return valid_events, dict(dropped)

0 commit comments

Comments
 (0)