SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2602.05728 · 2026

CompactRAG: Reducing LLM Calls and Token Overhead in Multi-Hop Question Answering

Hao Yang, Lin Yang, Wei Wei, Zhiyu Yang, Xupeng Zhang, Yunjie Zhang

arXiv · PDF · Open in the Atlas

Code that ran

9 of 10 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (0 of them constructed an object rather than computing a result; 1 honoured the contract we drafted, 4 violated it and 0 have no contract verdict; 4 failures of our instrument; 1 no recorded run), measured 2026-11-22; bodies inline only under a permissive licence as GitHub detects it. Not a reproduction of the paper's results.

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/2602.05728.json · badge: /api/ran/2602.05728.svg

Each repository's role is a label: a classifier's output recorded on the link, or, where no role is recorded, what the Papers with Code archive marked. The line under it names its basis. Neither says who wrote the code.

RepositoryRoleRan
How-Young-X/CompactRAG canonical (classifier label)
classifier basis: census
9 ran · 1 no recorded run
FunctionStatusWhere it lives
coverage_check Ran
ran; our contract draft was wrong, not the code
How-Young-X/CompactRAG/src/core/ReadingCorpus.py
code served (permissive licence) · get_code("0098b487d7dc437e")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned list, ndim 1, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch

torch.manual_seed(0)

# Define required_phrases - a list of strings that should be searched for
required_phrases = ["machine learning", "neural networks", "deep learning"]

# Define qa_list - a list of dicts, each with a 'question' key
qa_list = [
    {"question": "What is machine learning?", "answer": "Machine learning is..."},
    {"question": "How do neural networks work?", "answer": "Neural networks..."},
    {"question": "What about data science?", "answer": "Data science involves..."}
]

