### Create Basic Agent with Tool (Python) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langchain-fundamentals/SKILL.md Use `create_agent` to build an agent with a specific LLM, tools, and system prompt. This example defines a simple `get_weather` tool and invokes the agent to get weather information. ```python from langchain.agents import create_agent from langchain_core.tools import tool @tool def get_weather(location: str) -> str: """Get current weather for a location. Args: location: City name """ return f"Weather in {location}: Sunny, 72F" agent = create_agent( model="anthropic:claude-sonnet-4-5", tools=[get_weather], system_prompt="You are a helpful assistant." ) result = agent.invoke({ "messages": [{"role": "user", "content": "What's the weather in Paris?"}] }) print(result["messages"][-1].content) ``` -------------------------------- ### Production PostgreSQL Checkpointing Setup Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langgraph-persistence/SKILL.md Configure PostgreSQL-backed checkpointing for production deployments. The `setup()` method should be run once during deployment, not at application startup. ```python import os from langgraph.checkpoint.postgres import PostgresSaver # Run once during deployment (not at application startup): # PostgresSaver.from_conn_string(os.environ["DATABASE_URL"]).setup() with PostgresSaver.from_conn_string(os.environ["DATABASE_URL"]) as checkpointer: graph = builder.compile(checkpointer=checkpointer) ``` ```typescript import { PostgresSaver } from "@langchain/langgraph-checkpoint-postgres"; // Run once during deployment (not at application startup): // await PostgresSaver.fromConnString(process.env.DATABASE_URL!).setup(); const checkpointer = PostgresSaver.fromConnString(process.env.DATABASE_URL!); const graph = builder.compile({ checkpointer }); ``` -------------------------------- ### Create Basic Agent with Tool (TypeScript) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langchain-fundamentals/SKILL.md Use `createAgent` to build an agent with a specific LLM, tools, and system prompt. This example defines a simple `getWeather` tool and invokes the agent to get weather information. ```typescript import { createAgent } from "langchain"; import { tool } from "@langchain/core/tools"; import { z } from "zod"; const getWeather = tool( async ({ location }) => `Weather in ${location}: Sunny, 72F`, { name: "get_weather", description: "Get current weather for a location.", schema: z.object({ location: z.string().describe("City name") }), } ); const agent = createAgent({ model: "anthropic:claude-sonnet-4-5", tools: [getWeather], systemPrompt: "You are a helpful assistant.", }); const result = await agent.invoke({ messages: [{ role: "user", content: "What's the weather in Paris?" }], }); console.log(result.messages[result.messages.length - 1].content); ``` -------------------------------- ### Install LangChain Skills using Install Script Source: https://github.com/langchain-ai/langchain-skills/blob/main/README.md Use the install script for Claude Code or Deep Agents. Specify directory and global options as needed. ```bash # Install for Claude Code in current directory (default) ./install.sh ``` ```bash # Install for Claude Code in a specific project directory ./install.sh ~/my-project ``` ```bash # Install for Claude Code globally ./install.sh --global ``` ```bash # Install for Deep Agents CLI in a specific project directory ./install.sh --deepagents ~/my-project ``` ```bash # Install for Deep Agents CLI globally (includes agent persona) ./install.sh --deepagents --global ``` -------------------------------- ### Install LangChain Skills via install.sh Source: https://context7.com/langchain-ai/langchain-skills/llms.txt Installs skills for Claude Code or Deep Agents CLI with options for global installation, specific projects, overwriting, and skipping prompts. ```bash ./install.sh ``` ```bash ./install.sh ~/my-project ``` ```bash ./install.sh --global ``` ```bash ./install.sh --deepagents ~/my-project ``` ```bash ./install.sh --deepagents --global ``` ```bash ./install.sh --force --yes ``` -------------------------------- ### Install LangChain Skills via npx Source: https://context7.com/langchain-ai/langchain-skills/llms.txt Installs all 11 skills locally or globally for a specific agent. Use '--skill *' to add all skills. ```bash npx skills add langchain-ai/langchain-skills --skill '*' --yes ``` ```bash npx skills add langchain-ai/langchain-skills --skill '*' --yes --global ``` ```bash npx skills add langchain-ai/langchain-skills --agent claude-code --skill '*' --yes --global ``` -------------------------------- ### Install LangChain Skills Globally Source: https://github.com/langchain-ai/langchain-skills/blob/main/README.md Use this command to add LangChain skills to all your projects for global access. ```bash npx skills add langchain-ai/langchain-skills --skill '*' --yes --global ``` -------------------------------- ### Install LangChain Skills Locally Source: https://github.com/langchain-ai/langchain-skills/blob/main/README.md Use this command to add LangChain skills to your current project for local use. ```bash npx skills add langchain-ai/langchain-skills --skill '*' --yes ``` -------------------------------- ### Basic Human-In-The-Loop Setup Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langchain-middleware/SKILL.md Configure an agent with HumanInTheLoopMiddleware to pause before executing specific tools, requiring explicit approval. Ensure a checkpointer is provided for HITL workflows. ```python from langchain.agents import create_agent from langchain.agents.middleware import HumanInTheLoopMiddleware from langgraph.checkpoint.memory import MemorySaver from langchain.tools import tool @tool def send_email(to: str, subject: str, body: str) -> str: """Send an email.""" return f"Email sent to {to}" agent = create_agent( model="gpt-4.1", tools=[send_email], checkpointer=MemorySaver(), # Required for HITL middleware=[ HumanInTheLoopMiddleware( interrupt_on={ "send_email": {"allowed_decisions": ["approve", "edit", "reject"]}, } ) ], ) ``` ```typescript import { createAgent, humanInTheLoopMiddleware } from "langchain"; import { MemorySaver } from "@langchain/langgraph"; import { tool } from "@langchain/core/tools"; import { z } from "zod"; const sendEmail = tool( async ({ to, subject, body }) => `Email sent to ${to}`, { name: "send_email", description: "Send an email", schema: z.object({ to: z.string(), subject: z.string(), body: z.string() }), } ); const agent = createAgent({ model: "anthropic:claude-sonnet-4-5", tools: [sendEmail], checkpointer: new MemorySaver(), middleware: [ humanInTheLoopMiddleware({ interruptOn: { send_email: { allowedDecisions: ["approve", "edit", "reject"] } }, }), ], }); ``` -------------------------------- ### Environment Setup for API Keys Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/AGENTS.md Set these environment variables before running the code to authenticate with OpenAI and Anthropic models. ```bash OPENAI_API_KEY= # For OpenAI models ANTHROPIC_API_KEY= # For Anthropic models ``` -------------------------------- ### StoreBackend Requires Store Instance Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/deep-agents-memory/SKILL.md When using StoreBackend, ensure a store instance is provided. The WRONG example shows incorrect instantiation, while the CORRECT example demonstrates the proper way to initialize it. ```python # WRONG agent = create_deep_agent(backend=lambda rt: StoreBackend(rt)) # CORRECT agent = create_deep_agent(backend=lambda rt: StoreBackend(rt), store=InMemoryStore()) ``` -------------------------------- ### Install Claude Code Plugin Source: https://github.com/langchain-ai/langchain-skills/blob/main/README.md Commands to install LangChain skills directly as a Claude Code plugin. ```bash /plugin marketplace add langchain-ai/langchain-skills ``` ```bash /plugin install langchain-skills@langchain-skills ``` -------------------------------- ### TypeScript Agent Creation Equivalent Source: https://context7.com/langchain-ai/langchain-skills/llms.txt Provides the TypeScript equivalent of the Python agent creation example. Uses `@langchain/core/tools` and `MemorySaver` for similar functionality. ```typescript // TypeScript — equivalent agent import { createAgent } from "langchain"; import { tool } from "@langchain/core/tools"; import { MemorySaver } from "@langchain/langgraph"; import { z } from "zod"; const getWeather = tool( async ({ location }) => `Weather in ${location}: Sunny, 72°F`, { name: "get_weather", description: "Get current weather. Use when asked about weather.", schema: z.object({ location: z.string().describe("City name") }), } ); const agent = createAgent({ model: "anthropic:claude-sonnet-4-5", tools: [getWeather], systemPrompt: "You are a helpful assistant.", checkpointer: new MemorySaver(), }); const config = { configurable: { thread_id: "user-123" } }; const result = await agent.invoke( { messages: [{ role: "user", content: "Weather in Tokyo?" }] }, config ); console.log(result.messages[result.messages.length - 1].content); ``` -------------------------------- ### Complete RAG Pipeline Setup Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langchain-rag/SKILL.md Demonstrates an end-to-end RAG pipeline, including document loading, splitting, embedding, storing in an in-memory vector store, retrieval, and LLM-based generation. ```python from langchain_openai import ChatOpenAI, OpenAIEmbeddings from langchain_community.vectorstores import InMemoryVectorStore from langchain_text_splitters import RecursiveCharacterTextSplitter from langchain_core.documents import Document # 1. Load documents docs = [ Document(page_content="LangChain is a framework for LLM apps.", metadata={}), Document(page_content="RAG = Retrieval Augmented Generation.", metadata={}), ] # 2. Split documents splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50) splits = splitter.split_documents(docs) # 3. Create embeddings and store embeddings = OpenAIEmbeddings(model="text-embedding-3-small") vectorstore = InMemoryVectorStore.from_documents(splits, embeddings) # 4. Create retriever retriever = vectorstore.as_retriever(search_kwargs={"k": 4}) # 5. Use in RAG model = ChatOpenAI(model="gpt-4.1") query = "What is RAG?" relevant_docs = retriever.invoke(query) context = "\n\n".join([doc.page_content for doc in relevant_docs]) response = model.invoke([ {"role": "system", "content": f"Use this context:\n\n{context}"}, {"role": "user", "content": query}, ]) ``` ```typescript import { ChatOpenAI, OpenAIEmbeddings } from "@langchain/openai"; import { MemoryVectorStore } from "@langchain/classic/vectorstores/memory"; import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters"; import { Document } from "@langchain/core/documents"; // 1. Load documents const docs = [ new Document({ pageContent: "LangChain is a framework for LLM apps.", metadata: {} }), new Document({ pageContent: "RAG = Retrieval Augmented Generation.", metadata: {} }), ]; // 2. Split documents const splitter = new RecursiveCharacterTextSplitter({ chunkSize: 500, chunkOverlap: 50 }); const splits = await splitter.splitDocuments(docs); // 3. Create embeddings and store const embeddings = new OpenAIEmbeddings({ model: "text-embedding-3-small" }); const vectorstore = await MemoryVectorStore.fromDocuments(splits, embeddings); // 4. Create retriever const retriever = vectorstore.asRetriever({ k: 4 }); // 5. Use in RAG const model = new ChatOpenAI({ model: "gpt-4.1" }); const query = "What is RAG?"; const relevantDocs = await retriever.invoke(query); const context = relevantDocs.map(doc => doc.pageContent).join("\n\n"); const response = await model.invoke([ { role: "system", content: `Use this context:\n\n${context}` }, { role: "user", content: query }, ]); ``` -------------------------------- ### LangChain Package Versioning Guide Source: https://context7.com/langchain-ai/langchain-skills/llms.txt Illustrates correct and incorrect version pinning strategies for LangChain packages. Avoid legacy versions and unpinned community packages for stability. ```python # WRONG: Legacy — no new features, maintenance-only langchain>=0.3,<0.4 ``` ```python # CORRECT: LTS release langchain>=1.0,<2.0 ``` ```python # WRONG: langchain-community is NOT semver — unsafe unpinned langchain-community>=0.4 ``` ```python # CORRECT: Pin exact minor series langchain-community>=0.4.0,<0.5.0 ``` -------------------------------- ### Reject Tool Call with Feedback (Python) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langchain-middleware/SKILL.md Demonstrates how to reject a tool call and provide feedback to explain the reason for rejection. This is useful for guiding the agent or informing the user. ```python # Human rejects result2 = agent.invoke( Command(resume={ "decisions": [{ "type": "reject", "feedback": "Cannot delete customer data without manager approval", }] }), config=config ) ``` -------------------------------- ### Basic Store Operations in Python Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langgraph-persistence/SKILL.md Demonstrates basic `InMemoryStore` operations: `put`, `get`, `search`, and `delete` for managing key-value data. ```python from langgraph.store.memory import InMemoryStore store = InMemoryStore() store.put(("user-123", "facts"), "location", {"city": "San Francisco"}) # Put item = store.get(("user-123", "facts"), "location") # Get results = store.search(("user-123", "facts"), filter={"city": "San Francisco"}) # Search store.delete(("user-123", "facts"), "location") # Delete ``` -------------------------------- ### Complete HITL Approval Workflow (Python) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/deep-agents-orchestration/SKILL.md This example demonstrates a complete Human-in-the-Loop workflow: triggering an interrupt, checking the pending state, approving the action, and resuming execution. It requires a thread_id for state management. ```python from deepagents import create_deep_agent from langgraph.checkpoint.memory import MemorySaver from langgraph.types import Command agent = create_deep_agent( interrupt_on={"write_file": True}, checkpointer=MemorySaver() ) config = {"configurable": {"thread_id": "session-1"}} # Step 1: Agent proposes write_file - execution pauses result = agent.invoke({ "messages": [{"role": "user", "content": "Write config to /prod.yaml"}] }, config=config) # Step 2: Check for interrupts state = agent.get_state(config) if state.next: print(f"Pending action") # Step 3: Approve the action and resume # agent.submit(Command.CREATE, next=state.next, config=config) # agent.invoke(config=config) # Resume execution ``` -------------------------------- ### Subagents are Stateless (Python Example) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/deep-agents-orchestration/SKILL.md Illustrates that subagents do not retain memory between calls. All necessary information must be provided in a single instruction. ```python # WRONG: Subagents don't remember previous calls # task(agent='research', instruction='Find data') # task(agent='research', instruction='What did you find?') # Starts fresh! # CORRECT: Complete instructions upfront # task(agent='research', instruction='Find data on AI, save to /research/, return summary') ``` -------------------------------- ### TypeScript: Basic Interrupt and Resume Source: https://context7.com/langchain-ai/langchain-skills/llms.txt This TypeScript example shows a basic approval node using interrupts. It demonstrates how to check if the graph is interrupted and then resume it with a human decision. ```typescript // TypeScript — basic interrupt and resume import { interrupt, Command, MemorySaver, StateGraph, StateSchema, START, END, isInterrupted, INTERRUPT } from "@langchain/langgraph"; import { z } from "zod"; const State = new StateSchema({ approved: z.boolean().default(false) }); const approvalNode = async (state: typeof State.State) => { const approved = interrupt("Do you approve?"); return { approved }; }; const graph = new StateGraph(State) .addNode("approval", approvalNode) .addEdge(START, "approval") .addEdge("approval", END) .compile({ checkpointer: new MemorySaver() }); const config = { configurable: { thread_id: "t1" } }; let result = await graph.invoke({ approved: false }, config); if (isInterrupted(result)) { // Resume with human decision result = await graph.invoke(new Command({ resume: true }), config); console.log(result.approved); // true } ``` -------------------------------- ### Python Human-in-the-Loop Middleware Source: https://context7.com/langchain-ai/langchain-skills/llms.txt Demonstrates Python middleware for agent loops, specifically `HumanInTheLoopMiddleware`. This example requires a checkpointer and thread_id for operation and allows resuming after manual intervention. ```python # Python — HITL with per-tool policies, resume after interrupt from langchain.agents import create_agent from langchain.agents.middleware import HumanInTheLoopMiddleware, wrap_tool_call, before_model from langchain.tools import tool from langgraph.checkpoint.memory import MemorySaver from langgraph.types import Command @tool def send_email(to: str, subject: str, body: str) -> str: """Send an email.""" return f"Email sent to {to}" @tool def delete_email(email_id: str) -> str: """Permanently delete an email.""" return f"Deleted {email_id}" ``` -------------------------------- ### Tool Description Best Practices (TypeScript) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langchain-fundamentals/SKILL.md Write clear, specific descriptions for tools in TypeScript to guide the agent's usage. Include schema descriptions. ```typescript // WRONG: Vague description const badTool = tool(async ({ input }) => "result", { name: "bad_tool", description: "Does stuff.", // Too vague! schema: z.object({ input: z.string() }), }); // CORRECT: Clear, specific description const search = tool(async ({ query }) => webSearch(query), { name: "search", description: "Search the web for current information about a topic. Use this when you need recent data or facts.", schema: z.object({ query: z.string().describe("The search query (2-10 words recommended)"), }), }); ``` -------------------------------- ### Define Basic Tool (TypeScript) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langchain-fundamentals/SKILL.md Define a tool using the `tool()` function. This example creates an `add` tool that takes two number arguments and returns their sum. The schema defines the input parameters and their descriptions. ```typescript import { tool } from "@langchain/core/tools"; import { z } from "zod"; const add = tool( async ({ a, b }) => a + b, { name: "add", description: "Add two numbers.", schema: z.object({ a: z.number().describe("First number"), b: z.number().describe("Second number"), }), } ); ``` -------------------------------- ### Define Basic Tool (Python) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langchain-fundamentals/SKILL.md Define a tool using the `@tool` decorator. This example creates an `add` tool that takes two float arguments and returns their sum. Ensure type hints and docstrings are provided for clarity and schema generation. ```python from langchain_core.tools import tool @tool def add(a: float, b: float) -> float: """Add two numbers. Args: a: First number b: Second number """ return a + b ``` -------------------------------- ### Configure Different HITL Policies Per Tool Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langchain-middleware/SKILL.md Sets up distinct Human-in-the-Loop (HITL) policies for individual tools based on their risk level. For example, 'edit' might be disallowed for sensitive operations. ```python agent = create_agent( model="gpt-4.1", tools=[send_email, read_email, delete_email], checkpointer=MemorySaver(), middleware=[ HumanInTheLoopMiddleware( interrupt_on={ "send_email": {"allowed_decisions": ["approve", "edit", "reject"]}, "delete_email": {"allowed_decisions": ["approve", "reject"]}, # No edit "read_email": False, # No HITL for reading } ) ], ) ``` -------------------------------- ### Create Agent with FilesystemBackend (Python) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/deep-agents-core/SKILL.md Sets up an agent using FilesystemBackend for on-demand skill loading. Requires a checkpointer for state management. ```python from deepagents import create_deep_agent from deepagents.backends import FilesystemBackend from langgraph.checkpoint.memory import MemorySaver agent = create_deep_agent( backend=FilesystemBackend(root_dir=".", virtual_mode=True), skills=["./skills/"], checkpointer=MemorySaver() ) result = agent.invoke({ "messages": [{"role": "user", "content": "Use the python-testing skill"}] }, config={"configurable": {"thread_id": "session-1"}}) ``` -------------------------------- ### Configure FilesystemBackend for Local Skills Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/deep-agents-core/SKILL.md Skills need a proper backend to be loaded from the filesystem. Use FilesystemBackend for local skills, specifying the root directory and enabling virtual mode if necessary. ```python # WRONG: Skills won't load without proper backend agent = create_deep_agent(skills=["./skills/"]) # CORRECT: Use FilesystemBackend for local skills agent = create_deep_agent( backend=FilesystemBackend(root_dir=".", virtual_mode=True), skills=["./skills/"] ) ``` -------------------------------- ### Create Agent with FilesystemBackend (TypeScript) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/deep-agents-core/SKILL.md Sets up an agent using FilesystemBackend for on-demand skill loading. Requires a checkpointer for state management. ```typescript import { createDeepAgent, FilesystemBackend } from "deepagents"; import { MemorySaver } from "@langchain/langgraph"; const agent = await createDeepAgent({ backend: new FilesystemBackend({ rootDir: ".", virtualMode: true }), skills: ["./skills/"], checkpointer: new MemorySaver() }); const result = await agent.invoke({ messages: [{ role: "user", content: "Use the python-testing skill" }] }, { configurable: { thread_id: "session-1" } }); ``` -------------------------------- ### Python Checkpointer Setup for Interrupts Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langgraph-human-in-the-loop/SKILL.md A checkpointer is mandatory for interrupt functionality in Python graphs. Use `InMemorySaver` for basic setups. ```python # WRONG graph = builder.compile() # CORRECT graph = builder.compile(checkpointer=InMemorySaver()) ``` -------------------------------- ### Minimal LangGraph Project Dependencies (TypeScript) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langchain-dependencies/SKILL.md Install these packages for a basic LangGraph project. Ensure `@langchain/core` is explicitly installed in monorepos. ```json { "dependencies": { "@langchain/core": "^1.0.0", "langchain": "^1.0.0", "@langchain/langgraph": "^1.0.0", "langsmith": "^0.3.0" } } ``` -------------------------------- ### Create Agent with StoreBackend (Python) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/deep-agents-core/SKILL.md Loads skill content into a Store backend for environments without direct filesystem access. Requires a Store instance for persistence. ```python from deepagents import create_deep_agent from deepagents.backends import StoreBackend from deepagents.backends.utils import create_file_data from langgraph.store.memory import InMemoryStore store = InMemoryStore() # Load skill content into store skill_content = """--- name: python-testing description: Best practices for Python testing with pytest --- # Python Testing Skill ...""" store.put( namespace=("filesystem",), key="/skills/python-testing/SKILL.md", value=create_file_data(skill_content) ) agent = create_deep_agent( backend=lambda rt: StoreBackend(rt), store=store, skills=["/skills/"] ) ``` -------------------------------- ### StoreBackend Requires Store Instance (TypeScript) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/deep-agents-memory/SKILL.md When using StoreBackend in TypeScript, ensure a store instance is provided. The WRONG example shows incorrect instantiation, while the CORRECT example demonstrates the proper way to initialize it. ```typescript // WRONG const agent = await createDeepAgent({ backend: (c) => new StoreBackend(c) }); // CORRECT const agent = await createDeepAgent({ backend: (c) => new StoreBackend(c), store: new InMemoryStore() }); ``` -------------------------------- ### Verify Node.js Version for Langchain Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langchain-dependencies/SKILL.md Node.js version 20.x or higher is officially supported for Langchain. Check your Node.js version before installing. ```bash # Verify before installing node --version # must be v20.x or higher ``` -------------------------------- ### Minimal Deep Agents Project Dependencies (TypeScript) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langchain-dependencies/SKILL.md Install these packages for a Deep Agents project. `deepagents` bundles `langgraph` internally. ```json { "dependencies": { "deepagents": "latest", "@langchain/core": "^1.0.0", "langchain": "^1.0.0", "langsmith": "^0.3.0" } } ``` -------------------------------- ### Link LangChain Skills to Claude Code Agent Source: https://github.com/langchain-ai/langchain-skills/blob/main/README.md This command links the installed LangChain skills specifically to the Claude Code agent. ```bash npx skills add langchain-ai/langchain-skills --agent claude-code --skill '*' --yes --global ``` -------------------------------- ### Tool Description Best Practices (Python) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langchain-fundamentals/SKILL.md Provide clear, specific descriptions for tools in Python to help the agent determine when to use them. Include Args documentation. ```python # WRONG: Vague or missing description @tool def bad_tool(input: str) -> str: """Does stuff.""" return "result" # CORRECT: Clear, specific description with Args @tool def search(query: str) -> str: """Search the web for current information about a topic. Use this when you need recent data or facts. Args: query: The search query (2-10 words recommended) """ return web_search(query) ``` -------------------------------- ### TypeScript Checkpointer Setup for Interrupts Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langgraph-human-in-the-loop/SKILL.md Ensure a checkpointer is configured when compiling a TypeScript LangGraph that uses interrupts. `MemorySaver` is a common choice. ```typescript // WRONG const graph = builder.compile(); // CORRECT const graph = builder.compile({ checkpointer: new MemorySaver() }); ``` -------------------------------- ### Subagents are Stateless (TypeScript Example) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/deep-agents-orchestration/SKILL.md Illustrates that subagents do not retain memory between calls. All necessary information must be provided in a single instruction. ```typescript // WRONG: Subagents don't remember previous calls // task research: Find data // task research: What did you find? // Starts fresh! // CORRECT: Complete instructions upfront // task research: Find data on AI, save to /research/, return summary ``` -------------------------------- ### Correct LangChain Import Paths Source: https://context7.com/langchain-ai/langchain-skills/llms.txt Demonstrates the correct way to import tools and vector stores from dedicated LangChain packages, replacing deprecated import paths. ```python # WRONG: Deprecated import paths from langchain_community.tools.tavily_search import TavilySearchResults from langchain_community.vectorstores import Chroma ``` ```python # CORRECT: Use dedicated packages from langchain_tavily import TavilySearch from langchain_chroma import Chroma ``` -------------------------------- ### Local Development with FilesystemBackend (Python) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/deep-agents-memory/SKILL.md Use FilesystemBackend for local development to enable direct disk access. Configure `root_dir` for the base directory and `virtual_mode=True` to restrict access to that directory. Set `interrupt_on` to enable human-in-the-loop for file operations. ```python from deepagents import create_deep_agent from deepagents.backends import FilesystemBackend from langgraph.checkpoint.memory import MemorySaver agent = create_deep_agent( backend=FilesystemBackend(root_dir=".", virtual_mode=True), # Restrict access interrupt_on={"write_file": True, "edit_file": True}, checkpointer=MemorySaver() ) ``` -------------------------------- ### Model-Level Structured Output with Zod Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langchain-fundamentals/SKILL.md Use withStructuredOutput with Zod schemas in TypeScript to get typed, validated responses directly from a model. ```typescript import { ChatOpenAI } from "@langchain/openai"; import { z } from "zod"; const ContactInfo = z.object({ name: z.string(), email: z.string().email(), phone: z.string().describe("Phone number with area code"), }); // Model-level structured output const model = new ChatOpenAI({ model: "gpt-4.1" }); const structuredModel = model.withStructuredOutput(ContactInfo); const response = await structuredModel.invoke("Extract: John, john@example.com, 555-1234"); // { name: 'John', email: 'john@example.com', phone: '555-1234' } ``` -------------------------------- ### Create an Agent with RAG Tool (Python) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langchain-rag/SKILL.md Integrate RAG functionality into an agent by defining a tool that searches documentation. This allows the agent to answer questions using retrieved information. ```python from langchain.agents import create_agent from langchain.tools import tool @tool def search_docs(query: str) -> str: """Search documentation for relevant information.""" docs = retriever.invoke(query) return "\n\n".join([d.page_content for d in docs]) agent = create_agent( model="gpt-4.1", tools=[search_docs], ) result = agent.invoke({ "messages": [{"role": "user", "content": "How do I create an agent?"}] }) ``` -------------------------------- ### Configure a Deep Agent with Full Options (Python) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/deep-agents-core/SKILL.md Instantiate a Deep Agent with comprehensive configuration, including custom tools, subagents, filesystem backend, interrupt settings, skills directories, and memory/store persistence. ```python from deepagents import create_deep_agent from deepagents.backends import FilesystemBackend from langgraph.checkpoint.memory import MemorySaver from langgraph.store.memory import InMemoryStore agent = create_deep_agent( name="my-assistant", model="claude-sonnet-4-5-20250929", tools=[custom_tool1, custom_tool2], system_prompt="Custom instructions", subagents=[research_agent, code_agent], backend=FilesystemBackend(root_dir=".", virtual_mode=True), interrupt_on={"write_file": True}, skills=["./skills/"], checkpointer=MemorySaver(), store=InMemoryStore() ) ``` -------------------------------- ### Correct Checkpointer Requirement for HITL (TypeScript) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/deep-agents-orchestration/SKILL.md A checkpointer is mandatory when using interruptOn for human-in-the-loop (HITL) workflows. The 'CORRECT' example shows the proper initialization. ```typescript // WRONG const agent = await createDeepAgent({ interruptOn: { write_file: true } }); // CORRECT const agent = await createDeepAgent({ interruptOn: { write_file: true }, checkpointer: new MemorySaver() }); ``` -------------------------------- ### Correct Checkpointer Requirement for HITL (Python) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/deep-agents-orchestration/SKILL.md A checkpointer is mandatory when using interrupt_on for human-in-the-loop (HITL) workflows. The 'CORRECT' example shows the proper initialization. ```python # WRONG agent = create_deep_agent(interrupt_on={"write_file": True}) # CORRECT agent = create_deep_agent(interrupt_on={"write_file": True}, checkpointer=MemorySaver()) ``` -------------------------------- ### Use Langchain as an Agent Tool Source: https://context7.com/langchain-ai/langchain-skills/llms.txt Demonstrates how to use a Python function as a tool for a Langchain agent. Ensure the retriever is properly initialized. ```python from langchain.agents import tool from langchain.agents import create_agent @tool def search_docs(query: str) -> str: """Search project documentation for relevant information.""" docs = retriever.invoke(query) return "\n\n".join([d.page_content for d in docs]) agent = create_agent(model="gpt-4.1", tools=[search_docs]) result = agent.invoke({"messages": [{"role": "user", "content": "How do I create an agent?"}]}) print(result["messages"][-1].content) ``` -------------------------------- ### Verify Python Version for Langchain 1.0+ Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langchain-dependencies/SKILL.md LangChain 1.0 and later require Python 3.10 or higher. Verify your Python version before installation to ensure compatibility. ```python # Verify before installing import sys assert sys.version_info >= (3, 10), "Python 3.10+ required for LangChain 1.0" ``` -------------------------------- ### Python Agent Creation with Tools and Persistence Source: https://context7.com/langchain-ai/langchain-skills/llms.txt Creates a basic LangChain agent in Python using `create_agent`. Includes a tool definition, memory checkpointer, and demonstrates multi-turn conversation with persistent memory. ```python # Python — basic agent with tool, persistence, and recursion guard from langchain.agents import create_agent from langchain_core.tools import tool from langgraph.checkpoint.memory import MemorySaver from pydantic import BaseModel, Field @tool def get_weather(location: str) -> str: """Get current weather for a location. Args: location: City name (e.g. 'Paris') """ return f"Weather in {location}: Sunny, 72°F" class ContactInfo(BaseModel): name: str email: str phone: str = Field(description="Phone number with area code") checkpointer = MemorySaver() agent = create_agent( model="anthropic:claude-sonnet-4-5", # or ChatAnthropic(model="...", temperature=0) tools=[get_weather], system_prompt="You are a helpful assistant.", checkpointer=checkpointer, # response_format=ContactInfo, # optional: structured output # middleware=[HumanInTheLoopMiddleware(...)] ) config = {"configurable": {"thread_id": "user-123"}} # Multi-turn conversation with persistent memory agent.invoke({"messages": [{"role": "user", "content": "My name is Alice"}]}, config=config) result = agent.invoke( {"messages": [{"role": "user", "content": "What's the weather in Paris?"}]}, config=config, # Prevent runaway loops: # config={**config, "recursion_limit": 10}, ) print(result["messages"][-1].content) # Access last message, NOT result.content ``` -------------------------------- ### Create and Reload FAISS Vector Store (TypeScript) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langchain-rag/SKILL.md Create a FAISS vector store, save it to disk, and reload it. Requires FaissStore. ```typescript import { FaissStore } from "@langchain/community/vectorstores/faiss"; const vectorstore = await FaissStore.fromDocuments(splits, embeddings); await vectorstore.save("./faiss_index"); const loaded = await FaissStore.load("./faiss_index", embeddings); ``` -------------------------------- ### Configure CompositeBackend for Hybrid Storage (Python) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/deep-agents-memory/SKILL.md Configure CompositeBackend to route different file paths to different storage backends, mixing ephemeral and persistent storage. ```python from deepagents import create_deep_agent from deepagents.backends import CompositeBackend, StateBackend, StoreBackend from langgraph.store.memory import InMemoryStore store = InMemoryStore() composite_backend = lambda rt: CompositeBackend( default=StateBackend(rt), routes={"/memories/": StoreBackend(rt)} ) agent = create_deep_agent(backend=composite_backend, store=store) # /draft.txt -> ephemeral (StateBackend) # /memories/user-prefs.txt -> persistent (StoreBackend) ``` -------------------------------- ### Create and Reload FAISS Vector Store Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langchain-rag/SKILL.md Create a FAISS vector store, save it to disk, and reload it. Requires FAISS. ```python from langchain_community.vectorstores import FAISS vectorstore = FAISS.from_documents(splits, embeddings) vectorstore.save_local("./faiss_index") # Load (requires allow_dangerous_deserialization) loaded = FAISS.load_local( "./faiss_index", embeddings, allow_dangerous_deserialization=True ) ``` -------------------------------- ### Interrupts Occur Between Invocation Calls (Python) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/deep-agents-orchestration/SKILL.md Interrupts are detected between 'invoke()' calls, not during the execution of a single call. The example shows the pattern of invoking, checking for interrupts, and then resuming. ```python result = agent.invoke({...}, config=config) # Step 1: triggers interrupt if "__interrupt__" in result: # Step 2: check for interrupt result = agent.invoke( # Step 3: resume Command(resume={"decisions": [{"type": "approve"}]}), config=config, ) ``` -------------------------------- ### Langgraph: Stateful Graphs with Nodes and Edges (Python) Source: https://context7.com/langchain-ai/langchain-skills/llms.txt Builds a stateful graph using Langgraph, demonstrating state schema design, node implementation, and wiring edges. Nodes should return partial state updates. ```python # Python — orchestrator/worker fan-out with conditional routing and streaming from langgraph.graph import StateGraph, START, END from langgraph.types import Command, Send, RetryPolicy from langgraph.prebuilt import ToolNode from typing_extensions import TypedDict, Annotated, Literal import operator class State(TypedDict): query: str route: str tasks: list[str] results: Annotated[list, operator.add] # Reducer required for parallel workers summary: str # Nodes return PARTIAL dicts — never mutate and return full state def classify(state: State) -> Command[Literal["weather", "general"]]: """Classify and route in a single node using Command.""" if "weather" in state["query"].lower(): return Command(update={"route": "weather"}, goto="weather") return Command(update={"route": "general"}, goto="general") def orchestrator(state: State): """Fan-out tasks to parallel workers via Send.""" return [Send("worker", {"task": task}) for task in state["tasks"]] def worker(state: dict) -> dict: return {"results": [f"Done: {state['task']}"]} def synthesize(state: State) -> dict: return {"summary": f"Completed {len(state['results'])} tasks"} graph = ( StateGraph(State) .add_node("classify", classify, ends=["weather", "general"]) .add_node("weather", lambda s: {"results": ["Sunny, 72°F"]}) .add_node("general", lambda s: {"results": ["General answer"]}) .add_node("worker", worker, retry_policy=RetryPolicy(max_attempts=3, initial_interval=1.0)) .add_node("synthesize", synthesize) .add_edge(START, "classify") .add_edge("weather", END) .add_edge("general", END) .add_conditional_edges(START, orchestrator, ["worker"]) .add_edge("worker", "synthesize") .add_edge("synthesize", END) .compile() ) # Invoke result = graph.invoke({"query": "weather", "tasks": ["A", "B", "C"]}) ``` -------------------------------- ### Create and Invoke a Basic Deep Agent (Python) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/deep-agents-core/SKILL.md Use `create_deep_agent` to instantiate a basic agent with custom tools and a system prompt. Invoke the agent with user messages and configuration, including a thread ID for state management. ```python from deepagents import create_deep_agent from langchain.tools import tool @tool def get_weather(city: str) -> str: """Get the weather for a given city.""" return f"It is always sunny in {city}" agent = create_deep_agent( model="claude-sonnet-4-5-20250929", tools=[get_weather], system_prompt="You are a helpful assistant" ) config = {"configurable": {"thread_id": "user-123"}} result = agent.invoke({ "messages": [{"role": "user", "content": "What's the weather in Tokyo?"}] }, config=config) ``` -------------------------------- ### Reject Action with Feedback (TypeScript) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/deep-agents-orchestration/SKILL.md Reject a pending action and provide feedback to guide the agent towards a different approach. This requires the 'resume' command with a 'reject' decision. ```typescript const result = await agent.invoke( new Command({ resume: { decisions: [{ type: "reject", message: "Run tests first" }] } }), config, ); ``` -------------------------------- ### Use FilesystemBackend for Local Development Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/deep-agents-memory/SKILL.md Utilize FilesystemBackend for local development to enable real disk access and human-in-the-loop operations. Ensure security by not using this in web servers. ```typescript import { createDeepAgent, FilesystemBackend } from "deepagents"; import { MemorySaver } from "@langchain/langgraph"; const agent = await createDeepAgent({ backend: new FilesystemBackend({ rootDir: ".", virtualMode: true }), interruptOn: { write_file: true, edit_file: true }, checkpointer: new MemorySaver() }); ``` -------------------------------- ### Configure Agent with Model Instance Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langchain-fundamentals/SKILL.md Pass model instances to create_agent for custom model configurations, such as setting the temperature. ```python from langchain_anthropic import ChatAnthropic agent = create_agent(model=ChatAnthropic(model="claude-sonnet-4-5", temperature=0), tools=[...]) ``` -------------------------------- ### Reject Action with Feedback (Python) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/deep-agents-orchestration/SKILL.md Reject a pending action and provide feedback to guide the agent towards a different approach. This requires the 'resume' command with a 'reject' decision. ```python result = agent.invoke( Command(resume={"decisions": [{"type": "reject", "message": "Run tests first"}]}), config=config, ) ``` -------------------------------- ### Create Chroma Vector Store with Server Connection Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langchain-rag/SKILL.md Create a Chroma vector store connected to a running Chroma server. Requires Chroma and OpenAIEmbeddings. ```typescript import { Chroma } from "@langchain/community/vectorstores/chroma"; import { OpenAIEmbeddings } from "@langchain/openai"; const vectorstore = await Chroma.fromDocuments( splits, new OpenAIEmbeddings(), { collectionName: "my-collection", url: "http://localhost:8000" } ); ``` -------------------------------- ### Ensure Thread ID for Resuming Interrupted Workflows (TypeScript) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/deep-agents-orchestration/SKILL.md A consistent thread_id is essential for resuming interrupted workflows. The 'CORRECT' example demonstrates how to invoke with and resume using the same configuration. ```typescript // WRONG: Can't resume without thread_id await agent.invoke({ messages: [...] }); // CORRECT const config = { configurable: { thread_id: "session-1" } }; await agent.invoke({ messages: [...] }, config); // Resume with Command using same config await agent.invoke(new Command({ resume: { decisions: [{ type: "approve" }] } }), config); ``` -------------------------------- ### Correct Agent Configuration for StoreBackend (Python) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/deep-agents-core/SKILL.md Ensures StoreBackend functions correctly by providing a Store instance for persistent memory. ```python # WRONG agent = create_deep_agent(backend=lambda rt: StoreBackend(rt)) # CORRECT agent = create_deep_agent(backend=lambda rt: StoreBackend(rt), store=InMemoryStore()) ``` -------------------------------- ### Use Persistent Storage (PostgresSaver) for Production Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langgraph-persistence/SKILL.md For production environments, use a persistent storage solution like `PostgresSaver` instead of `InMemorySaver`. `InMemorySaver` will lose all data when the process restarts. ```python # WRONG: Data lost on process restart checkpointer = InMemorySaver() # In-memory only! # CORRECT: Use persistent storage for production from langgraph.checkpoint.postgres import PostgresSaver with PostgresSaver.from_conn_string("postgresql://...") as checkpointer: checkpointer.setup() # only needed on first use to create tables graph = builder.compile(checkpointer=checkpointer) ``` -------------------------------- ### Ensure Thread ID for Resuming Interrupted Workflows (Python) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/deep-agents-orchestration/SKILL.md A consistent thread_id is essential for resuming interrupted workflows. The 'CORRECT' example demonstrates how to invoke with and resume using the same configuration. ```python # WRONG: Can't resume without thread_id agent.invoke({"messages": [...]}) # CORRECT config = {"configurable": {"thread_id": "session-1"}} agent.invoke({...}, config=config) # Resume with Command using same config agent.invoke(Command(resume={"decisions": [{"type": "approve"}]}), config=config) ``` -------------------------------- ### Composite Backend Longest Prefix Match in Python Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/deep-agents-memory/SKILL.md CompositeBackend prioritizes matching the longest prefix first. This example demonstrates how different routes are matched based on their prefix length. ```python routes = {"/mem/": StoreBackend(rt), "/mem/temp/": StateBackend(rt)} # /mem/file.txt -> StoreBackend, /mem/temp/file.txt -> StateBackend (longer match) ``` -------------------------------- ### Use PostgresStore for Production Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/deep-agents-memory/SKILL.md For production environments, it is recommended to use PostgresStore instead of InMemoryStore, as InMemoryStore data is lost upon restart. ```python # Use PostgresStore for production (InMemoryStore lost on restart). ``` -------------------------------- ### Custom Subagents Do Not Inherit Skills (Python Example) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/deep-agents-orchestration/SKILL.md Custom subagents do not automatically inherit the skills configured for the main agent. Skills must be explicitly provided for custom subagents. ```python # WRONG: Custom subagent won't have main agent's skills agent = create_deep_agent( skills=["/main-skills/"], subagents=[{"name": "helper", ...}] # No skills inherited ) # CORRECT: Provide skills explicitly (general-purpose subagent DOES inherit) agent = create_deep_agent( skills=["/main-skills/"], subagents=[{"name": "helper", "skills": ["/helper-skills/"], ...}] ) ``` -------------------------------- ### Create an Agent with RAG Tool (TypeScript) Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langchain-rag/SKILL.md Integrate RAG functionality into an agent using TypeScript. Define a tool that searches documentation, enabling the agent to answer questions with retrieved context. ```typescript import { createAgent } from "langchain"; import { tool } from "@langchain/core/tools"; import { z } from "zod"; const searchDocs = tool( async (input) => { const docs = await retriever.invoke(input.query); return docs.map(d => d.pageContent).join("\n\n"); }, { name: "search_docs", description: "Search documentation for relevant information.", schema: z.object({ query: z.string() }), } ); const agent = createAgent({ model: "gpt-4.1", tools: [searchDocs], }); const result = await agent.invoke({ messages: [{ role: "user", content: "How do I create an agent?" }], }); ``` -------------------------------- ### Accumulate parallel worker results in TypeScript Source: https://github.com/langchain-ai/langchain-skills/blob/main/config/skills/langgraph-fundamentals/SKILL.md Shows the correct use of ReducedValue for accumulating parallel worker results. The incorrect example illustrates the issue of results being overwritten without a reducer. ```typescript // WRONG: No reducer const State = new StateSchema({ results: z.array(z.string()) }); // CORRECT const State = new StateSchema({ results: new ReducedValue(z.array(z.string()).default(() => []), { reducer: (curr, upd) => curr.concat(upd) }), }); ```