0
# LangChain
1
2
A comprehensive Python framework for building applications powered by Large Language Models (LLMs) through composable components. LangChain provides a standard interface for models, embeddings, vector stores, and external integrations, enabling developers to create sophisticated AI applications with real-time data augmentation, model interoperability, and advanced agent orchestration capabilities.
3
4
## Package Information
5
6
- **Package Name**: langchain
7
- **Language**: Python
8
- **Installation**: `pip install langchain`
9
- **Version**: 0.3.27
10
11
## Core Imports
12
13
```python
14
import langchain
15
```
16
17
For specific functionality, import from module namespaces:
18
19
```python
20
from langchain.agents import initialize_agent, AgentType
21
from langchain.chains import LLMChain, ConversationChain
22
from langchain.callbacks import StreamingStdOutCallbackHandler
23
from langchain.memory import ConversationBufferMemory
24
```
25
26
**Note**: Many LangChain components have migrated to specialized packages for better modularity:
27
28
```python
29
# Core abstractions (recommended)
30
from langchain_core.prompts import PromptTemplate
31
from langchain_core.messages import HumanMessage, AIMessage
32
from langchain_core.tools import BaseTool, tool
33
34
# Provider-specific components
35
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
36
from langchain_anthropic import ChatAnthropic
37
from langchain_community.vectorstores import FAISS
38
```
39
40
## Basic Usage
41
42
```python
43
from langchain.chains import LLMChain
44
from langchain_core.prompts import PromptTemplate
45
from langchain_openai import OpenAI
46
47
# Create a simple LLM chain
48
llm = OpenAI(temperature=0.7)
49
prompt = PromptTemplate(
50
input_variables=["topic"],
51
template="Write a short poem about {topic}."
52
)
53
54
chain = LLMChain(llm=llm, prompt=prompt)
55
result = chain.run("artificial intelligence")
56
print(result)
57
```
58
59
More complex example with agents:
60
61
```python
62
from langchain.agents import initialize_agent, AgentType
63
from langchain_community.tools import DuckDuckGoSearchRun
64
from langchain_openai import OpenAI
65
66
# Create tools and agent
67
search = DuckDuckGoSearchRun()
68
tools = [search]
69
70
llm = OpenAI(temperature=0)
71
agent = initialize_agent(
72
tools,
73
llm,
74
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
75
verbose=True
76
)
77
78
# Run the agent
79
response = agent.run("What is the latest news about AI?")
80
```
81
82
## Architecture
83
84
LangChain follows a modular architecture built around composable components:
85
86
- **Models**: LLMs, Chat Models, and Embeddings providing AI capabilities
87
- **Prompts**: Templates and management for model inputs
88
- **Chains**: Sequences of components for complex workflows
89
- **Agents**: AI systems that can use tools and make decisions
90
- **Memory**: State management for conversations and context
91
- **Retrievers**: Components for fetching relevant information
92
- **Tools**: External system integrations for agents
93
- **Callbacks**: Event handling and monitoring
94
95
This design enables maximum reusability across AI applications, chatbots, document analysis systems, and any application requiring intelligent language processing, with built-in support for retrieval-augmented generation (RAG), agent workflows, and production deployment patterns.
96
97
## Migration Note
98
99
**Important**: LangChain v0.3.x serves primarily as an orchestration layer and compatibility interface. Most concrete implementations have moved to specialized packages:
100
101
- **langchain_core**: Core abstractions and base classes
102
- **langchain_community**: Third-party integrations and implementations
103
- **Provider packages**: langchain_openai, langchain_anthropic, etc.
104
105
The main langchain package provides backward compatibility with deprecation warnings guiding migration to appropriate packages.
106
107
## Capabilities
108
109
### Agents and Tools
110
111
AI agents that can reason about which tools to use and when to use them. Agents can interact with external APIs, databases, search engines, and other systems to accomplish complex tasks autonomously.
112
113
```python { .api }
114
def initialize_agent(tools, llm, agent=None, **kwargs):
115
"""Initialize an agent with tools and LLM."""
116
117
class AgentExecutor:
118
"""Execute agent actions with tools."""
119
def run(self, input: str) -> str: ...
120
def invoke(self, input: dict) -> dict: ...
121
122
class AgentType:
123
"""Enumeration of available agent types."""
124
ZERO_SHOT_REACT_DESCRIPTION: str
125
CHAT_ZERO_SHOT_REACT_DESCRIPTION: str
126
CONVERSATIONAL_REACT_DESCRIPTION: str
127
```
128
129
[Agents and Tools](./agents-tools.md)
130
131
### Chains and Workflows
132
133
Composable sequences of operations that combine models, retrievers, and processing steps. Chains enable complex workflows like question-answering, summarization, and document analysis.
134
135
```python { .api }
136
class LLMChain:
137
"""Chain for single LLM calls with prompt templates."""
138
def __init__(self, llm, prompt, **kwargs): ...
139
def run(self, **kwargs) -> str: ...
140
def invoke(self, input: dict) -> dict: ...
141
142
class ConversationChain:
143
"""Chain for conversational interactions with memory."""
144
def __init__(self, llm, memory=None, **kwargs): ...
145
146
class RetrievalQA:
147
"""Chain for question-answering with document retrieval."""
148
@classmethod
149
def from_chain_type(cls, llm, chain_type: str, retriever, **kwargs): ...
150
```
151
152
[Chains and Workflows](./chains-workflows.md)
153
154
### Document Processing and Retrieval
155
156
Tools for loading, processing, and retrieving documents to enable retrieval-augmented generation (RAG) workflows. Supports various document types and vector storage backends.
157
158
```python { .api }
159
class BaseRetriever:
160
"""Base class for document retrievers."""
161
def get_relevant_documents(self, query: str) -> list: ...
162
def invoke(self, input: str) -> list: ...
163
164
class VectorStoreRetriever:
165
"""Retriever backed by vector store."""
166
def __init__(self, vectorstore, search_kwargs=None): ...
167
168
def create_retrieval_chain(retriever, combine_docs_chain):
169
"""Create a retrieval chain combining retriever and processing."""
170
```
171
172
[Document Processing](./document-processing.md)
173
174
### Memory and Context Management
175
176
State management for maintaining conversation history, context, and intermediate results across interactions. Essential for building conversational AI applications.
177
178
```python { .api }
179
class ConversationBufferMemory:
180
"""Buffer memory storing conversation history."""
181
def __init__(self, memory_key: str = "history"): ...
182
def save_context(self, inputs: dict, outputs: dict): ...
183
def load_memory_variables(self, inputs: dict) -> dict: ...
184
185
class ConversationSummaryMemory:
186
"""Memory that summarizes conversation history."""
187
def __init__(self, llm, memory_key: str = "history"): ...
188
189
class ConversationBufferWindowMemory:
190
"""Windowed buffer memory keeping recent messages."""
191
def __init__(self, k: int = 5): ...
192
```
193
194
[Memory and Context](./memory-context.md)
195
196
### Callbacks and Monitoring
197
198
Event handling system for monitoring, logging, and debugging LangChain operations. Supports streaming outputs, usage tracking, and integration with observability platforms.
199
200
```python { .api }
201
class BaseCallbackHandler:
202
"""Base callback handler for LangChain events."""
203
def on_llm_start(self, serialized: dict, prompts: list, **kwargs): ...
204
def on_llm_end(self, response, **kwargs): ...
205
def on_chain_start(self, serialized: dict, inputs: dict, **kwargs): ...
206
207
class StreamingStdOutCallbackHandler:
208
"""Stream LLM outputs to stdout."""
209
210
def tracing_enabled() -> bool:
211
"""Check if LangSmith tracing is enabled."""
212
```
213
214
[Callbacks and Monitoring](./callbacks-monitoring.md)
215
216
## Types
217
218
```python { .api }
219
from typing import Any, Dict, List, Optional, Union
220
from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, SystemMessage
221
from langchain_core.documents import Document
222
from langchain_core.prompts import BasePromptTemplate, PromptTemplate
223
from langchain_core.language_models import BaseLanguageModel, BaseLLM
224
225
class Document:
226
"""Document with content and metadata."""
227
def __init__(self, page_content: str, metadata: dict = None): ...
228
page_content: str
229
metadata: dict
230
231
class BaseMessage:
232
"""Base message class for chat interactions."""
233
content: str
234
additional_kwargs: dict
235
236
class HumanMessage(BaseMessage):
237
"""Message from human user."""
238
239
class AIMessage(BaseMessage):
240
"""Message from AI assistant."""
241
242
class SystemMessage(BaseMessage):
243
"""System message for instructions."""
244
```