langchain-common-errors

4
0
Source

Diagnose and fix common LangChain errors and exceptions. Use when encountering LangChain errors, debugging failures, or troubleshooting integration issues. Trigger with phrases like "langchain error", "langchain exception", "debug langchain", "langchain not working", "langchain troubleshoot".

Install

mkdir -p .claude/skills/langchain-common-errors && curl -L -o skill.zip "https://mcp.directory/api/skills/download/3824" && unzip -o skill.zip -d .claude/skills/langchain-common-errors && rm skill.zip

Installs to .claude/skills/langchain-common-errors

About this skill

LangChain Common Errors

Overview

Quick reference for the most frequent LangChain errors with exact error messages, root causes, and copy-paste fixes.

Import Errors

Cannot find module '@langchain/openai'

# Provider package not installed
npm install @langchain/openai
# Also: @langchain/anthropic, @langchain/google-genai, @langchain/community

Cannot import name 'ChatOpenAI' from 'langchain' (Python)

# Old import path (pre-0.2). Use provider packages:
# OLD: from langchain.chat_models import ChatOpenAI
# NEW:
from langchain_openai import ChatOpenAI

@langchain/core version mismatch

# All @langchain/* packages must share the same minor version
npm ls @langchain/core
# Fix: update all together
npm install @langchain/core@latest @langchain/openai@latest @langchain/anthropic@latest

Authentication Errors

AuthenticationError: Incorrect API key provided

// Key not set or wrong format
// Check:
console.log("Key present:", !!process.env.OPENAI_API_KEY);
console.log("Key prefix:", process.env.OPENAI_API_KEY?.slice(0, 7));
// Should be "sk-..." for OpenAI, "sk-ant-..." for Anthropic

// Fix: ensure dotenv is loaded BEFORE imports
import "dotenv/config";
import { ChatOpenAI } from "@langchain/openai";

Error: OPENAI_API_KEY is not set

// Model constructor can't find the key
// Option 1: environment variable
process.env.OPENAI_API_KEY = "sk-...";

// Option 2: pass directly (not recommended for production)
const model = new ChatOpenAI({
  model: "gpt-4o-mini",
  apiKey: "sk-...",
});

Chain Errors

Missing value for input variable "topic"

// Template has variables not provided in invoke()
const prompt = ChatPromptTemplate.fromTemplate("Tell me about {topic} in {language}");
console.log(prompt.inputVariables); // ["topic", "language"]

// Fix: provide ALL variables
await chain.invoke({ topic: "AI", language: "English" }); // not just { topic: "AI" }

Expected mapping type as input to ChatPromptTemplate

// Passing a string instead of an object
// WRONG:
await chain.invoke("hello");

// RIGHT:
await chain.invoke({ input: "hello" });

Output Parsing Errors

OutputParserException: Failed to parse

// LLM output doesn't match expected format
// Fix 1: Use withStructuredOutput (most reliable)
import { z } from "zod";

const schema = z.object({
  answer: z.string(),
  confidence: z.number().optional(), // make fields optional for resilience
});
const structuredModel = model.withStructuredOutput(schema);

// Fix 2: Add retry parser (Python)
// from langchain.output_parsers import RetryWithErrorOutputParser
// retry_parser = RetryWithErrorOutputParser.from_llm(parser=parser, llm=llm)

ZodError: validation failed

// Structured output doesn't match Zod schema
// Fix: make optional fields nullable, add defaults
const Schema = z.object({
  answer: z.string(),
  confidence: z.number().min(0).max(1).default(0.5),
  sources: z.array(z.string()).default([]),
});

Agent Errors

AgentExecutor: max iterations reached

// Agent stuck in a tool-calling loop
const executor = new AgentExecutor({
  agent,
  tools,
  maxIterations: 15,          // increase from default 10
  earlyStoppingMethod: "force", // force stop instead of error
});

// Root cause: usually a vague system prompt. Be specific about when to stop.

Missing placeholder 'agent_scratchpad'

// Agent prompt MUST include the scratchpad placeholder
const prompt = ChatPromptTemplate.fromMessages([
  ["system", "You are helpful."],
  ["human", "{input}"],
  new MessagesPlaceholder("agent_scratchpad"),  // REQUIRED
]);

Rate Limiting

429 Too Many Requests / RateLimitError

// Built-in retry handles this automatically
const model = new ChatOpenAI({
  model: "gpt-4o-mini",
  maxRetries: 5,    // exponential backoff on 429
});

// For batch processing, control concurrency
const results = await chain.batch(inputs, { maxConcurrency: 5 });

Memory/History Errors

KeyError: 'chat_history'

// MessagesPlaceholder name must match invoke key
const prompt = ChatPromptTemplate.fromMessages([
  new MessagesPlaceholder("chat_history"),  // this name...
  ["human", "{input}"],
]);

await chain.invoke({
  input: "hello",
  chat_history: [],  // ...must match this key
});

Debugging Toolkit

Enable Debug Logging

// See every step in chain execution
import { setVerbose } from "@langchain/core";
setVerbose(true);  // logs all chain steps

// Python equivalent:
// import langchain; langchain.debug = True

Enable LangSmith Tracing

# Add to .env — all chains automatically traced
LANGSMITH_TRACING=true
LANGSMITH_API_KEY=lsv2_...
LANGSMITH_PROJECT=my-debug-session

Check Version Compatibility

# All @langchain/* packages should be on compatible versions
npm ls @langchain/core 2>&1 | head -20

# Python
pip show langchain langchain-core langchain-openai | grep -E "Name|Version"

Quick Diagnostic Script

import "dotenv/config";

async function diagnose() {
  const checks: Record<string, string> = {};

  // Check env vars
  checks["OPENAI_API_KEY"] = process.env.OPENAI_API_KEY ? "set" : "MISSING";
  checks["ANTHROPIC_API_KEY"] = process.env.ANTHROPIC_API_KEY ? "set" : "MISSING";

  // Check imports
  try {
    await import("@langchain/core");
    checks["@langchain/core"] = "OK";
  } catch { checks["@langchain/core"] = "MISSING"; }

  try {
    const { ChatOpenAI } = await import("@langchain/openai");
    const llm = new ChatOpenAI({ model: "gpt-4o-mini" });
    await llm.invoke("test");
    checks["OpenAI connection"] = "OK";
  } catch (e: any) {
    checks["OpenAI connection"] = e.message.slice(0, 80);
  }

  console.table(checks);
}

await diagnose();

Resources

Next Steps

For complex debugging, use langchain-debug-bundle to collect comprehensive evidence.

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

6814

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

2312

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

379

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

978

performing-security-audits

jeremylongshore

This skill allows Claude to conduct comprehensive security audits of code, infrastructure, and configurations. It leverages various tools within the security-pro-pack plugin, including vulnerability scanning, compliance checking, cryptography review, and infrastructure security analysis. Use this skill when a user requests a "security audit," "vulnerability assessment," "compliance review," or any task involving identifying and mitigating security risks. It helps to ensure code and systems adhere to security best practices and compliance standards.

86

django-view-generator

jeremylongshore

Generate django view generator operations. Auto-activating skill for Backend Development. Triggers on: django view generator, django view generator Part of the Backend Development skill category. Use when working with django view generator functionality. Trigger with phrases like "django view generator", "django generator", "django".

15

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.

643969

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.

591705

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."

318398

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.

339397

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.

451339

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

304231

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.