← 返回 Skills 市场
vnesin-sarai

Knowledge Graph for Agents

作者 SARAI Defence · GitHub ↗ · v1.0.0 · MIT-0
cross-platform ✓ 安全检测通过
137
总下载
1
收藏
0
当前安装
1
版本数
在 OpenClaw 中安装
/install knowledge-graph-agents
功能描述
Add a knowledge graph layer to an AI agent for relationship reasoning and multi-hop recall. Use when agents need to answer "who works with whom", "what's con...
使用说明 (SKILL.md)

You are an expert in knowledge graphs for AI agent systems. Help the user add a graph layer that captures entities and relationships from their data, enabling multi-hop reasoning that vector and keyword search can't do.

Why a Knowledge Graph?

Vector search finds similar documents. BM25 finds matching keywords. Neither answers:

  • "Who works with Alice at Acme Corp?"
  • "What services are running on the production server?"
  • "Which projects depend on PostgreSQL?"

These require relationship traversal — following connections between entities. That's what a knowledge graph does.

Architecture

Ingest → Entity Extraction → Graph Storage → Query
                                    ↓
                            Spreading Activation
                            (2-hop traversal)

Entity Extraction (at ingest time)

Extract entities from every chunk of text you index:

def extract_entities(text):
    """Simple heuristic entity extraction — no LLM needed."""
    entities = []
    # Title-case words (proper nouns)
    for word in text.split():
        if word[0].isupper() and len(word) > 2:
            entities.append({"name": word, "label": "Entity"})
    # Email addresses → Person
    for email in re.findall(r'[\w.+-]+@[\w.-]+\.\w+', text):
        entities.append({"name": email.split("@")[0].title(), "label": "Person"})
    return entities

For production, use spaCy NER or an LLM-based extractor for higher quality.

Graph Storage

SQLite graph (simple, zero dependencies):

CREATE TABLE nodes (
    id INTEGER PRIMARY KEY,
    name TEXT UNIQUE,
    label TEXT,
    properties_json TEXT DEFAULT '{}'
);

CREATE TABLE edges (
    source_id INTEGER REFERENCES nodes(id),
    target_id INTEGER REFERENCES nodes(id),
    rel_type TEXT DEFAULT 'RELATED_TO',
    weight REAL DEFAULT 1.0
);

Neo4j (production, scales better):

CREATE (n:Entity {name: "Alice", label: "Person"})
CREATE (m:Entity {name: "Acme Corp", label: "Organisation"})
CREATE (n)-[:WORKS_AT]->(m)

Co-occurrence Edges

When two named entities appear in the same chunk, create a CO_OCCURS edge:

NAMED_LABELS = {"Person", "Place", "Organisation", "Event", "Product"}

for i, e1 in enumerate(chunk_entities):
    for e2 in chunk_entities[i+1:]:
        if e1["label"] in NAMED_LABELS and e2["label"] in NAMED_LABELS:
            graph.add_edge(e1["name"], e2["name"], "CO_OCCURS")

This is what gives the graph traversal value — connecting entities that appear together in context.

Querying: Spreading Activation (2-hop)

Don't just match entities — traverse their connections:

-- Find entities connected to the query entity within 2 hops
WITH start_nodes AS (
    SELECT id, name FROM nodes WHERE name LIKE '%Alice%'
),
hop1 AS (
    SELECT CASE WHEN e.source_id = s.id THEN e.target_id ELSE e.source_id END as mid_id
    FROM start_nodes s JOIN edges e ON (e.source_id = s.id OR e.target_id = s.id)
    WHERE e.weight >= 0.5
),
hop2 AS (
    SELECT CASE WHEN e.source_id = h.mid_id THEN e.target_id ELSE e.source_id END as end_id,
           h.mid_id
    FROM hop1 h JOIN edges e ON (e.source_id = h.mid_id OR e.target_id = h.mid_id)
)
SELECT DISTINCT n.name, n.label FROM hop2 JOIN nodes n ON n.id = hop2.end_id;

Hebbian Strengthening

Edges between co-accessed entities get stronger over time:

def hebbian_strengthen(accessed_entities):
    """Strengthen edges between entities accessed in the same query."""
    for i, e1 in enumerate(accessed_entities):
        for e2 in accessed_entities[i+1:]:
            graph.update_edge_weight(e1, e2, delta=0.1)

Integration with Hybrid Search

The graph layer works alongside BM25 and vector search:

  1. Extract entities from query — "What services does Alice use?" → entities: [Alice, services]
  2. Query graph — find Alice node, traverse USES relationships
  3. Boost matching chunks — chunks mentioning graph-discovered entities get a score boost
  4. Fuse with other layers — graph results merge into the unified ranking

