graphrag-patterns
Implement GraphRAG patterns combining knowledge graphs with retrieval for complex reasoning. Use this skill when building RAG over interconnected data or needing relationship-aware retrieval. Activate when: GraphRAG, knowledge graph, graph retrieval, entity relationships, Neo4j RAG, graph database, connected data.
What this skill does
# GraphRAG Patterns
**Combine knowledge graphs with RAG for relationship-aware retrieval and reasoning.**
## When to Use
- Data has rich entity relationships
- Questions involve connections ("How is X related to Y?")
- Need multi-hop reasoning across documents
- Building over structured + unstructured data
- Want explainable retrieval paths
## GraphRAG Architecture
```
┌──────────────────────────────────────────────────────────┐
│ Documents │
└─────────────────────────┬────────────────────────────────┘
│
┌───────────────┼───────────────┐
│ │ │
▼ ▼ ▼
┌────────────┐ ┌────────────┐ ┌────────────┐
│ Entity │ │ Vector │ │ Text │
│ Extraction │ │ Embeddings │ │ Chunks │
└─────┬──────┘ └─────┬──────┘ └─────┬──────┘
│ │ │
▼ │ │
┌────────────┐ │ │
│ Knowledge │ │ │
│ Graph │ │ │
└─────┬──────┘ │ │
│ │ │
└───────────────┼───────────────┘
│
▼
┌─────────────────────┐
│ Hybrid Index │
│ (Graph + Vectors) │
└──────────┬──────────┘
│
▼
┌─────────────────────┐
│ Graph-Aware RAG │
└─────────────────────┘
```
## Building the Knowledge Graph
### Entity & Relationship Extraction
```python
from langchain_openai import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
EXTRACTION_PROMPT = """Extract entities and relationships from the text.
Text: {text}
Return JSON:
{{
"entities": [
{{"name": "...", "type": "PERSON|ORG|PRODUCT|CONCEPT|...", "description": "..."}}
],
"relationships": [
{{"source": "...", "target": "...", "type": "WORKS_FOR|USES|RELATED_TO|...", "description": "..."}}
]
}}
"""
def extract_graph_elements(text: str) -> dict:
llm = ChatOpenAI(model="gpt-4", temperature=0)
prompt = ChatPromptTemplate.from_template(EXTRACTION_PROMPT)
chain = prompt | llm
result = chain.invoke({"text": text})
return json.loads(result.content)
```
### Store in Neo4j
```python
from neo4j import GraphDatabase
class GraphStore:
def __init__(self, uri, user, password):
self.driver = GraphDatabase.driver(uri, auth=(user, password))
def add_entity(self, entity: dict):
with self.driver.session() as session:
session.run("""
MERGE (e:Entity {name: $name})
SET e.type = $type, e.description = $description
""",
name=entity["name"],
type=entity["type"],
description=entity["description"]
)
def add_relationship(self, rel: dict):
with self.driver.session() as session:
session.run("""
MATCH (a:Entity {name: $source})
MATCH (b:Entity {name: $target})
MERGE (a)-[r:RELATES {type: $type}]->(b)
SET r.description = $description
""",
source=rel["source"],
target=rel["target"],
type=rel["type"],
description=rel["description"]
)
def get_neighbors(self, entity: str, hops: int = 2) -> list:
with self.driver.session() as session:
result = session.run("""
MATCH path = (e:Entity {name: $name})-[*1..$hops]-(related)
RETURN path
""",
name=entity, hops=hops
)
return [record["path"] for record in result]
```
## GraphRAG Retrieval Strategies
### 1. Entity-Centric Retrieval
```python
def entity_centric_retrieve(query: str, graph: GraphStore, vectorstore) -> list:
"""Extract entities from query, expand via graph, retrieve chunks."""
# Extract entities from query
entities = extract_entities(query)
# Get graph neighbors
expanded_entities = set(entities)
for entity in entities:
neighbors = graph.get_neighbors(entity, hops=2)
expanded_entities.update(neighbors)
# Retrieve chunks mentioning these entities
chunks = []
for entity in expanded_entities:
results = vectorstore.similarity_search(
entity,
k=3,
filter={"entities": {"$contains": entity}}
)
chunks.extend(results)
return deduplicate(chunks)
```
### 2. Path-Based Retrieval
```python
def path_retrieve(query: str, entity_a: str, entity_b: str, graph: GraphStore) -> str:
"""Find and explain paths between entities."""
with graph.driver.session() as session:
result = session.run("""
MATCH path = shortestPath(
(a:Entity {name: $entity_a})-[*..5]-(b:Entity {name: $entity_b})
)
RETURN path, length(path) as hops
ORDER BY hops
LIMIT 5
""",
entity_a=entity_a, entity_b=entity_b
)
paths = []
for record in result:
path = record["path"]
path_str = " -> ".join([node["name"] for node in path.nodes])
paths.append(path_str)
return paths
```
### 3. Community-Based Retrieval (Microsoft GraphRAG)
```python
from graspologic.partition import hierarchical_leiden
def build_communities(graph: GraphStore) -> dict:
"""Detect communities for hierarchical summarization."""
# Export graph to networkx
nx_graph = graph.to_networkx()
# Detect communities at multiple levels
communities = hierarchical_leiden(nx_graph, max_cluster_size=10)
# Summarize each community
community_summaries = {}
for community_id, members in communities.items():
member_descriptions = [graph.get_entity(m)["description"] for m in members]
summary = summarize_community(member_descriptions)
community_summaries[community_id] = summary
return community_summaries
def community_retrieve(query: str, community_summaries: dict) -> list:
"""Search community summaries first, then drill down."""
# Find relevant communities
relevant = vectorstore.similarity_search(
query,
k=3,
filter={"type": "community_summary"}
)
# Get entities from those communities
entities = []
for community in relevant:
entities.extend(community.metadata["members"])
# Retrieve detailed chunks
return retrieve_by_entities(entities)
```
## LangChain + Neo4j Integration
```python
from langchain_community.graphs import Neo4jGraph
from langchain.chains import GraphCypherQAChain
# Connect to Neo4j
graph = Neo4jGraph(
url="bolt://localhost:7687",
username="neo4j",
password="password"
)
# Natural language to Cypher
chain = GraphCypherQAChain.from_llm(
llm=ChatOpenAI(model="gpt-4"),
graph=graph,
verbose=True,
return_intermediate_steps=True
)
# Query in natural language
result = chain.invoke({
"query": "Who are the engineers working on Project Atlas?"
})
# Automatically generates: MATCH (p:Person)-[:WORKS_ON]->(proj:Project {name: 'Atlas'}) RETURN p
```
## Hybrid Graph + Vector Pipeline
```python
class GraphRAG:
def __init__(self, graph: GraphStore, vectorstore, llm):
self.graph = graph
self.vectorstore = vectorstore
self.llm = llm
def retrieve(self, query: str) -> list:
# 1. Vector search for initial chunks
vector_results = self.vectorstore.similarity_search(query, k=10)
# 2. Extract entities from results
entities = set()
for doc in vector_results:
entities.update(doc.metadata.get("entities", []))
# Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.