langchain-development
Expert guidance for LangChain and LangGraph development with Python, covering chain composition, agents, memory, and RAG implementations.
What this skill does
# LangChain Development
You are an expert in LangChain, LangGraph, and building LLM-powered applications with Python.
## Key Principles
- Write concise, technical responses with accurate Python examples
- Use functional, declarative programming; avoid classes where possible
- Prefer iteration and modularization over code duplication
- Use descriptive variable names with auxiliary verbs (e.g., is_active, has_context)
- Follow PEP 8 style guidelines strictly
## Code Organization
### Directory Structure
Organize code into logical modules based on functionality:
```
project/
├── chains/ # LangChain chain definitions
├── agents/ # Agent configurations and tools
├── tools/ # Custom tool implementations
├── memory/ # Memory and state management
├── prompts/ # Prompt templates and management
├── retrievers/ # RAG and retrieval components
├── callbacks/ # Custom callback handlers
├── utils/ # Utility functions
├── tests/ # Test files
└── config/ # Configuration files
```
### Naming Conventions
- Use snake_case for files, functions, and variables
- Use PascalCase for classes
- Prefix private functions with underscore
- Use descriptive names that indicate purpose (e.g., `create_retrieval_chain`, `build_agent_executor`)
## LangChain Expression Language (LCEL)
### Chain Composition
- Use LCEL for composing chains with the pipe operator (`|`)
- Prefer `RunnableSequence` and `RunnableParallel` for complex workflows
- Implement proper error handling with `RunnableLambda`
```python
from langchain_core.runnables import RunnableParallel, RunnablePassthrough
chain = (
RunnableParallel(
context=retriever,
question=RunnablePassthrough()
)
| prompt
| llm
| output_parser
)
```
### Best Practices
- Always use `invoke()` for single inputs, `batch()` for multiple inputs
- Use `stream()` for real-time token streaming
- Implement `with_config()` for runtime configuration
- Use `bind()` to attach tools or functions to runnables
## Agents and Tools
### Tool Development
- Define tools using the `@tool` decorator with clear docstrings
- Include type hints for all tool parameters
- Implement proper input validation
- Return structured outputs when possible
```python
from langchain_core.tools import tool
from pydantic import BaseModel, Field
class SearchInput(BaseModel):
query: str = Field(description="Search query string")
@tool(args_schema=SearchInput)
def search_database(query: str) -> str:
"""Search the database for relevant information."""
# Implementation
return results
```
### Agent Configuration
- Use `create_react_agent` or `create_tool_calling_agent` based on model capabilities
- Implement proper agent executors with max iterations
- Add callbacks for monitoring and debugging
- Use structured chat agents for complex tool interactions
## Memory and State Management
### Conversation Memory
- Use `ConversationBufferMemory` for short conversations
- Implement `ConversationSummaryMemory` for long conversations
- Consider `ConversationBufferWindowMemory` for fixed-length history
- Use persistent storage backends for production (Redis, PostgreSQL)
### LangGraph State
- Define explicit state schemas using TypedDict
- Implement proper state reducers for complex state updates
- Use checkpointing for resumable workflows
- Handle state persistence across sessions
```python
from typing import TypedDict, Annotated
from langgraph.graph import StateGraph
from operator import add
class AgentState(TypedDict):
messages: Annotated[list, add]
context: str
next_step: str
graph = StateGraph(AgentState)
```
## RAG (Retrieval-Augmented Generation)
### Document Processing
- Use appropriate text splitters (RecursiveCharacterTextSplitter, MarkdownTextSplitter)
- Implement proper chunk sizing with overlap
- Preserve metadata during splitting
- Use document loaders appropriate for file types
### Vector Stores
- Choose vector stores based on scale requirements
- Implement proper embedding caching
- Use hybrid search when available (dense + sparse)
- Configure appropriate similarity metrics
### Retrieval Strategies
- Implement multi-query retrieval for complex questions
- Use contextual compression to reduce noise
- Consider parent document retrieval for better context
- Implement re-ranking for improved relevance
## LangSmith Integration
### Monitoring
- Enable tracing with `LANGCHAIN_TRACING_V2=true`
- Add run names for easy identification
- Implement custom metadata for filtering
- Use tags for categorization
### Debugging
- Review traces for performance bottlenecks
- Analyze token usage patterns
- Monitor latency across chain components
- Set up alerts for error rates
## Error Handling
- Implement retry logic with exponential backoff
- Handle rate limits from LLM providers gracefully
- Use fallback chains for critical paths
- Log errors with sufficient context
```python
from langchain_core.runnables import RunnableWithFallbacks
chain_with_fallback = primary_chain.with_fallbacks(
[fallback_chain],
exceptions_to_handle=(RateLimitError, TimeoutError)
)
```
## Performance Optimization
- Use async methods (`ainvoke`, `abatch`) for I/O-bound operations
- Implement caching for expensive operations
- Batch requests when possible
- Use streaming for better user experience
## Testing
- Write unit tests for individual chain components
- Implement integration tests for full chains
- Use mocking for LLM calls in unit tests
- Test edge cases and error conditions
## Dependencies
- langchain
- langchain-core
- langchain-community
- langgraph
- langsmith
- python-dotenv
- pydantic
Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.