Common Patterns

Resolving Ambiguity

# Merge duplicate entities
graph.merge("Alice", "Alice Smith")  # Same person, different references

Temporal Edges

# Add timestamps to relationships
graph.add_edge("Alice", "Project Alpha", "WORKS_ON", 
               properties={"since": "2024-01-15"})

Entity Types for Agents

Label Examples Use Case
Person team members, contacts Who questions
Organisation companies, teams Affiliation queries
Project initiatives, repos What's connected
System services, tools Infrastructure queries
Place offices, cities Location queries

Pitfalls

  1. Edge explosion — don't create edges between ALL entities, only named ones (Person, Place, Org). Topic words create too many low-value edges.
  2. No graph layer — you'll hit a ceiling where flat retrieval can't answer relationship questions.
  3. Over-reliance on LLM extraction — heuristic extraction (capitalisation + patterns) is 80% as good at 0% of the cost.
  4. Forgetting to prune — graphs grow. Schedule periodic cleanup of orphan nodes and weak edges.

Getting Started

  1. Pick a backend: SQLite (simple) or Neo4j (production)
  2. Add entity extraction to your ingest pipeline
  3. Create co-occurrence edges between named entities per chunk
  4. Add 2-hop spreading activation to your search
  5. Fuse graph results with your existing BM25/vector search
  6. Set up a simple evaluation (test queries → expected results)
安全使用建议
This skill appears coherent and useful for relationship-style queries. Before you implement: 1) remember the graph will store extracted entities and query-access patterns — consider privacy, retention, and access controls (especially if using Neo4j across a network); 2) the provided extractor is a simplistic heuristic (capitalization + regex) and will produce false positives/negatives — use a proper NER or LLM extractor for higher quality; 3) Hebbian strengthening records which entities were accessed together — ensure that logging of query context can't leak sensitive queries; 4) plan pruning policies to avoid edge explosion and storage bloat; and 5) if you add Neo4j or third-party ML services, secure their credentials and endpoints (the skill itself does not request them, but integrations will). Overall: coherent and expected for the stated purpose.
功能分析
Type: OpenClaw Skill Name: knowledge-graph-agents Version: 1.0.0 The skill bundle is an educational guide for implementing knowledge graphs in AI agents. It contains standard Python and SQL/Cypher snippets for entity extraction, graph storage, and relationship traversal (SKILL.md). There are no indicators of data exfiltration, malicious execution, or prompt injection attacks.
能力评估
Purpose & Capability
The name/description (knowledge graph for relationship queries) match the instructions: entity extraction, graph storage, co-occurrence edges, 2‑hop traversal, and integration with BM25/vector search. No unrelated credentials, binaries, or installs are requested.
Instruction Scope
SKILL.md instructs the agent to extract entities from every chunk of indexed text and to strengthen edges based on query accesses — this is expected for a graph layer. Note: the provided extractor is a heuristic and may misclassify; production use recommends spaCy or an LLM. The instructions imply reading and storing user data (documents, query access patterns) into the graph — this is functionally necessary but has privacy/retention implications that implementers should consider.
Install Mechanism
Instruction-only skill with no install spec or external downloads. Lowest install risk — nothing is written to disk by the skill itself.
Credentials
No environment variables, credentials, or config paths are requested. The instructions reference optional backends (SQLite or Neo4j); any credentials for Neo4j would be normal and expected but are not required by the skill itself.
Persistence & Privilege
always:false and no self-install behavior. Skill describes storing entities/edges in a graph (expected for its function) but does not request elevated platform privileges or cross-skill configuration changes.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install knowledge-graph-agents
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /knowledge-graph-agents 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v1.0.0
Design knowledge graphs for AI agents — entity extraction, multi-hop traversal, Hebbian strengthening
元数据
Slug knowledge-graph-agents
版本 1.0.0
许可证 MIT-0
累计安装 0
当前安装数 0
历史版本数 1
常见问题

Knowledge Graph for Agents 是什么?

Add a knowledge graph layer to an AI agent for relationship reasoning and multi-hop recall. Use when agents need to answer "who works with whom", "what's con... 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 137 次。

如何安装 Knowledge Graph for Agents?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install knowledge-graph-agents」即可一键安装,无需额外配置。

Knowledge Graph for Agents 是免费的吗?

是的,Knowledge Graph for Agents 完全免费,采用 MIT-0 许可证,可自由下载、安装和使用。

Knowledge Graph for Agents 支持哪些平台?

Knowledge Graph for Agents 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 Knowledge Graph for Agents?

由 SARAI Defence(@vnesin-sarai)开发并维护,当前版本 v1.0.0。

💬 留言讨论