包含 CodeAgent 前后端源码、SKILLS、MCP、demo 代码与工作区文档。 排除依赖缓存、运行数据、备份与二进制附件,规则见 .gitignore。 Co-Authored-By: Claude Code <[email protected]>
178 lines
6.3 KiB
Python
178 lines
6.3 KiB
Python
"""
|
||
知识图谱服务
|
||
============
|
||
|
||
【功能说明】
|
||
从文档中抽取实体与关系,构建轻量知识图谱,支持图查询。
|
||
对应功能 23:深度理解文档语义关系。
|
||
|
||
【技术选型理由】
|
||
1. 轻量图存储(SQLite 三元组),免 Neo4j 等外部依赖;
|
||
2. LLM 驱动的实体关系抽取;
|
||
3. 支持实体查询、关系查询、路径查询。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import logging
|
||
import sqlite3
|
||
import uuid
|
||
from datetime import datetime
|
||
from pathlib import Path
|
||
|
||
from app.models.model_router import get_model_for_task
|
||
from app.store.sqlite_util import open_connection
|
||
|
||
logger = logging.getLogger("agent.knowledge_graph")
|
||
|
||
|
||
class KnowledgeGraphStore:
|
||
"""知识图谱存储(三元组模型)"""
|
||
|
||
def __init__(self, db_path: Path) -> None:
|
||
self._db_path = Path(db_path)
|
||
self._init_schema()
|
||
|
||
def _conn(self):
|
||
"""
|
||
获取一个短连接(用完自动提交/回滚并关闭)。
|
||
|
||
【修复】原先只返回裸 sqlite3 连接、用完从不 close,连接泄漏到 GC
|
||
(Windows 文件锁 / 句柄增长)。改为委托 app.store.sqlite_util.open_connection,
|
||
提交/回滚语义不变,额外保证 close。
|
||
"""
|
||
return open_connection(self._db_path)
|
||
|
||
def _init_schema(self) -> None:
|
||
ddl = """
|
||
CREATE TABLE IF NOT EXISTS knowledge_triple (
|
||
id TEXT PRIMARY KEY,
|
||
subject TEXT NOT NULL,
|
||
predicate TEXT NOT NULL,
|
||
object TEXT NOT NULL,
|
||
source TEXT DEFAULT '',
|
||
confidence REAL DEFAULT 1.0,
|
||
created_at TEXT NOT NULL
|
||
);
|
||
CREATE INDEX IF NOT EXISTS idx_kg_subject ON knowledge_triple(subject);
|
||
CREATE INDEX IF NOT EXISTS idx_kg_object ON knowledge_triple(object);
|
||
"""
|
||
with self._conn() as conn:
|
||
conn.executescript(ddl)
|
||
conn.commit()
|
||
|
||
def add_triple(self, subject: str, predicate: str, obj: str, source: str = "", confidence: float = 1.0) -> str:
|
||
"""添加一个三元组。"""
|
||
triple_id = f"kg_{uuid.uuid4().hex[:8]}"
|
||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||
with self._conn() as conn:
|
||
conn.execute(
|
||
"INSERT INTO knowledge_triple (id, subject, predicate, object, source, confidence, created_at) VALUES (?,?,?,?,?,?,?)",
|
||
(triple_id, subject, predicate, obj, source, confidence, now),
|
||
)
|
||
conn.commit()
|
||
return triple_id
|
||
|
||
def query_by_subject(self, subject: str) -> list[dict]:
|
||
"""按主语查询关系。"""
|
||
with self._conn() as conn:
|
||
rows = conn.execute(
|
||
"SELECT * FROM knowledge_triple WHERE subject = ? ORDER BY confidence DESC",
|
||
(subject,),
|
||
).fetchall()
|
||
return [dict(r) for r in rows]
|
||
|
||
def query_by_object(self, obj: str) -> list[dict]:
|
||
"""按宾语查询关系。"""
|
||
with self._conn() as conn:
|
||
rows = conn.execute(
|
||
"SELECT * FROM knowledge_triple WHERE object = ? ORDER BY confidence DESC",
|
||
(obj,),
|
||
).fetchall()
|
||
return [dict(r) for r in rows]
|
||
|
||
def query_relation(self, predicate: str) -> list[dict]:
|
||
"""按关系查询。"""
|
||
with self._conn() as conn:
|
||
rows = conn.execute(
|
||
"SELECT * FROM knowledge_triple WHERE predicate LIKE ? ORDER BY confidence DESC",
|
||
(f"%{predicate}%",),
|
||
).fetchall()
|
||
return [dict(r) for r in rows]
|
||
|
||
def search_entities(self, keyword: str, limit: int = 20) -> list[dict]:
|
||
"""搜索实体(主语或宾语含关键词)。"""
|
||
with self._conn() as conn:
|
||
rows = conn.execute(
|
||
"""SELECT DISTINCT subject AS entity FROM knowledge_triple WHERE subject LIKE ?
|
||
UNION
|
||
SELECT DISTINCT object AS entity FROM knowledge_triple WHERE object LIKE ? LIMIT ?""",
|
||
(f"%{keyword}%", f"%{keyword}%", limit),
|
||
).fetchall()
|
||
return [dict(r) for r in rows]
|
||
|
||
def get_graph_stats(self) -> dict:
|
||
"""获取图谱统计。"""
|
||
with self._conn() as conn:
|
||
triple_count = conn.execute("SELECT COUNT(*) FROM knowledge_triple").fetchone()[0]
|
||
subject_count = conn.execute("SELECT COUNT(DISTINCT subject) FROM knowledge_triple").fetchone()[0]
|
||
predicate_count = conn.execute("SELECT COUNT(DISTINCT predicate) FROM knowledge_triple").fetchone()[0]
|
||
return {
|
||
"triples": triple_count,
|
||
"entities": subject_count,
|
||
"relations": predicate_count,
|
||
}
|
||
|
||
|
||
def extract_triples(text: str, source: str = "", model_preference: str = "auto") -> dict:
|
||
"""
|
||
从文本中抽取实体关系三元组(LLM 驱动)。
|
||
|
||
【返回】{triples: [{subject, predicate, object}], count}
|
||
"""
|
||
prompt = f"""从下面的文本中抽取实体和关系,输出 JSON 三元组数组。
|
||
|
||
【文本】
|
||
{text[:3000]}
|
||
|
||
【输出格式】
|
||
只输出 JSON 数组,每个元素:
|
||
[{{"subject": "实体1", "predicate": "关系", "object": "实体2"}}]
|
||
|
||
示例:
|
||
[{{"subject": "网关", "predicate": "连接", "object": "MQTT服务器"}}]
|
||
|
||
只输出 JSON,不要解释。"""
|
||
|
||
try:
|
||
model = get_model_for_task(model_preference, "strong")
|
||
resp = model.invoke(prompt)
|
||
content = resp.content if hasattr(resp, "content") else str(resp)
|
||
|
||
import re
|
||
|
||
json_match = re.search(r"\[.*\]", content, re.DOTALL)
|
||
if json_match:
|
||
triples = json.loads(json_match.group(0))
|
||
if isinstance(triples, list):
|
||
return {"triples": triples[:20], "count": len(triples), "source": source}
|
||
return {"triples": [], "count": 0, "source": source}
|
||
except Exception as exc: # noqa: BLE001
|
||
logger.warning("三元组抽取失败:%s", exc)
|
||
return {"triples": [], "count": 0, "error": str(exc)}
|
||
|
||
|
||
# 全局单例
|
||
_store: KnowledgeGraphStore | None = None
|
||
|
||
|
||
def get_kg_store() -> KnowledgeGraphStore:
|
||
global _store
|
||
if _store is None:
|
||
from app.config.settings import load_settings
|
||
|
||
settings = load_settings()
|
||
_store = KnowledgeGraphStore(settings.sqlite_db_path)
|
||
return _store
|