langchain
LangChain is a Python framework for building applications powered by large language models, offering abstractions for working with multiple LLM providers, implementing retrieval-augmented generation pipelines, creating autonomous agents with tool calling, and managing conversation memory. Use it when rapidly prototyping or deploying chatbots, question-answering systems, agents that reason through tasks using the ReAct pattern, or any LLM application requiring flexibility across different model providers and access to hundreds of integrations for vector stores and external tools.
git clone --depth 1 https://github.com/Orchestra-Research/AI-Research-SKILLs /tmp/langchain && cp -r /tmp/langchain/14-agents/langchain ~/.claude/skills/langchainSKILL.md
# LangChain - Build LLM Applications with Agents & RAG
The most popular framework for building LLM-powered applications.
## When to use LangChain
**Use LangChain when:**
- Building agents with tool calling and reasoning (ReAct pattern)
- Implementing RAG (retrieval-augmented generation) pipelines
- Need to swap LLM providers easily (OpenAI, Anthropic, Google)
- Creating chatbots with conversation memory
- Rapid prototyping of LLM applications
- Production deployments with LangSmith observability
**Metrics**:
- **119,000+ GitHub stars**
- **272,000+ repositories** use LangChain
- **500+ integrations** (models, vector stores, tools)
- **3,800+ contributors**
**Use alternatives instead**:
- **LlamaIndex**: RAG-focused, better for document Q&A
- **LangGraph**: Complex stateful workflows, more control
- **Haystack**: Production search pipelines
- **Semantic Kernel**: Microsoft ecosystem
## Quick start
### Installation
```bash
# Core library (Python 3.10+)
pip install -U langchain
# With OpenAI
pip install langchain-openai
# With Anthropic
pip install langchain-anthropic
# Common extras
pip install langchain-community # 500+ integrations
pip install langchain-chroma # Vector store
```
### Basic LLM usage
```python
from langchain_anthropic import ChatAnthropic
# Initialize model
llm = ChatAnthropic(model="claude-sonnet-4-5-20250929")
# Simple completion
response = llm.invoke("Explain quantum computing in 2 sentences")
print(response.content)
```
### Create an agent (ReAct pattern)
```python
from langchain.agents import create_agent
from langchain_anthropic import ChatAnthropic
# Define tools
def get_weather(city: str) -> str:
"""Get current weather for a city."""
return f"It's sunny in {city}, 72°F"
def search_web(query: str) -> str:
"""Search the web for information."""
return f"Search results for: {query}"
# Create agent (<10 lines!)
agent = create_agent(
model=ChatAnthropic(model="claude-sonnet-4-5-20250929"),
tools=[get_weather, search_web],
system_prompt="You are a helpful assistant. Use tools when needed."
)
# Run agent
result = agent.invoke({"messages": [{"role": "user", "content": "What's the weather in Paris?"}]})
print(result["messages"][-1].content)
```
## Core concepts
### 1. Models - LLM abstraction
```python
from langchain_openai import ChatOpenAI
from langchain_anthropic import ChatAnthropic
from langchain_google_genai import ChatGoogleGenerativeAI
# Swap providers easily
llm = ChatOpenAI(model="gpt-4o")
llm = ChatAnthropic(model="claude-sonnet-4-5-20250929")
llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash-exp")
# Streaming
for chunk in llm.stream("Write a poem"):
print(chunk.content, end="", flush=True)
```
### 2. Chains - Sequential operations
```python
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
# Define prompt template
prompt = PromptTemplate(
input_variables=["topic"],
template="Write a 3-sentence summary about {topic}"
)
# Create chain
chain = LLMChain(llm=llm, prompt=prompt)
# Run chain
result = chain.run(topic="machine learning")
```
### 3. Agents - Tool-using reasoning
**ReAct (Reasoning + Acting) pattern:**
```python
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain.tools import Tool
# Define custom tool
calculator = Tool(
name="Calculator",
func=lambda x: eval(x),
description="Useful for math calculations. Input: valid Python expression."
)
# Create agent with tools
agent = create_tool_calling_agent(
llm=llm,
tools=[calculator, search_web],
prompt="Answer questions using available tools"
)
# Create executor
agent_executor = AgentExecutor(agent=agent, tools=[calculator], verbose=True)
# Run with reasoning
result = agent_executor.invoke({"input": "What is 25 * 17 + 142?"})
```
### 4. Memory - Conversation history
```python
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain
# Add memory to track conversation
memory = ConversationBufferMemory()
conversation = ConversationChain(
llm=llm,
memory=memory,
verbose=True
)
# Multi-turn conversation
conversation.predict(input="Hi, I'm Alice")
conversation.predict(input="What's my name?") # Remembers "Alice"
```
## RAG (Retrieval-Augmented Generation)
### Basic RAG pipeline
```python
from langchain_community.document_loaders import WebBaseLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_openai import OpenAIEmbeddings
from langchain_chroma import Chroma
from langchain.chains import RetrievalQA
# 1. Load documents
loader = WebBaseLoader("https://docs.python.org/3/tutorial/")
docs = loader.load()
# 2. Split into chunks
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=200
)
splits = text_splitter.split_documents(docs)
# 3. Create embeddings and vector store
vectorstore = Chroma.from_documents(
documents=splits,
embedding=OpenAIEmbeddings()
)
# 4. Create retriever
retriever = vectorstore.as_retriever(search_kwargs={"k": 4})
# 5. Create QA chain
qa_chain = RetrievalQA.from_chain_type(
llm=llm,
retriever=retriever,
return_source_documents=True
)
# 6. Query
result = qa_chain({"query": "What are Python decorators?"})
print(result["result"])
print(f"Sources: {result['source_documents']}")
```
### Conversational RAG with memory
```python
from langchain.chains import ConversationalRetrievalChain
# RAG with conversation memory
qa = ConversationalRetrievalChain.from_llm(
llm=llm,
retriever=retriever,
memory=ConversationBufferMemory(
memory_key="chat_history",
return_messages=True
)
)
# Multi-turn RAG
qa({"question": "What is Python used for?"})
qa({"question": "Can you elaborate on web development?"}) # Remembers context
```
## Advanced agent patterns
### Structured output
```python
from langchain_core.pydantic_v1 import BaseModel, Field
# Define schOrchestrates end-to-end autonomous AI research projects using a two-loop architecture. The inner loop runs rapid experiment iterations with clear optimization targets. The outer loop synthesizes results, identifies patterns, and steers research direction. Routes to domain-specific skills for execution, supports continuous agent operation via Claude Code /loop and OpenClaw heartbeat, and produces research presentations and papers. Use when starting a research project, running autonomous experiments, or managing a multi-hypothesis research effort.
Implements and trains LLMs using Lightning AI's LitGPT with 20+ pretrained architectures (Llama, Gemma, Phi, Qwen, Mistral). Use when need clean model implementations, educational understanding of architectures, or production fine-tuning with LoRA/QLoRA. Single-file implementations, no abstraction layers.
State-space model with O(n) complexity vs Transformers' O(n²). 5× faster inference, million-token sequences, no KV cache. Selective SSM with hardware-aware design. Mamba-1 (d_state=16) and Mamba-2 (d_state=128, multi-head). Models 130M-2.8B on HuggingFace.
Educational GPT implementation in ~300 lines. Reproduces GPT-2 (124M) on OpenWebText. Clean, hackable code for learning transformers. By Andrej Karpathy. Perfect for understanding GPT architecture from scratch. Train on Shakespeare (CPU) or OpenWebText (multi-GPU).
RNN+Transformer hybrid with O(n) inference. Linear time, infinite context, no KV cache. Train like GPT (parallel), infer like RNN (sequential). Linux Foundation AI project. Production at Windows, Office, NeMo. RWKV-7 (March 2025). Models up to 14B parameters.
Provides PyTorch-native distributed LLM pretraining using torchtitan with 4D parallelism (FSDP2, TP, PP, CP). Use when pretraining Llama 3.1, DeepSeek V3, or custom models at scale from 8 to 512+ GPUs with Float8, torch.compile, and distributed checkpointing.
Fast tokenizers optimized for research and production. Rust-based implementation tokenizes 1GB in <20 seconds. Supports BPE, WordPiece, and Unigram algorithms. Train custom vocabularies, track alignments, handle padding/truncation. Integrates seamlessly with transformers. Use when you need high-performance tokenization or custom tokenizer training.
Language-independent tokenizer treating text as raw Unicode. Supports BPE and Unigram algorithms. Fast (50k sentences/sec), lightweight (6MB memory), deterministic vocabulary. Used by T5, ALBERT, XLNet, mBART. Train on raw text without pre-tokenization. Use when you need multilingual support, CJK languages, or reproducible tokenization.