ARGS = {
    "required_phrases": required_phrases,
    "qa_list": qa_list
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type list, ndim 1, dtype family float — a list output has no array shape of its own; none is stated
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
exact_match_score Ran
ran, violated the contract we drafted
How-Young-X/CompactRAG/src/metrics/F1Eval.py
code served (permissive licence) · get_code("1a90d2afb9055e47")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned bool, ndim 0, dtype family float, shape () as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn
import re
import string

def normalize_answer(s):
    """Lower text and remove punctuation, articles and extra whitespace."""
    if s is None:
        return ''

    def remove_articles(text):
        regex = re.compile('\\b(a|an|the)\\b', re.IGNORECASE)
        return re.sub(regex, ' ', text)

    def white_space_fix(text):
        return ' '.join(text.split())

    def remove_punc(text):
        exclude = set(string.punctuation)
        return ''.join((ch for ch in text if ch not in exclude))

    def lower(text):
        return text.lower()
    return white_space_fix(remove_articles(remove_punc(lower(s))))

def exact_match_score(prediction, ground_truth):
    """Calculate exact match score between prediction and ground truth."""
    if prediction is None:
        prediction = ''
    if ground_truth is None:
        ground_truth = ''
    return normalize_answer(prediction) == normalize_answer(ground_truth)

ARGS = {
    'prediction': 'The quick brown fox',
    'ground_truth': 'the quick brown fox',
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type bool, ndim 0, dtype family float, shape () — shape () as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
extract_json Ran
ran; our contract draft was wrong, not the code
How-Young-X/CompactRAG/src/core/AskCorpus.py
code served (permissive licence) · get_code("9f0a5786975dd602")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned list, ndim 1, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import json
import logging
import re

logging.basicConfig(level=logging.INFO)

# Test case 1: Valid JSON in code block
text_with_code_block = """
Here are the questions and answers:
json
[
  {"question": "What is Python?", "answer": "Python is a programming language."},
  {"question": "What is a function?", "answer": "A function is a reusable block of code."}
]

"""

# Test case 2: Valid JSON array without code block
text_with_array = """
[
  {"question": "What is machine learning?", "answer": "Machine learning is a subset of AI."},
  {"question": "What is deep learning?", "answer": "Deep learning uses neural networks."}
]
"""

# Test case 3: Valid JSON with prefix and suffix
text_with_prefix = """Here are the generated questions and answers:
[
  {"question": "What is NLP?", "answer": "NLP is natural language processing."}
]

"""

# Test case 4: Valid JSON with multiple items
text_multiple_items = """

[
  {"question": "Q1?", "answer": "A1"},
  {"question": "Q2?", "answer": "A2"},
  {"question": "Q3?", "answer": "A3"}
]

"""

# Test case 5: Valid JSON with nested structure (still valid QA pairs)
text_simple = '[{"question": "test?", "answer": "test answer"}]'

ARGS = {
    "text": text_with_code_block
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
none outside the standard library — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type list, ndim 1, dtype family float — a list output has no array shape of its own; none is stated
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
f1_score Ran
ran, honoured the contract we drafted
How-Young-X/CompactRAG/src/metrics/F1Eval.py
code served (permissive licence) · get_code("a4de989b76f916f5")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned float, ndim 0, dtype family float, shape () as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import re
import string
from collections import Counter

def normalize_answer(s):
    """Lower text and remove punctuation, articles and extra whitespace."""
    if s is None:
        return ''

    def remove_articles(text):
        regex = re.compile('\\b(a|an|the)\\b', re.IGNORECASE)
        return re.sub(regex, ' ', text)

    def white_space_fix(text):
        return ' '.join(text.split())

    def remove_punc(text):
        exclude = set(string.punctuation)
        return ''.join((ch for ch in text if ch not in exclude))

    def lower(text):
        return text.lower()
    return white_space_fix(remove_articles(remove_punc(lower(s))))

def f1_score(prediction, ground_truth):
    """Calculate F1 score between prediction and ground truth."""
    if prediction is None:
        prediction = ''
    if ground_truth is None:
        ground_truth = ''
    prediction_tokens = normalize_answer(prediction).split()
    ground_truth_tokens = normalize_answer(ground_truth).split()
    if len(prediction_tokens) == 0 and len(ground_truth_tokens) == 0:
        return 1.0
    if len(prediction_tokens) == 0 or len(ground_truth_tokens) == 0:
        return 0.0
    common = Counter(prediction_tokens) & Counter(ground_truth_tokens)
    num_same = sum(common.values())
    if num_same == 0:
        return 0.0
    precision = 1.0 * num_same / len(prediction_tokens)
    recall = 1.0 * num_same / len(ground_truth_tokens)
    f1 = 2 * precision * recall / (precision + recall)
    return f1

ARGS = {
    'prediction': 'The quick brown fox jumps over the lazy dog',
    'ground_truth': 'A quick brown fox jumps over a lazy dog'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
none outside the standard library — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type float, ndim 0, dtype family float, shape () — shape () as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
format_entities_for_prompt Ran
ran; our contract draft was wrong, not the code
How-Young-X/CompactRAG/ReadingCorpus2.py
code served (permissive licence) · get_code("9f6e3af87078a74c")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned str. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import numpy as np

torch.manual_seed(0)

# Construct the extracted_info dictionary with all required fields
extracted_info = {
    'entities': [
        {'text': 'Apple Inc.', 'label': 'ORGANIZATION'},
        {'text': 'Steve Jobs', 'label': 'PERSON'},
        {'text': 'California', 'label': 'LOCATION'},
    ],
    'noun_chunks': [
        'Apple Inc.',
        'Steve Jobs',
        'technology company',
        'personal computers',
        'innovation',
        'digital revolution',
    ],
    'relations': [
        {
            'subject': 'Steve Jobs',
            'predicate': 'founded',
            'object': 'Apple Inc.'
        },
        {
            'subject': 'Apple Inc.',
            'predicate': 'located_in',
            'object': 'California'
        },
        {
            'subject': 'Apple Inc.',
            'predicate': 'produces',
            'object': 'personal computers'
        },
    ]
}

ARGS = {
    'extracted_info': extracted_info
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type str — a str output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a str output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
has_bad_word Ran
ran, violated the contract we drafted
How-Young-X/CompactRAG/ReadingCorpus2.py
code served (permissive licence) · get_code("95285251b374c3d2")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned bool, ndim 0, dtype family float, shape () as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import re

BAD_WORDS = ['it', 'this', 'that', 'they', 'those', 'these', 'the film', 'this film', 'the movie', 'this movie', 'the book', 'this book', 'the article', 'this article', 'the passage', 'this passage', 'the story', 'this story', 'the director', 'this director', 'the person', 'this person', 'the place', 'this place', 'the country', 'this country', 'the year', 'this year', '^it ', '^this ', '^that ', '^he ', '^she ', '^his ', '^her ']

BAD_WORDS_LOWER = [w.lower() for w in BAD_WORDS]

def has_bad_word(s):
    s_low = s.lower()
    for pattern in BAD_WORDS_LOWER:
        if pattern.startswith('^'):
            regex_pattern = pattern[1:]
            if re.match(regex_pattern, s_low):
                return True
        elif pattern in s_low:
            return True
    return False

ARGS = {
    "s": "The film is great"
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
none outside the standard library — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type bool, ndim 0, dtype family float, shape () — shape () as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
has_bad_word Ran
ran, violated the contract we drafted
How-Young-X/CompactRAG/src/core/ReadingCorpus.py
code served (permissive licence) · get_code("7c8c64b457f3afd4")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned bool, ndim 0, dtype family float, shape () as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import numpy as np

torch.manual_seed(0)

# The function has_bad_word takes a single parameter 's' which is a string
# It converts it to lowercase and checks if any bad word is contained in it
# So we need to provide a string argument

ARGS = {
    's': 'This is a test string with the film in it'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type bool, ndim 0, dtype family float, shape () — shape () as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
normalize_answer Ran
ran; our contract draft was wrong, not the code
How-Young-X/CompactRAG/src/metrics/F1Eval.py
code served (permissive licence) · get_code("26a63699755bd04e")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned str. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import re
import string

torch_imported = False
try:
    import torch
    torch_imported = True
except ImportError:
    pass

# The function normalize_answer takes a single parameter: s (a string)
# It processes the string by lowercasing, removing punctuation, removing articles, and fixing whitespace
# No complex objects needed - just a string argument

ARGS = {
    "s": "The Quick Brown Fox! A lazy dog, and the rest."
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type str — a str output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a str output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
validate_qa_pairs Ran
ran, violated the contract we drafted
How-Young-X/CompactRAG/src/core/AskCorpus.py
code served (permissive licence) · get_code("911346ae88836fbc")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned bool, ndim 0, dtype family float, shape () as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch

# Valid QA pairs - should return True
valid_qa_list = [
    {
        'question': 'What is Python?',
        'answer': 'Python is a programming language.'
    },
    {
        'question': 'How do you create a list?',
        'answer': 'You use square brackets like [1, 2, 3].'
    }
]

ARGS = {
    'qa_list': valid_qa_list
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type bool, ndim 0, dtype family float, shape () — shape () as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
extract_entities_and_relations Not yet run
unverified (harvested, no recorded run)
How-Young-X/CompactRAG/ReadingCorpus2.py
code served (permissive licence) · get_code("dabb9e40f05a14a2")
How it ran

no invocation recorded.

Also present in other papers' code

Of 10 samples lifted from this paper's linked repositories, 10 carry a function identity and 0 do not. Of the 10 distinct functions with an identity, 0 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 0 the same month, 0 later) and 10 are only here among the 52,977 papers whose code Syntology holds (as of 2026-09-26).

Only here means: among the 52,977 papers whose code Syntology holds (51,887 with lifted samples, 1,090 through their assemblies only), as of 2026-09-26, no other paper's lifted samples or current assembly bricks contain an identical function body after normalisation.

Presence, not direction: an identical function body in two papers' repositories does not say who wrote it, which came from which, or that either paper's method rests on it. Matching is exact after normalisation, so a renamed or edited function is not matched. Dates are when papers appeared, not when code was written. Only .py files the harvester lifted are covered; notebooks are not read. A new-style arXiv id YYMM.NNNN dates a paper to the month 20YY-MM; otherwise Paper.year dates it to the year; otherwise it is undated. Dates are when the paper appeared, not when the code was written. Read 2026-11-22.

Repositories linked to this paper

Some links come from the archived Papers with Code dataset (CC BY-SA 4.0): attribution and licence.

Abstract

Retrieval-augmented generation (RAG) has become a key paradigm for knowledge-intensive question answering. However, existing multi-hop RAG systems remain inefficient, as they alternate between retrieval and reasoning at each step, resulting in repeated LLM calls, high token consumption, and unstable entity grounding across hops. We propose CompactRAG, a simple yet effective framework that decouples offline corpus restructuring from online reasoning. In the offline stage, an LLM reads the corpus once and converts it into an atomic QA knowledge base, which represents knowledge as minimal, fine-grained question-answer pairs. In the online stage, complex queries are decomposed and carefully rewritten to preserve entity consistency, and are resolved through dense retrieval followed by RoBERTa-based answer extraction. Notably, during inference, the LLM is invoked only twice in total-once for sub-question decomposition and once for final answer synthesis-regardless of the number of reasoning hops. Experiments on HotpotQA, 2WikiMultiHopQA, and MuSiQue demonstrate that CompactRAG achieves competitive accuracy while substantially reducing token consumption compared to iterative RAG baselines, highlighting a cost-efficient and practical approach to multi-hop reasoning over large knowledge corpora. The implementation is available at https://github.com/How-Young-X/CompactRAG.

For agents

The same record, over MCP at https://syntology.ai/mcp:

get_harvested_code_for_paper("2602.05728")
get_code_for_paper("2602.05728")
have("2602.05728")

The run record, dated, one paper per request, free:

curl https://syntology.ai/api/ran/2602.05728.json

A badge for a README (the split and the date, never a ratio):

[![Syntology run record](https://syntology.ai/api/ran/2602.05728.svg)](https://syntology.ai/paper/2602.05728)

Connect an agent — have() is free.