langchain-sdk-patterns
Apply production-ready LangChain SDK patterns for chains, agents, and memory. Use when implementing LangChain integrations, refactoring code, or establishing team coding standards for LangChain applications. Trigger with phrases like "langchain SDK patterns", "langchain best practices", "langchain code patterns", "idiomatic langchain", "langchain architecture".
Install
mkdir -p .claude/skills/langchain-sdk-patterns && curl -L -o skill.zip "https://mcp.directory/api/skills/download/8638" && unzip -o skill.zip -d .claude/skills/langchain-sdk-patterns && rm skill.zipInstalls to .claude/skills/langchain-sdk-patterns
About this skill
LangChain SDK Patterns
Overview
Production-grade patterns every LangChain application should use: type-safe structured output, provider fallbacks, async batch processing, streaming, caching, and retry logic.
Pattern 1: Structured Output with Zod
import { ChatOpenAI } from "@langchain/openai";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { z } from "zod";
const ExtractedData = z.object({
entities: z.array(z.object({
name: z.string(),
type: z.enum(["person", "org", "location"]),
confidence: z.number().min(0).max(1),
})),
language: z.string(),
summary: z.string(),
});
const model = new ChatOpenAI({ model: "gpt-4o-mini" });
const structuredModel = model.withStructuredOutput(ExtractedData);
const prompt = ChatPromptTemplate.fromTemplate(
"Extract entities from this text:\n\n{text}"
);
const chain = prompt.pipe(structuredModel);
const result = await chain.invoke({
text: "Satya Nadella announced Microsoft's new AI lab in Seattle.",
});
// result is fully typed: { entities: [...], language: "en", summary: "..." }
Pattern 2: Provider Fallbacks
import { ChatOpenAI } from "@langchain/openai";
import { ChatAnthropic } from "@langchain/anthropic";
const primary = new ChatOpenAI({
model: "gpt-4o",
maxRetries: 2,
timeout: 10000,
});
const fallback = new ChatAnthropic({
model: "claude-sonnet-4-20250514",
});
// Automatically falls back on any error (rate limit, timeout, 500)
const robustModel = primary.withFallbacks({
fallbacks: [fallback],
});
// Works identically to a normal model
const chain = prompt.pipe(robustModel).pipe(new StringOutputParser());
Pattern 3: Async Batch Processing
import { ChatOpenAI } from "@langchain/openai";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { StringOutputParser } from "@langchain/core/output_parsers";
const chain = ChatPromptTemplate.fromTemplate("Summarize: {text}")
.pipe(new ChatOpenAI({ model: "gpt-4o-mini" }))
.pipe(new StringOutputParser());
const texts = ["Article 1...", "Article 2...", "Article 3..."];
const inputs = texts.map((text) => ({ text }));
// Process all inputs with controlled concurrency
const results = await chain.batch(inputs, {
maxConcurrency: 5, // max 5 parallel API calls
});
// results: string[] — one summary per input
Pattern 4: Streaming with Token Callbacks
import { ChatOpenAI } from "@langchain/openai";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { StringOutputParser } from "@langchain/core/output_parsers";
const chain = ChatPromptTemplate.fromTemplate("{input}")
.pipe(new ChatOpenAI({ model: "gpt-4o-mini", streaming: true }))
.pipe(new StringOutputParser());
// Stream string chunks
const stream = await chain.stream({ input: "Tell me a story" });
for await (const chunk of stream) {
process.stdout.write(chunk); // each chunk is a string fragment
}
Pattern 5: Retry with Exponential Backoff
import { ChatOpenAI } from "@langchain/openai";
// Built-in retry handles transient failures
const model = new ChatOpenAI({
model: "gpt-4o-mini",
maxRetries: 3, // retries with exponential backoff
timeout: 30000, // 30s timeout per request
});
// Manual retry wrapper for custom logic
async function invokeWithRetry<T>(
chain: { invoke: (input: any) => Promise<T> },
input: any,
maxRetries = 3,
): Promise<T> {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await chain.invoke(input);
} catch (error: any) {
if (attempt === maxRetries - 1) throw error;
const delay = Math.min(1000 * 2 ** attempt, 30000);
console.warn(`Retry ${attempt + 1}/${maxRetries} after ${delay}ms`);
await new Promise((r) => setTimeout(r, delay));
}
}
throw new Error("Unreachable");
}
Pattern 6: Caching (Python)
from langchain_openai import ChatOpenAI
from langchain_core.globals import set_llm_cache
from langchain_community.cache import SQLiteCache
# Enable persistent caching — identical inputs skip the API
set_llm_cache(SQLiteCache(database_path=".langchain_cache.db"))
llm = ChatOpenAI(model="gpt-4o-mini")
# First call: hits API (~500ms)
r1 = llm.invoke("What is 2+2?")
# Second identical call: cache hit (~0ms, no cost)
r2 = llm.invoke("What is 2+2?")
Pattern 7: RunnableLambda for Custom Logic
import { RunnableLambda } from "@langchain/core/runnables";
// Wrap any function as a Runnable to use in chains
const cleanInput = RunnableLambda.from((input: { text: string }) => ({
text: input.text.trim().toLowerCase(),
}));
const addMetadata = RunnableLambda.from((result: string) => ({
answer: result,
timestamp: new Date().toISOString(),
model: "gpt-4o-mini",
}));
const chain = cleanInput
.pipe(prompt)
.pipe(model)
.pipe(new StringOutputParser())
.pipe(addMetadata);
Anti-Patterns to Avoid
| Anti-Pattern | Why | Better |
|---|---|---|
| Hardcoded API keys | Security risk | Use env vars + dotenv |
| No error handling | Silent failures | Use .withFallbacks() + try/catch |
| Sequential when parallel works | Slow | Use RunnableParallel or .batch() |
| Parsing raw LLM text | Fragile | Use .withStructuredOutput(zodSchema) |
| No timeout | Hanging requests | Set timeout on model constructor |
| No streaming in UIs | Bad UX | Use .stream() for user-facing output |
Error Handling
| Error | Cause | Fix |
|---|---|---|
ZodError | LLM output doesn't match schema | Improve prompt or relax schema with .optional() |
RateLimitError | API quota exceeded | Add maxRetries, use .withFallbacks() |
TimeoutError | Slow response | Increase timeout, try smaller model |
OutputParserException | Unparseable output | Switch to .withStructuredOutput() |
Resources
Next Steps
Proceed to langchain-data-handling for data privacy patterns.
More by jeremylongshore
View all skills by jeremylongshore →You might also like
flutter-development
aj-geddes
Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.
drawio-diagrams-enhanced
jgtolentino
Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.
ui-ux-pro-max
nextlevelbuilder
"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."
godot
bfollington
This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.
nano-banana-pro
garg-aayush
Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.
pdf-to-markdown
aliceisjustplaying
Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.
Related MCP Servers
Browse all serversSecurely join MySQL databases with Read MySQL for read-only query access and in-depth data analysis.
Context Portal: Manage project memory with a database-backed system for decisions, tracking, and semantic search via a k
EVM Blockchain connects with Ethereum, Optimism, Arbitrum, and Base for token transfers, smart contract data, and ENS na
Dot AI (Kubernetes Deployment) streamlines and automates Kubernetes deployment with intelligent guidance and vector sear
Claude Historian is a free AI search engine offering advanced search, file context, and solution discovery in Claude Cod
Claude Historian: AI-powered search for Claude Code conversations—find files, errors, context, and sessions via JSONL pa
Stay ahead of the MCP ecosystem
Get weekly updates on new skills and servers.