SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2503.10150 · 2025

Retrieval-Augmented Generation with Hierarchical Knowledge

arXiv · PDF · Open in the Atlas

Code that ran

9 of 11 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; 0 honoured the contract we drafted, 0 violated it and 6 have no contract verdict; 3 failures of our instrument; 2 no recorded run), measured 2026-11-23; repository links from the Papers with Code archive attributed under CC BY-SA, no affiliation; 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/2503.10150.json · badge: /api/ran/2503.10150.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
hhy-huang/HiRAG canonical (classifier label)
classifier basis not recorded on the link
9 ran · 2 no recorded run
FunctionStatusWhere it lives
chunking_by_token_size Ran
ran on a synthesized input
hhy-huang/HiRAG/hirag/_op.py
code served (permissive licence) · get_code("bf9f7cd0dbc8f53e")
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 tiktoken

class MockTiktokenModel:
    def decode_batch(self, token_chunks):
        """Mock decode_batch that converts token lists to strings"""
        results = []
        for chunk in token_chunks:
            # Simple mock: convert tokens to strings
            decoded = " ".join(str(token) for token in chunk)
            results.append(decoded)
        return results

# Create mock tiktoken model
mock_tiktoken = MockTiktokenModel()

# Create sample token lists
tokens_list = [
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] * 150,  # 1500 tokens total
    [11, 12, 13, 14, 15] * 80,  # 400 tokens total
]

# Create doc keys matching the number of documents
doc_keys = ["doc_1", "doc_2"]

