目录
摘要
根据《SymAgent: A Neural-Symbolic Self-Learning Agent Framework for Complex Reasoning over Knowledge Graphs》(《SymAgent:一种用于知识图谱复杂推理的神经符号自学习Agent框架》)论文思路,简单复现代码,以实现SymAgent中的Agent-Planner和Agent-Executor模块。Agent-Planner利用大语言模型的归纳推理能力从知识图谱中提取符号规则,指导高效的问题分解。 Agent-Executor自主调用预定义的动作工具,以整合知识图谱和外部文档中的信息,解决知识图谱不完整的问题。还实现了其中的自学习框架,包含在线探索和离线迭代策略更新阶段,使代理能够自动合成推理轨迹并提升性能。
abstract
According to the paper idea of "SymAgent: A Neural-Symbolic Self-Learning Agent Framework for Complex Reasoning over Knowledge Graphs", the simple reproduction of modern code, Implement the Agent-Planner and Agent-Executor modules in SymAgent. Agent-Planner uses the inductive reasoning ability of large language models to extract symbolic rules from the knowledge graph to guide efficient problem decomposition. Agent-Executor autonomously invokes predefined action tools to integrate information from the knowledge graph and external documents to solve the problem of incomplete knowledge graph. It also implements a self-learning framework, including online exploration and offline iterative policy update phases, which enables agents to automatically synthesize inference trajectories and improve performance.
0 SymAgent整体结构
SymAgent为一个结合知识图谱(KGs)和 LLMs 来自主解决复杂推理任务的框架,包括:
- Agent-Planner:它从 KG 中提取符号规则来分解问题并规划推理步骤;
- Agent-Executor:它从反思和环境反馈中综合见解来回答问题;
- 自学习框架:为了解决标注推理数据的缺乏问题,引入了一个通过自主交互进行协同改进的自学习框架。
SymAgent整体架构如下图所示:
- (a)SymAgent中的规划器,它从知识图谱(KG)中推导出符号规则来指导推理;
- (b)SymAgent中的执行器,它进行自动动作调用以获取答案;
- (c)用于迭代增强代理的自学习框架;

1 导入模块和配置日志
导入必要的库:requests, json, socket, re, wikipedia, neo4j, deque, time, logging;配置日志记录器,记录INFO级别及以上的日志:
import requests
import json
import socket
import re
import wikipedia
from neo4j import GraphDatabase
from collections import deque
import time
import logging
# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger("SymAgent")
2 Agent-Planner
AgentPlanner用于根据问题从知识图谱中提取符号规则,规划推理路径:
class AgentPlanner:
def __init__(self, llm_client, kg_client):
self.llm_client = llm_client
self.kg_client = kg_client
self.max_planning_depth = 3
logger.info("AgentPlanner初始化完成")
def plan_reasoning_path(self, question, context=None):
"""
规划推理路径:从KG中提取符号规则
返回:推理路径(action序列)和初始思考
"""
logger.info(f"开始规划: {question}")
# 1. 提取问题中的实体
entities = self._extract_entities(question)
logger.info(f"提取的实体: {entities}")
# 2. 查询KG中的相关规则
kg_rules = self._query_kg_rules(entities)
logger.info(f"找到的KG规则: {len(kg_rules)}条")
# 3. 使用LLM生成推理计划
thought, plan = self._generate_reasoning_plan(question, kg_rules, context)
logger.info(f"生成的推理计划: {len(plan)}个步骤")
return thought, plan
def _extract_entities(self, question):
"""使用LLM提取问题中的实体"""
prompt = [
{
"role": "system",
"content": (
"你是一个实体提取器。从用户问题中识别所有命名实体和关键概念。"
"返回JSON格式: {\"entities\": [\"实体1\", \"实体2\", ...]}"
)
},
{"role": "user", "content": question}
]
response = self.llm_client.send_message(prompt)
logger.debug(f"实体提取响应: {response}")
try:
return json.loads(response).get("entities", [])
except json.JSONDecodeError:
logger.warning(f"实体提取响应不是有效JSON: {response}")
# 尝试从原始响应中提取实体
entities = re.findall(r'"([^"]+)"', response)
return entities if entities else []
except Exception as e:
logger.error(f"实体提取失败: {str(e)}")
return []
def _query_kg_rules(self, entities):
"""从KG查询与实体相关的规则"""
rules = []
if not entities:
return rules
for entity in entities:
# 查询直接关联的规则
direct_query = """
MATCH (e1:Entity)-[r]->(e2)
WHERE e1.name = $entity OR e2.name = $entity
RETURN e1.name AS source, type(r) AS relation, e2.name AS target
"""
direct_rules = self.kg_client.run_query(direct_query, {"entity": entity})
rules.extend(direct_rules)
# 查询间接关联的规则(2跳)
indirect_query = """
MATCH (e1:Entity)-[r1]->(
246



被折叠的 条评论
为什么被折叠?



