14.5万 Stars 的 LLM 应用开发框架 LangChain 核心能力全景解读
14.5万 Stars 的 LLM 应用开发框架:LangChain 核心能力全景解读
LangChain 是 AI 应用开发的事实标准框架,145K Stars,帮助开发者用模块化方式构建 LLM 应用。组件链(Chain)、Agent、工具调用、记忆系统——一文讲清楚 LangChain 核心能力。
LangChain(langchain-ai/langchain,⭐ 145,510,Python,MIT)是 LLM 应用开发框架,核心理念:用可组合的模块构建复杂的 LLM 应用,而不是从零写 Prompt 和 API 调用逻辑。
核心数据
| 指标 | 数值 |
|---|---|
| ⭐ Stars | 145,510 |
| 🍴 Forks | 21,472 |
| 💻 语言 | Python |
| 📜 许可证 | MIT |
| 🔌 组件数 | 工具 / 记忆 / Agent / Chain |
它解决什么问题
直接调用 LLM API 能跑,但难维护、难复用、难测试。LangChain 的解法:
- 组件化:Prompt 模板、LLM 调用、工具、记忆全部抽象为组件
- 链式调用:用 Chain 把组件串成工作流
- Agent 自治:Agent 自己决定调用哪个工具
- 记忆系统:跨会话保留对话上下文
技术亮点
1. Chain(链)
from langchain import LLMChain
from langchain.prompts import PromptTemplate
from langchain.llms import OpenAI
chain = LLMChain(
llm=OpenAI(temperature=0),
prompt=PromptTemplate.from_template("Explain {concept} in one sentence.")
)
print(chain.run("gradient descent"))
把 Prompt 模板 + LLM 封装成可复用链。
2. Agent(自主执行)
from langchain.agents import load_tools, initialize_agent
from langchain.llms import OpenAI
llm = OpenAI()
tools = load_tools(["serpapi", "llm-math"], llm=llm)
agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True)
agent.run("What is the population of Tokyo, multiplied by 2?")
Agent 根据问题自己选择工具、调用、得到答案。
3. 工具调用(Tools)
from langchain.tools import Tool
from langchain.utilities import SerpAPIWrapper
search = SerpAPIWrapper()
tools = [
Tool(name="Search", func=search.run, description="Search the web")
]
支持 Google Search、Wolfram Alpha、Python REPL、SQL 等工具生态。
4. 记忆系统(Memory)
from langchain.memory import ConversationBufferMemory
memory = ConversationBufferMemory(memory_key="chat_history")
# Agent 记住之前的对话内容
支持 Buffer、Summary、Entity 等多种记忆类型。
5. 丰富的集成
LLM: OpenAI / Anthropic / Google / HuggingFace / 本地模型
向量库: Pinecone / Chroma / FAISS
工具: Search / SQL / API / Python REPL
云服务: AWS / Azure / GCP
安装使用
pip install langchain
# 配合 LLM 使用
pip install langchain openai
和直接调用 API 的区别
| 特性 | 直接调用 API | LangChain |
|---|---|---|
| Prompt 管理 | 字符串拼接 | 模板复用 |
| 工具扩展 | 手动写 | 生态丰富 |
| Agent 自治 | ❌ | ✅ |
| 记忆系统 | ❌ | ✅ |
| Chain 组合 | ❌ | ✅ |
评论区
0 条评论
登录后可评论。