langgraph-rag
БесплатноБез исполняемых скриптовНе проверенLangGraph state machines for RAG and agentic flows. Covers typed state, conditional edges for routing (answer/clarify/retrieve/rewrite), checkpointing with…
от claude-dev-suite★ 51 звезда на GitHubОб этом скилле
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
pip install langgraph langchain langchain-anthropic langchain-openai \
langchain-community langgraph-checkpoint-sqlite \
langgraph-checkpoint-postgres
Typed State
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
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.
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.
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)
from langgraph.checkpoint.sqlite import SqliteSaver
checkpointer = SqliteSaver.from_conn_string("./lg_state.sqlite")
app = graph.compile(checkpointer=checkpointer)
config = {"configurabl
Установить langgraph-rag в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobWriteEditFAQ
Что делает скилл 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`
Как установить скилл langgraph-rag?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл langgraph-rag запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic