run-llama/llama_index · error · ValueError

kg_rel_map must be found in at least one Node.

Error message

kg_rel_map must be found in at least one Node.

What it means

KG table retrievers attach the graph context as node metadata under the key 'kg_rel_map'; _get_metadata_for_response scans the retrieved nodes for that key so the response synthesizer can cite the graph relations. If no retrieved node carries 'kg_rel_map' metadata, the method raises ValueError. This usually means retrieval produced no KG-augmented nodes (e.g. empty rel_map or custom nodes passed in).

Source

Thrown at llama-index-core/llama_index/core/indices/knowledge_graph/retrievers.py:391

            excluded_embed_metadata_keys=["kg_rel_map", "kg_rel_texts"],
            excluded_llm_metadata_keys=["kg_rel_map", "kg_rel_texts"],
        )
        # this node is constructed from rel_texts, give high confidence to avoid cutoff
        sorted_nodes_with_scores.append(
            NodeWithScore(node=rel_text_node, score=DEFAULT_NODE_SCORE)
        )

        return sorted_nodes_with_scores

    def _get_metadata_for_response(
        self, nodes: List[BaseNode]
    ) -> Optional[Dict[str, Any]]:
        """Get metadata for response."""
        for node in nodes:
            if node.metadata is None or "kg_rel_map" not in node.metadata:
                continue
            return node.metadata
        raise ValueError("kg_rel_map must be found in at least one Node.")


DEFAULT_SYNONYM_EXPAND_TEMPLATE = """
Generate synonyms or possible form of keywords up to {max_keywords} in total,
considering possible cases of capitalization, pluralization, common expressions, etc.
Provide all synonyms of keywords in comma-separated format: 'SYNONYMS: <keywords>'
Note, result should be in one-line with only one 'SYNONYMS: ' prefix
----
KEYWORDS: {question}
----
"""

DEFAULT_SYNONYM_EXPAND_PROMPT = PromptTemplate(
    DEFAULT_SYNONYM_EXPAND_TEMPLATE,
    prompt_type=PromptType.QUERY_KEYWORD_EXTRACT,
)

View on GitHub (pinned to afd0fef371)

Solutions

  1. Check the graph actually contains relevant entities: inspect kg_index.index_struct.table and the rel_map the store returns for the query keywords; broaden max_keywords or add more triplets/documents.
  2. Verify the graph store connection and get_rel_map(subjs, depth, limit) settings so relation maps are actually returned.
  3. If empty results are expected, subclass or wrap the retriever to return a 'no context' response instead of letting the metadata lookup raise.

Example fix

# before
# query with keywords that match no KG entities -> ValueError
response = kg_index.as_query_engine().query("unrelated question")

# after
# ensure the graph has content covering the query domain
kg_index = KnowledgeGraphIndex.from_documents(docs, max_triplets_per_node=10)
response = kg_index.as_query_engine().query("question about graph entities")
Defensive patterns

Strategy: validation

Validate before calling

# before querying, confirm the KG has entities matching typical queries
subjs = list(kg_index.index_struct.table.keys())
rel_map = kg_index._graph_store.get_rel_map(subjs=subjs, depth=1, limit=5)
assert rel_map, "KG store returned no relations; retriever will fail on kg_rel_map lookup"

Try / catch

try:
    response = kg_engine.query(q)
except ValueError as e:
    if "kg_rel_map" in str(e):
        response = llm.complete(q)  # no KG context available; answer directly
    else:
        raise

Prevention

When it happens

Trigger: KGTableRetriever._get_metadata_for_response invoked when every retrieved node lacks the 'kg_rel_map' metadata key — typically the knowledge graph store returned an empty rel_map (no entities matched the query keywords) or nodes were synthesized/injected without KG metadata; also triggered by querying a KG index built with include_embeddings but a graph store that returns no relations.

Common situations: Querying a sparse or freshly built KnowledgeGraphIndex whose triplets share no keywords with the query; using a graph store (e.g. Nebula/Neo4j remote) that returns an empty rel_map due to connection or depth settings; custom retriever subclasses that override retrieval but reuse this metadata hook.

Related errors


AI-assisted analysis of run-llama/llama_index@afd0fef371 (2026-08-15). Data as JSON: /api/errors/e2c81b4f0c219122. Report an issue: GitHub.