KG2Code: Bridging Knowledge Graphs and Large Language Models via Executable Code for Question Answering

Yike Wu, Nan Hu, Guilin Qi, Guohui Xiao, Chen Jiang, Xinchun Zou, Yuchen Lu, Songlin Zhai, Yongrui Chen, Yuyang Zhang, Xiaoguang Li, Lifeng Shang, Jiaoyan Chen, Jeff Z. PanarXiv 2026

TL;DR

KG2Code introduces a novel paradigm for Knowledge Graph Question Answering (KGQA) by transforming graph subgraphs into executable Python code using the NetworkX library. By framing question answering as a code generation task, it leverages the powerful code-reasoning capabilities of modern Large Language Models (LLMs) to preserve graph topology and ensure strictly grounded, verifiable answers.

What Problem Does This Paper Address?

Integrating Knowledge Graphs (KGs) with Large Language Models (LLMs) is a powerful way to tackle knowledge-intensive tasks. However, existing Knowledge Graph Question Answering (KGQA) methods fall into three flawed paradigms:

  1. Retrieval-Augmented Generation (RAG) / Text-linearization: Flattens graph triples into text strings, which destroys structural connectivity and leads to hallucinations.
  2. Agent-based methods: Use multi-step text interactions to explore the graph, but the intermediate reasoning steps are rarely strictly grounded in the actual graph topology.
  3. SPARQL-based semantic parsing: Translates questions into formal database queries. While structurally sound, SPARQL has rigid syntactic constraints (a single typo breaks the query) and is highly dependent on specific graph schemas, limiting generalization.
Comparison of existing KG-enhanced LLM methods vs. KG2Code

The authors propose KG2Code to bridge this gap, treating code as the ultimate intermediate representation that preserves graph structure while remaining highly compatible with LLM pre-training.

Methods

The framework consists of two main steps: KG2Code (knowledge graph rewriting) and KG2Code-QA (code generation for question answering).

  • KG Rewriting: Instead of turning a retrieved subgraph into text sentences, KG2Code converts it into executable Python code using the NetworkX library. Entities become nodes (graph.add_node()) and relations become directed labeled edges (graph.add_edge()).
  • Code-Generation Reasoning: The question and the generated Python graph initialization code are fed into the LLM. The model is prompted to complete a function (def KGQA(question, graph):) by interleaving natural language comments (stating reasoning intent) with executable Python code blocks (performing graph traversals, filtering, and set operations).
  • Hybrid Answer Strategy: To obtain the final answer, the system attempts to execute the generated code block ("hard answer"). If the code execution fails due to a syntax or runtime error, it falls back to a "soft answer" parsed directly from the natural language comments generated by the LLM.

To train open-source models, the authors also built an automated pipeline that synthesized over 200,000 high-quality code-based KGQA training examples using template-based SPARQL queries and LLM question generation.

Illustration of the KG2Code-QA framework pipeline

Datasets

The authors evaluated their approach across four established KGQA benchmarks spanning two different underlying knowledge bases:

  • Wikidata-based: WikiWebQuestions (WWQ) and LC-QuAD 2.0 (filtered to 4,932 test questions).
  • Freebase-based (Cross-KG Transfer): WebQuestionsSP (WebQSP) and GrailQA. These were used strictly to test how well the model generalizes to entirely unseen graph schemas without any additional fine-tuning.

Key Insights and Ideas

  • Code as a Natural Interface: Modern LLMs undergo massive code-aware pre-training. Representing a graph as code aligns perfectly with these latent capabilities, making graph operations like neighborhood traversal or set intersections highly intuitive for the model.
  • The Power of ReAct-style Interleaving: Forcing the model to write a comment before a code block ensures logical consistency. The comments maintain the reasoning flexibility of natural language, while the code grounds those thoughts into strict, verifiable symbolic operations.
  • Drastically Lowering "No-Answer" Rates: Traditional SPARQL generation is fragile; minor schema mismatches result in zero returned answers. Python code is far more forgiving, allowing the model to implement custom filtering logic even if the underlying ontology is complex or unfamiliar.

Key Results

KG2Code-QA consistently outperformed RAG, agentic, and SPARQL baselines across multiple backbone architectures (Llama-3.1-8B, Qwen2.5-Coder-7B, and GPT-5-Mini).

  • Accuracy Boost: On the complex LC-QuAD 2.0 dataset using a Llama-3.1-8B backbone, KG2Code-QA achieved an Exact Match (EM) score of 74.78%, significantly outperforming CoT-Tuning (70.78%) and obliterating the SPARQL-SFT baseline (18.51%).
  • Robustness to Errors: KG2Code-QA dramatically reduced the "no-answer" rate. On LC-QuAD 2.0, SPARQL-SFT failed to return an answer 61.82% of the time, whereas KG2Code-QA dropped that failure rate to just 1.68% thanks to its hybrid hard/soft answer fallback mechanism.
  • Zero-Shot Generalization: When trained on Wikidata-derived code corpora and evaluated zero-shot on Freebase datasets (WebQSP and GrailQA), KG2Code-QA maintained top-tier performance, proving it learns generalized graph-processing logic rather than just memorizing schema names.

Limitations and Future Work

Despite its success, the authors highlighted a few key areas for improvement:

  • Upstream Retrieval Bottlenecks: Around 40% of the errors encountered were due to "subgraph retrieval issues"—meaning the initial retriever failed to capture the necessary entities or relations from the massive KG, leaving the code-generation module with incomplete data.
  • Model Capacity Demands: Scalability experiments revealed that the performance gains from 7B to 14B parameters are minor, but jump significantly when moving to 32B. This implies that graph-to-code reasoning places high demands on model capacity.
  • Future Directions: The authors plan to extend this method into a broader "Graph-RAG" framework capable of handling unstructured data sources (like text and tables) by first converting them into code-based graphs.

Summary updated

BibTeX
@misc{wu2026kg,
  author = {Yike Wu and Nan Hu and Guilin Qi and Guohui Xiao and Chen Jiang and Xinchun Zou and Yuchen Lu and Songlin Zhai and Yongrui Chen and Yuyang Zhang and Xiaoguang Li and Lifeng Shang and Jiaoyan Chen and Jeff Z. Pan},
  title = {{KG2Code: Bridging Knowledge Graphs and Large Language Models via Executable Code for Question Answering}},
  year = {2026},
  eprint = {2607.22652},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2607.22652},
}
Figure