graph_engine
zocrates.rag.graph_engine ¶
Evidence-Gated Hybrid & Curated Paper Relations Engine.
Discovers, verifies, and transactionally persists high-confidence undirected edges between academic papers in conversion_meta.db without LLMs or cross-encoders: 1. Sub-millisecond 5-feature statistical keywords and Zotero user tags. 2. Chunk-level hybrid search (Chroma dense + SQLite FTS5 BM25 with RRF). 3. The Canonical Evidence Gate: - Method == 'hybrid' (dense semantic + BM25 keyword corroboration), OR - High single-chunk semantic similarity >= 0.65, OR - Multi-chunk dense cohesion (>= 2 chunks and max_sem >= 0.58). 4. Exponential diminishing-returns score rescaling to intuitive [0.50, 0.99]. 5. Ground truth ingestion (human_curated, shared_tags, human_curated_and_hybrid_search). 6. Undirected edge symmetrization with canonical max score and ON CONFLICT semantics.
DEFAULT_GRAPH_RELATIONS
module-attribute
¶
DEFAULT_GRAPH_RELATIONS = {'enabled': True, 'strategy': 'hybrid_corroborated', 'candidate_pool_size': 50, 'min_hybrid_score': 0.015, 'score_tau': 0.1, 'shared_tags_score': 0.7, 'include_human_curated': True, 'include_shared_tags': True, 'min_shared_tags': 2, 'sync_bundle_files': True}
GENERIC_TAGS
module-attribute
¶
build_search_query ¶
Build a deduplicated, high-signal search query combining title, keywords, and tags.
Guarantees high-IDF lexical coverage without repeating words or bloating the query.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
title
|
str
|
Document title. |
required |
keywords
|
list[str]
|
Extracted statistical keywords. |
required |
tags
|
list[str] | None
|
Optional user or automatic Zotero tags. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Deduplicated space-separated query string capped at 35 terms. |
Source code in zocrates/rag/keyword_extractor.py
check_evidence_gate ¶
Check if retrieved chunks satisfy the canonical Evidence Gate.
A candidate paper connection clears the Evidence Gate if: agg_score >= min_hybrid_score AND at least one of: 1. Any chunk has retrieval_method == 'hybrid' (lexical BM25 + dense cos-sim >= 0.50). 2. High single-chunk semantic confidence: max_sem_score >= 0.65. 3. Multi-chunk dense cohesion: len(chunks) >= 2 and max_sem_score >= 0.58.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunks
|
list[Any]
|
List of retrieved SearchResult chunks or dict equivalents. |
required |
min_hybrid_score
|
float
|
Minimum aggregated raw RRF score threshold. |
0.015
|
Returns:
| Type | Description |
|---|---|
tuple[bool, float, float, set[str]]
|
Tuple of (is_valid, agg_score, max_sem_score, retrieval_methods). |
Source code in zocrates/rag/graph_engine.py
evaluate_and_persist_edges ¶
Evaluate and persist relations for an item using hybrid search and ground truth.
- Looks up item_key metadata, keywords, and tags.
- Builds high-signal search query via build_search_query.
- Runs syncer.store.search isolating body chunks and excluding Chunk 0 frontmatter.
- Groups candidates by parent key, strictly excluding own parent key and sibling attachments.
- Clears candidates through the canonical Evidence Gate and exponential score rescaling.
- Persists edges transactionally with ON CONFLICT max score and undirected symmetrization.
- Syncs manual links and shared user tags if enabled.
- If sync_bundle_files is True, regenerates item_relations.md for item_key and all connected neighbors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item_key
|
str
|
Unique Zotero attachment or item key. |
required |
syncer
|
Any
|
Active LibrarySyncer instance with vector store and database. |
required |
sync_bundle_files
|
bool
|
If True, regenerates item_relations.md on disk. |
True
|
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
List of all verified relation dictionaries for item_key. |
Source code in zocrates/rag/graph_engine.py
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 | |
extract_statistical_keywords ¶
Pure-Python 5-feature statistical keyphrase extractor (RAKE + YAKE principles).
Extracts high-precision compound keyphrases in < 0.2 ms on CPU using: 1. Co-occurrence degree / frequency ratio. 2. Casing & acronym multipliers (1.8x ALL_CAPS, 1.3x proper nouns). 3. Title positional boost (2.0x). 4. Sentence spread log-multiplier. 5. Length normalization favoring 2-3 word technical noun phrases.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
title
|
str
|
Document title. |
required |
text
|
str
|
Text to extract from (e.g. structural digest or abstract). |
required |
max_keywords
|
int
|
Maximum number of keywords to return. |
6
|
Returns:
| Type | Description |
|---|---|
list[str]
|
List of extracted keyphrase strings. |
Source code in zocrates/rag/keyword_extractor.py
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 | |
extract_structural_digest ¶
Extract lead abstract/intro plus topical H1/H2/H3 section headers.
Filters out standard academic IMRAD boilerplate headers so only substantive topical section headings are retained alongside lead text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
doc_text
|
str
|
Full document markdown string. |
required |
max_lead
|
int
|
Maximum character length for lead prose. |
2000
|
Returns:
| Type | Description |
|---|---|
str
|
Structural digest string combining lead text and topical section headers. |
Source code in zocrates/rag/keyword_extractor.py
get_corpus_dir ¶
Return (and create if needed) the document corpus directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zotero_data_dir
|
Path
|
Root Zotero data directory. |
required |
Returns:
| Type | Description |
|---|---|
Path
|
Path to |
Source code in zocrates/config.py
get_graph_relations_config ¶
Return the graph relations configuration dict from zocrates_config.json merged with defaults.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zotero_data_dir
|
Path | str | None
|
Path to the Zotero data directory. |
None
|
cfg
|
dict[str, Any] | None
|
Optional in-memory config dict. If provided, bypasses disk read. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dict containing graph relations parameters. |
Source code in zocrates/config.py
get_item_tags ¶
Retrieve user and automatic tags for an item from zotero.sqlite.
Excludes generic workflow tags (e.g. 'read', 'unread', 'to-read', 'favorite'). If item is an attachment, also resolves tags from its parent item.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zotero_dir
|
Path | str
|
Path to the root Zotero data directory. |
required |
item_id
|
int | None
|
Optional integer itemID in zotero.sqlite. |
None
|
item_key
|
str | None
|
Optional string key in zotero.sqlite (items.key). |
None
|
tag_type
|
int | None
|
Optional integer tag type filter (0 = user/manual tag, 1 = automatic tag). If None (default), returns all tag types. |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
List of non-generic tag name strings. |
Source code in zocrates/rag/keyword_extractor.py
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 | |
rescale_hybrid_score ¶
Rescale raw aggregated RRF score to [0.50, 0.99] using exponential diminishing returns.
Formula
score = round(0.50 + 0.49 * (1.0 - exp(-(raw_rrf_score - min_hybrid_score) / score_tau)), 2)
Clamped strictly to [0.50, 0.99].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw_rrf_score
|
float
|
Aggregated raw Reciprocal Rank Fusion score. |
required |
min_hybrid_score
|
float
|
Minimum raw score threshold to qualify. |
0.015
|
score_tau
|
float
|
Exponential decay constant governing progression. |
0.1
|
Returns:
| Type | Description |
|---|---|
float
|
Rescaled confidence score in [0.50, 0.99] rounded to 2 decimals. |
Source code in zocrates/rag/graph_engine.py
sync_manual_relations ¶
Read itemRelations from zotero.sqlite and persist human_curated edges.
If a manual link matches an existing hybrid_search edge, promotes it to human_curated_and_hybrid_search with score 1.0 while preserving underlying evidence. Otherwise, inserts human_curated with score 1.0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conn
|
Connection
|
Open SQLite connection to conversion_meta.db. |
required |
zotero_dir
|
Path
|
Root Zotero data directory containing zotero.sqlite. |
required |
target_key
|
str | None
|
Optional filter to restrict sync to relations involving this key. |
None
|
Returns:
| Type | Description |
|---|---|
int
|
Number of manual edges processed and persisted. |
Source code in zocrates/rag/graph_engine.py
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 | |
sync_shared_tags ¶
Check for shared user tags (type=0) and persist shared_tags edges.
Requires at least min_shared_tags (default: 2) distinctive non-generic user tags.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conn
|
Connection
|
Open SQLite connection to conversion_meta.db. |
required |
zotero_dir
|
Path
|
Root Zotero data directory containing zotero.sqlite. |
required |
min_shared_tags
|
int
|
Minimum count of shared distinctive tags required. |
2
|
target_key
|
str | None
|
Optional filter to restrict comparison to this item key. |
None
|
score
|
float | None
|
Optional score override (defaults to config shared_tags_score or 0.70). |
None
|
Returns:
| Type | Description |
|---|---|
int
|
Number of shared_tags edges created. |
Source code in zocrates/rag/graph_engine.py
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 | |
upsert_edge ¶
upsert_edge(conn, source_key, target_key, score, relation_type, match_evidence=None, symmetrize=True)
Insert or update an edge in SQLite item_relations with max-score semantics.
Always enforces undirected edge symmetrization by persisting both (A, B) and (B, A) with the canonical max score when symmetrize is True.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conn
|
Connection
|
Open SQLite connection to conversion_meta.db. |
required |
source_key
|
str
|
Source item or attachment key. |
required |
target_key
|
str
|
Target item or attachment key. |
required |
score
|
float
|
Edge confidence score in [0.50, 1.0]. |
required |
relation_type
|
str
|
Relation category ('human_curated_and_hybrid_search', 'human_curated', 'hybrid_search', or 'shared_tags'). |
required |
match_evidence
|
str | None
|
Optional JSON evidence debug summary string. |
None
|
symmetrize
|
bool
|
If True, writes both directional rows with canonical max score. |
True
|