ARGS = {
    "tokens_list": tokens_list,
    "doc_keys": doc_keys,
    "tiktoken_model": mock_tiktoken,
    "overlap_token_size": 128,
    "max_token_size": 1024,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
tiktoken — 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
extract_first_complete_json Ran
ran; our contract draft was wrong, not the code
hhy-huang/HiRAG/hirag/_utils.py
code served (permissive licence) · get_code("e857b5e84512c1ad")
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 dict. 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 json
import logging

logger = logging.getLogger('HiRAG')

def extract_first_complete_json(s: str):
    """Extract the first complete JSON object from the string using a stack to track braces."""
    stack = []
    first_json_start = None
    for i, char in enumerate(s):
        if char == '{':
            stack.append(i)
            if first_json_start is None:
                first_json_start = i
        elif char == '}':
            if stack:
                start = stack.pop()
                if not stack:
                    first_json_str = s[first_json_start:i + 1]
                    try:
                        return json.loads(first_json_str.replace('\n', ''))
                    except json.JSONDecodeError as e:
                        logger.error(f'JSON decoding failed: {e}. Attempted string: {first_json_str[:50]}...')
                        return None
                    finally:
                        first_json_start = None
    logger.warning('No complete JSON object found in the input string.')
    return None


# Test case 1: Valid JSON in string
test_string_1 = 'Some text before {"key": "value", "number": 42} and text after'

# Test case 2: JSON with newlines
test_string_2 = 'Prefix {"name":\n"test",\n"id": 123} suffix'

# Test case 3: Nested JSON
test_string_3 = 'Start {"outer": {"inner": "data"}, "list": [1, 2, 3]} End'

# Test case 4: Empty JSON object
test_string_4 = 'Text before {} text after'

# Test case 5: JSON with special characters
test_string_5 = 'Text {"key": "value with \\"quotes\\"", "other": true} more text'

ARGS = {
    's': test_string_1
}
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 dict — a dict output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a dict 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
extract_values_from_json Ran
ran; our contract draft was wrong, not the code
hhy-huang/HiRAG/hirag/_utils.py
code served (permissive licence) · get_code("aa2e19784362624e")
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 dict. 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 logging
import re

logger = logging.getLogger('HiRAG')

def parse_value(value: str):
    """Convert a string value to its appropriate type (int, float, bool, None, or keep as string). Work as a more broad 'eval()'"""
    value = value.strip()
    if value == 'null':
        return None
    elif value == 'true':
        return True
    elif value == 'false':
        return False
    else:
        try:
            if '.' in value:
                return float(value)
            else:
                return int(value)
        except ValueError:
            return value.strip('"')

def extract_values_from_json(json_string, keys=['reasoning', 'answer', 'data'], allow_no_quotes=False):
    """Extract key values from a non-standard or malformed JSON string, handling nested objects."""
    extracted_values = {}
    regex_pattern = '(?P<key>"?\\w+"?)\\s*:\\s*(?P<value>{[^}]*}|".*?"|[^,}]+)'
    for match in re.finditer(regex_pattern, json_string, re.DOTALL):
        key = match.group('key').strip('"')
        value = match.group('value').strip()
        if value.startswith('{') and value.endswith('}'):
            extracted_values[key] = extract_values_from_json(value)
        else:
            extracted_values[key] = parse_value(value)
    if not extracted_values:
        logger.warning('No values could be extracted from the string.')
    return extracted_values


# Setup code
json_string_simple = '{"reasoning": "step by step", "answer": "42", "data": null}'

json_string_nested = '{"reasoning": "think", "answer": "true", "data": {"nested_key": "3.14"}}'

json_string_malformed = '{reasoning: "no quotes", answer: 100, data: false}'

ARGS = {
    'json_string': json_string_simple,
    'keys': ['reasoning', 'answer', 'data'],
    'allow_no_quotes': False
}
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 dict — a dict output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a dict 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
fit_gaussian_mixture Ran
ran on a synthesized input
hhy-huang/HiRAG/hirag/_cluster_utils.py
code served (permissive licence) · get_code("afc0b756a1dddef5")
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 numpy as np
from sklearn.mixture import GaussianMixture

# Create small embeddings array for testing
# GaussianMixture.fit() expects a 2D array of shape (n_samples, n_features)
np.random.seed(0)
embeddings = np.random.randn(10, 4).astype(np.float32)

ARGS = {
    'n_components': 2,
    'embeddings': embeddings,
    'random_state': 42
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, sklearn — 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
gpt_35_turbo_complete Ran
ran on a synthesized input
hhy-huang/HiRAG/hirag/_llm_backup.py
code served (permissive licence) · get_code("1baae13108795150")
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 coroutine. 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 os
import asyncio
from unittest.mock import Mock, AsyncMock, MagicMock, patch

# Set up environment variables
os.environ['OPENAI_API_KEY'] = 'test-key'
os.environ['OPENAI_MODEL'] = 'gpt-3.5-turbo'

# Define a minimal BaseKVStorage stand-in
class BaseKVStorage:
    async def get_by_id(self, key):
        return None
    
    async def upsert(self, data):
        pass
    
    async def index_done_callback(self):
        pass

# Mock the compute_args_hash function that's used in the code
def compute_args_hash(model, messages):
    return f"hash_{model}_{len(messages)}"

# Create minimal mock for OpenAI client response
class MockMessage:
    def __init__(self):
        self.content = "This is a test response from the model."

class MockChoice:
    def __init__(self):
        self.message = MockMessage()

class MockCompletion:
    def __init__(self):
        self.choices = [MockChoice()]

# Patch the necessary imports and set up mocks
async def mock_create(*args, **kwargs):
    return MockCompletion()

# Build arguments for gpt_35_turbo_complete
ARGS = {
    'prompt': 'What is the capital of France?',
    'system_prompt': 'You are a helpful assistant.',
    'history_messages': [
        {'role': 'user', 'content': 'Hello'},
        {'role': 'assistant', 'content': 'Hi there!'}
    ],
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
openai, tenacity — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type coroutine — a coroutine output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a coroutine 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
gpt_4o_complete Ran
ran on a synthesized input
hhy-huang/HiRAG/hirag/_llm_backup.py
code served (permissive licence) · get_code("bb6322730b978b13")
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 coroutine. 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 os
import asyncio
from unittest.mock import AsyncMock, MagicMock, patch

# Set up environment variables
os.environ['OPENAI_API_KEY'] = 'test-key-123'
os.environ['OPENAI_MODEL'] = 'gpt-4o'

# Mock BaseKVStorage class
class BaseKVStorage:
    async def get_by_id(self, key):
        return None
    
    async def upsert(self, data):
        pass
    
    async def index_done_callback(self):
        pass

# Mock compute_args_hash function
def compute_args_hash(model, messages):
    return f"hash_{model}_{len(messages)}"

# Patch the imports and functions at module level
import sys
from unittest.mock import AsyncMock

mock_response = MagicMock()
mock_response.choices = [MagicMock()]
mock_response.choices[0].message.content = "This is a test response from the model."

mock_client = AsyncMock()
mock_client.chat.completions.create = AsyncMock(return_value=mock_response)

# Define ARGS for gpt_4o_complete function
ARGS = {
    'prompt': 'What is 2+2?',
    'system_prompt': 'You are a helpful math assistant.',
    'history_messages': [
        {'role': 'user', 'content': 'Hello'},
        {'role': 'assistant', 'content': 'Hi there!'}
    ],
    'temperature': 0.7,
    'max_tokens': 100,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
openai, tenacity — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type coroutine — a coroutine output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a coroutine 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
make_path_idable Ran
ran on a synthesized input
hhy-huang/HiRAG/hirag/_storage/gdb_neo4j.py
code served (permissive licence) · get_code("d0c42489d83e2ac7")
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

ARGS = {
    "path": "module.layer.weight-decay/config.txt"
}
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
openai_complete_if_cache Ran
ran; our contract draft was wrong, not the code
hhy-huang/HiRAG/hirag/_llm_backup.py
code served (permissive licence) · get_code("34d148a5b4170144")
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 coroutine. 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 os
from unittest.mock import AsyncMock, MagicMock, patch
import asyncio

# Set up environment variables for OpenAI
os.environ['OPENAI_API_KEY'] = 'test-key-12345'
os.environ['OPENAI_API_BASE'] = 'http://localhost:8000/v1'

# Create a minimal BaseKVStorage stand-in class
class BaseKVStorage:
    async def get_by_id(self, key):
        return None
    
    async def upsert(self, data):
        pass
    
    async def index_done_callback(self):
        pass

# Create a mock for compute_args_hash function
def compute_args_hash(model, messages):
    import hashlib
    import json
    content = json.dumps({'model': model, 'messages': messages})
    return hashlib.md5(content.encode()).hexdigest()

# Create mock response object
class MockMessage:
    def __init__(self, content):
        self.content = content

class MockChoice:
    def __init__(self, content):
        self.message = MockMessage(content)

class MockResponse:
    def __init__(self, content):
        self.choices = [MockChoice(content)]

# Patch the OpenAI client and related functions
async def mock_create(**kwargs):
    return MockResponse("Test response from mock API")

# Set up patches
with patch('openai.AsyncOpenAI') as mock_openai_class:
    mock_client = AsyncMock()
    mock_client.chat.completions.create = mock_create
    mock_openai_class.return_value = mock_client

# Create test arguments
hashing_kv = BaseKVStorage()

ARGS = {
    'model': 'gpt-3.5-turbo',
    'prompt': 'What is the capital of France?',
    'system_prompt': 'You are a helpful assistant.',
    'history_messages': [
        {'role': 'user', 'content': 'Hello'},
        {'role': 'assistant', 'content': 'Hi there!'}
    ],
    'hashing_kv': hashing_kv,
    'temperature': 0.7,
    'max_tokens': 100
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
openai, tenacity — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type coroutine — a coroutine output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a coroutine 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
parse_value Ran
ran on a synthesized input
hhy-huang/HiRAG/hirag/_utils.py
code served (permissive licence) · get_code("da80c1396be65c39")
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 int, ndim 0, dtype family int, 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

ARGS = {
    "value": "42"
}
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 int, ndim 0, dtype family int, 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
chunking_by_seperators Not yet run
unverified (harvested, no recorded run)
hhy-huang/HiRAG/hirag/_op.py
code served (permissive licence) · get_code("39d3d26fb44efb3c")
How it ran

no invocation recorded.

get_chunks Not yet run
unverified (harvested, no recorded run)
hhy-huang/HiRAG/hirag/_op.py
code served (permissive licence) · get_code("903db7183e5ab2a8")
How it ran

no invocation recorded.

Also present in other papers' code

Of 11 samples lifted from this paper's linked repositories, 11 carry a function identity and 0 do not. Of the 11 distinct functions with an identity, 4 are also present in other papers whose code we hold (4 with at least one paper dated earlier, 0 the same month, 0 later) and 7 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.

FunctionAlso present inEarliest-datedOthers named
extract_first_complete_json 1 other paper
1 dated earlier
2404.16130 (2024-04)
From Local to Global: A Graph RAG Approach to Query-Focused Summarization
extract_values_from_json 1 other paper
1 dated earlier
2404.16130 (2024-04)
From Local to Global: A Graph RAG Approach to Query-Focused Summarization
openai_complete_if_cache 1 other paper
1 dated earlier
2404.16130 (2024-04)
From Local to Global: A Graph RAG Approach to Query-Focused Summarization
parse_value 1 other paper
1 dated earlier
2404.16130 (2024-04)
From Local to Global: A Graph RAG Approach to Query-Focused Summarization

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-23.

Repositories linked to this paper

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

Abstract

Graph-based Retrieval-Augmented Generation (RAG) methods have significantly enhanced the performance of large language models (LLMs) in domain-specific tasks. However, existing RAG methods do not adequately utilize the naturally inherent hierarchical knowledge in human cognition, which limits the capabilities of RAG systems. In this paper, we introduce a new RAG approach, called HiRAG, which utilizes hierarchical knowledge to enhance the semantic understanding and structure capturing capabilities of RAG systems in the indexing and retrieval processes. Our extensive experiments demonstrate that HiRAG achieves significant performance improvements over the state-of-the-art baseline methods.

For agents

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

get_harvested_code_for_paper("2503.10150")
get_code_for_paper("2503.10150")
have("2503.10150")

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

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

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

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

Connect an agent — have() is free.