langgraph-rag
LangGraph state machines for RAG and agentic flows. Covers typed state, conditional edges for routing (answer/clarify/retrieve/rewrite), checkpointing with SqliteSaver/PostgresSaver, human-in-the-loop interrupts, multi-agent supervisor patterns, Self-RAG and CRAG as explicit graphs, combining with LangChain retrievers. USE WHEN: user mentions "LangGraph", "StateGraph", "agentic RAG", "conditional edges", "checkpointer", "human in the loop", "Self-RAG", "CRAG", "corrective RAG", "supervisor agent", "LangGraph RAG" DO NOT USE FOR: plain LangChain chains - use `langchain`; LlamaIndex workflows - use `llamaindex`; generic agentic RAG theory - use `agentic-rag`; DSPy programs - use `dspy`
What this skill does
# LangGraph for RAG
LangGraph models RAG as an explicit DAG/cyclic graph over a typed state. Unlike LCEL chains, it supports loops, branching, checkpointing, and HITL — exactly what agentic RAG needs.
## Installation
```bash
pip install langgraph langchain langchain-anthropic langchain-openai \
langchain-community langgraph-checkpoint-sqlite \
langgraph-checkpoint-postgres
```
## Typed State
```python
from typing import Annotated, Literal, TypedDict
from langgraph.graph.message import add_messages
from langchain_core.documents import Document
from langchain_core.messages import BaseMessage
class RagState(TypedDict):
question: str
rewritten_question: str
documents: list[Document]
grade: Literal["relevant", "irrelevant", "partial"]
attempts: int
answer: str
messages: Annotated[list[BaseMessage], add_messages]
```
`Annotated[list, add_messages]` uses a reducer so each node can *append* messages without clobbering prior turns. Without a reducer, each node overwrites the slot.
## Minimal Agentic RAG Graph
```python
from langgraph.graph import StateGraph, START, END
from langchain_anthropic import ChatAnthropic
from langchain_community.vectorstores import Chroma
from langchain_openai import OpenAIEmbeddings
llm = ChatAnthropic(model="claude-sonnet-4-5", temperature=0)
vs = Chroma(persist_directory="./chroma", embedding_function=OpenAIEmbeddings())
def retrieve(state: RagState) -> dict:
docs = vs.similarity_search(state["rewritten_question"] or state["question"], k=6)
return {"documents": docs}
def grade(state: RagState) -> dict:
prompt = f"Are the documents relevant to '{state['question']}'? Reply relevant|irrelevant|partial.\n\n" \
+ "\n---\n".join(d.page_content[:400] for d in state["documents"])
verdict = llm.invoke(prompt).content.strip().lower()
return {"grade": verdict if verdict in {"relevant","irrelevant","partial"} else "irrelevant"}
def rewrite(state: RagState) -> dict:
new_q = llm.invoke(f"Rewrite for better retrieval: {state['question']}").content
return {"rewritten_question": new_q, "attempts": state.get("attempts", 0) + 1}
def generate(state: RagState) -> dict:
ctx = "\n\n".join(d.page_content for d in state["documents"])
resp = llm.invoke(f"Answer using context.\n\nContext:\n{ctx}\n\nQ: {state['question']}")
return {"answer": resp.content}
def route_after_grade(state: RagState) -> str:
if state["grade"] == "relevant":
return "generate"
if state.get("attempts", 0) >= 2:
return "generate" # give up; best effort
return "rewrite"
graph = StateGraph(RagState)
graph.add_node("retrieve", retrieve)
graph.add_node("grade", grade)
graph.add_node("rewrite", rewrite)
graph.add_node("generate", generate)
graph.add_edge(START, "retrieve")
graph.add_edge("retrieve", "grade")
graph.add_conditional_edges("grade", route_after_grade, {
"rewrite": "rewrite", "generate": "generate",
})
graph.add_edge("rewrite", "retrieve")
graph.add_edge("generate", END)
app = graph.compile()
result = app.invoke({"question": "How do we rotate DB credentials?"})
```
## CRAG (Corrective RAG) as LangGraph
CRAG = retrieve → grade → if irrelevant, fall back to web search → generate.
```python
from langchain_community.tools.tavily_search import TavilySearchResults
web = TavilySearchResults(k=5)
def web_search(state: RagState) -> dict:
hits = web.invoke(state["rewritten_question"] or state["question"])
return {"documents": [Document(page_content=h["content"], metadata={"url": h["url"]}) for h in hits]}
def route_crag(state: RagState) -> str:
return {"relevant": "generate", "partial": "generate",
"irrelevant": "web_search"}[state["grade"]]
g = StateGraph(RagState)
g.add_node("retrieve", retrieve)
g.add_node("grade", grade)
g.add_node("web_search", web_search)
g.add_node("generate", generate)
g.add_edge(START, "retrieve")
g.add_edge("retrieve", "grade")
g.add_conditional_edges("grade", route_crag)
g.add_edge("web_search", "generate")
g.add_edge("generate", END)
crag_app = g.compile()
```
## Self-RAG as LangGraph
Self-RAG adds reflection tokens: `Retrieve?`, `IsRel`, `IsSup`, `IsUse`. Each becomes a node.
```python
def decide_retrieve(state) -> str:
v = llm.invoke(f"Does this need retrieval? yes/no. Q: {state['question']}").content.lower()
return "retrieve" if "yes" in v else "direct_answer"
def check_support(state) -> dict:
prompt = f"Is the draft supported by the docs? supported|partial|unsupported.\n\nDraft:{state['answer']}"
return {"grade": llm.invoke(prompt).content.strip().lower()}
# Wire: START -> decide_retrieve -> retrieve -> grade -> generate -> check_support -> (regenerate | END)
```
## Checkpointing (durable state + resumability)
```python
from langgraph.checkpoint.sqlite import SqliteSaver
checkpointer = SqliteSaver.from_conn_string("./lg_state.sqlite")
app = graph.compile(checkpointer=checkpointer)
config = {"configurable": {"thread_id": "user-42"}}
app.invoke({"question": "..."}, config=config)
# Later, resume mid-graph:
state = app.get_state(config)
print(state.next, state.values)
```
Postgres for multi-worker:
```python
from langgraph.checkpoint.postgres import PostgresSaver
checkpointer = PostgresSaver.from_conn_string("postgresql://user:pw@host/db")
checkpointer.setup()
```
## Human-in-the-Loop (interrupts)
```python
from langgraph.types import interrupt, Command
def confirm_cypher(state):
decision = interrupt({"cypher": state["generated_cypher"], "ask": "Run this query?"})
return {"approved": decision == "yes"}
graph.add_node("confirm_cypher", confirm_cypher)
# Client-side:
# app.invoke(inputs, config) # pauses at interrupt
# app.invoke(Command(resume="yes"), config) # continue
```
Use for: destructive actions, costly tool calls, schema changes, low-confidence answers.
## Multi-Agent Supervisor Pattern
```python
from langgraph.prebuilt import create_react_agent
retriever_agent = create_react_agent(llm, tools=[retrieval_tool], prompt="Retrieval specialist.")
sql_agent = create_react_agent(llm, tools=[sql_tool], prompt="SQL specialist.")
graph_agent = create_react_agent(llm, tools=[cypher_tool], prompt="Graph DB specialist.")
def supervisor(state):
route = llm.invoke(f"Route to retriever|sql|graph|finish: {state['question']}").content.strip()
return {"route": route}
def pick(state) -> str:
return state["route"]
super_g = StateGraph(RagState)
super_g.add_node("supervisor", supervisor)
super_g.add_node("retriever", retriever_agent)
super_g.add_node("sql", sql_agent)
super_g.add_node("graph", graph_agent)
super_g.add_edge(START, "supervisor")
super_g.add_conditional_edges("supervisor", pick,
{"retriever": "retriever", "sql": "sql", "graph": "graph", "finish": END})
for n in ("retriever", "sql", "graph"):
super_g.add_edge(n, "supervisor") # return to supervisor
```
## Streaming
```python
async for event in app.astream_events({"question": "..."}, version="v2"):
if event["event"] == "on_chat_model_stream":
print(event["data"]["chunk"].content, end="")
```
`stream_mode="values"` emits full state snapshots; `"updates"` emits per-node deltas; `"messages"` emits token chunks.
## Combining with LangChain Retrievers
Any LangChain retriever drops straight into a node:
```python
from langchain.retrievers import EnsembleRetriever, BM25Retriever
retriever = EnsembleRetriever(
retrievers=[vs.as_retriever(search_kwargs={"k": 8}), BM25Retriever.from_documents(docs)],
weights=[0.6, 0.4],
)
def retrieve(state): return {"documents": retriever.invoke(state["question"])}
```
## Anti-Patterns
| Anti-Pattern | Fix |
|---|---|
| One giant node that does retrieve + rewrite + generate | Split per responsibility; enables partial reruns |
| Unbounded rewrite loop | Cap via `attempts` counter in state + `add_conditional_edges` guard |
| Forgetting message reducer | `Annotated[list, add_messages]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.