arXiv:2607.22652cs.AI2026-07

将知识图谱转为可执行代码,让大模型更准回答知识问题。

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

论文配图:KG2Code: Bridging Knowledge Graphs and Large Language Models via Executable Code for Question Answering
图 1 · 摘自论文原文
  • 把知识图谱转成代码形式,保留结构语义并适配大模型预训练
  • 生成可验证的推理过程和代码,大幅减少幻觉错误
  • 支持零样本泛化,适合需要高可信度问答的场景

近期研究尝试将知识图谱(KG)与大语言模型(LLMs)结合,以提升其在知识密集型任务中的表现,尤其是知识图谱问答(KGQA)。现有方法主要通过检索增强生成(RAG)、代理式或SPARQL方式整合,但存在结构信息丢失、推理不忠实、灵活性与泛化性差等问题。本文提出KG2Code,一种将知识图谱转化为代码表示的新方法,既保留结构语义,又自然契合现代大模型对代码的预训练能力。基于此,进一步构建KG2Code-QA框架,将KGQA建模为代码生成任务,实现可验证的推理路径与可执行代码生成,显著降低幻觉影响。同时,设计自动化流程构建大规模高质量代码语料库,用于训练开源大模型进行KG2Code-QA。训练后模型可在零样本场景下完成知识图谱问答。大量实验表明,该方法显著优于现有增强型大模型方法,并展现出对未见知识图谱的强大泛化能力。代码与数据已公开于GitHub。

原文摘要 · Abstract (English)

Recent research has explored the integration of knowledge graphs (KGs) with large language models (LLMs) to enhance their performance on downstream knowledge-intensive tasks, particularly knowledge graph question answering (KGQA). Existing approaches primarily combine LLMs with KGs through retrieval-augmented generation (RAG)-based, agent-based, and SPARQL-based methods. Although these methods have achieved notable success, they still suffer from several limitations, including structural information loss, unfaithful reasoning, and limited flexibility and generalization. To address these challenges, this paper proposes KG2Code, a novel approach that transforms knowledge graphs into a code-based representation, preserving structural semantics while naturally aligning with the code-aware pretraining of modern LLMs. Based on KG2Code, KG2Code-QA is further introduced as a KGQA framework that formulates KGQA as a code generation task. This formulation enables the generation of verifiable reasoning traces and executable code, thereby substantially mitigating the impact of hallucinations. In addition, an automated pipeline is developed to construct a large-scale, high-quality code corpus for effectively training open-source LLMs on KG2Code-QA. After training, LLMs are able to perform KGQA in zero-shot scenarios. Extensive experiments demonstrate that the proposed approach significantly outperforms existing KG-enhanced LLM methods for KGQA, while exhibiting strong generalization to unseen KGs. The code and data are available at Github.

知识图谱大模型代码生成问答系统

Thank you to arXiv for use of its open access interoperability. PaperDance 不是 arXiv 官方产品;中文卡片由大模型生成,请以原文为准。