Skill站外收录 @skilllib/skill-2014279401716789251
langchain-common-errors
诊断并解决 LangChain 使用中的常见错误,涵盖认证失败、导入异常、速率限制、输出解析失败及链与代理执行问题,提供环境配置、版本兼容性检查和调试追踪等系统性排查方法,帮助快速定位并修复集成过程中的技术障碍。
数据与分析 AI 技能
Skills.MD
# LangChain Common Errors
## Overview
Quick reference for diagnosing and resolving the most common LangChain errors.
## Prerequisites
- LangChain installed and configured
- Access to application logs
- Understanding of your LangChain implementation
## Error Reference
### Authentication Errors
#### `openai.AuthenticationError: Incorrect API key provided`
```python
# Cause: Invalid or missing API key
# Solution:
import os
os.environ["OPENAI_API_KEY"] = "sk-..." # Set correct key
# Verify key is loaded
from langchain_openai import ChatOpenAI
llm = ChatOpenAI() # Will raise error if key invalid
```
#### `anthropic.AuthenticationError: Invalid x-api-key`
```python
# Cause: Anthropic API key not set or invalid
# Solution:
os.environ["ANTHROPIC_API_KEY"] = "sk-ant-..."
# Or pass directly
from langchain_anthropic import ChatAnthropic
llm = ChatAnthropic(api_key="sk-ant-...")
```
### Import Errors
#### `ModuleNotFoundError: No module named 'langchain_openai'`
```bash
# Cause: Provider package not installed
# Solution:
pip install langchain-openai
# For other providers:
pip install langchain-anthropic
pip install langchain-google-genai
pip install langchain-community
```
#### `ImportError: cannot import name 'ChatOpenAI' from 'langchain'`
```python
# Cause: Using old import path (pre-0.2.0)
# Old (deprecated):
from langchain.chat_models import ChatOpenAI
# New (correct):
from langchain_openai import ChatOpenAI
```
### Rate Limiting
#### `openai.RateLimitError: Rate limit reached`
```python
# Cause: Too many API requests
# Solution: Implement retry with backoff
from langchain_openai import ChatOpenAI
from tenacity import retry, wait_exponential, stop_after_attempt
@retry(wait=wait_exponential(min=1, max=60), stop=stop_after_attempt(5))
def call_with_retry(llm, prompt):
return llm.invoke(prompt)
# Or use LangChain's built-in retry
llm = ChatOpenAI(max_retries=3)
```
### Output Parsing Errors
#### `OutputParserException: Failed to parse output`
```python
# Cause: LLM output doesn't match expected format
# Solution 1: Use with_retry
from langchain.output_parsers import RetryOutputParser
parser = RetryOutputParser.from_llm(parser=your_parser, llm=llm)
# Solution 2: Use structured output (more reliable)
from pydantic import BaseModel
class Output(BaseModel):
answer: str
llm_with_structure = llm.with_structured_output(Output)
```
#### `ValidationError: field required`
```python
# Cause: Pydantic model validation failed
# Solution: Make fields optional or provide defaults
from pydantic import BaseModel, Field
from typing import Optional
class Output(BaseModel):
answer: str
confidence: Optional[float] = Field(default=None)
```
### Chain Errors
#### `ValueError: Missing required input keys`
```python
# Cause: Input dict missing required variables
# Debug:
prompt = ChatPromptTemplate.from_template("Hello {name}, you are {age}")
print(prompt.input_variables) # ['name', 'age']
# Solution: Provide all required keys
chain.invoke({"name": "Alice", "age": 30})
```
#### `TypeError: Expected mapping type as input`
```python
# Cause: Passing wrong input type
# Wrong:
chain.invoke("hello")
# Correct:
chain.invoke({"input": "hello"})
```
### Agent Errors
#### `AgentExecutor: max iterations reached`
```python
# Cause: Agent stuck in loop
# Solution: Increase iterations or improve prompts
agent_executor = AgentExecutor(
agent=agent,
tools=tools,
max_iterations=20, # Increase from default 15
early_stopping_method="force" # Force stop after max
)
```
#### `ToolException: Tool execution failed`
```python
# Cause: Tool raised an exception
# Solution: Add error handling in tool
@tool
def my_tool(input: str) -> str:
"""Tool description."""
try:
# Tool logic
return result
except Exception as e:
return f"Tool error: {str(e)}"
```
### Memory Errors
#### `KeyError: 'chat_history'`
```python
# Cause: Memory key mismatch
# Solution: Ensure consistent key names
prompt = ChatPromptTemplate.from_messages([
MessagesPlaceholder(variable_name="chat_history"), # Match this
("human", "{input}")
])
# When invoking:
chain.invoke({
"input": "hello",
"chat_history": [] # Must match placeholder name
})
```
## Debugging Tips
### Enable Verbose Mode
```python
import langchain
langchain.debug = True # Shows all chain steps
# Or per-component
agent_executor = AgentExecutor(verbose=True)
```
### Trace with LangSmith
```python
# Set environment variables
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_API_KEY"] = "your-langsmith-key"
os.environ["LANGCHAIN_PROJECT"] = "my-project"
# All chains automatically traced
```
### Check Version Compatibility
```bash
pip show langchain langchain-core langchain-openai
# Ensure versions are compatible:
# langchain >= 0.3.0
# langchain-core >= 0.3.0
# langchain-openai >= 0.2.0
```
## Resources
- [LangChain Troubleshooting](https://python.langchain.com/docs/troubleshooting/)
- [LangSmith Debugging](https://docs.smith.langchain.com/)
- [GitHub Issues](https://github.com/langchain-ai/langchain/issues)
## Next Steps
For complex debugging, use `langchain-debug-bundle` to collect evidence.
评论 0
还没有评论,来抢沙发。
相关内容
同类或同场景的收录内容
building-with-kafka-strimzi
在 Kubernetes 上构建基于 Apache Kafka 的事件驱动系统,支持高可靠的消息传递、事务性处理与精确一次语义,结合 Strimzi 运营商实现集群自动化管理,利用 Schema Registry 保障事件模式演进,适用于微服务间解耦通信与实时数据流处理场景。
站外数据与分析
609 0.0
personal-tool-builder
专注于从个人真实痛点出发快速构建实用工具,涵盖命令行程序、本地优先应用和自动化脚本的开发与演进,强调先满足自身需求再逐步扩展,通过持续自用打磨功能,避免过度设计,确保工具简洁有效且长期可维护。
站外商业与营销
196 0.0
threejs-lighting
实现三维场景中的光照与阴影控制,支持多种光源类型及环境光照明,提供从基础布光到高级阴影优化的完整方案,适用于需要真实感渲染或性能平衡的可视化项目。
站外效率工具
442 0.0
aggregation-helper
提供数据聚合场景的自动化辅助能力,涵盖 SQL 查询编写、统计分析建模、可视化方案设计及商业智能配置,支持从需求理解到生产级代码生成的全流程指导。
站外效率工具数据与分析
217 0.0
举报「langchain-common-errors」
举报信息仅审核团队可见,同一资产 24 小时内仅可举报一次