一、前言

LangChain 作为当前最火热的 LLM 应用开发框架,提供了从简单 Chain 到复杂 Agent 的一整套工具链。本文将通过实战案例,带你快速掌握 LangChain 的核心概念。

二、Model I/O — 模型交互的基础

Model I/O 是 LangChain 的核心模块,负责与大语言模型进行交互。

2.1 Prompt 模板

from langchain.prompts import PromptTemplate

template = PromptTemplate.from_template(
    "请用一句话解释:{concept}"
)
formatted = template.format(concept="人工智能")
print(formatted)
# 输出:请用一句话解释:人工智能

2.2 ChatModel 调用

from langchain.chat_models import ChatOpenAI

chat = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.7)
response = chat.invoke("解释什么是 RAG")
print(response.content)

三、Chain — 链式调用

Chain 是 LangChain 的核心概念,允许我们将多个组件串联起来完成复杂任务。

3.1 LLMChain 示例

from langchain.chains import LLMChain
from langchain.llms import OpenAI

llm = OpenAI(temperature=0.9)
chain = LLMChain(llm=llm, prompt=template)
result = chain.run("大语言模型")
print(result)

3.2 Sequential Chain

from langchain.chains import SequentialChain

chain1 = LLMChain(llm=llm, prompt=prompt1, output_key="story")
chain2 = LLMChain(llm=llm, prompt=prompt2, output_key="summary")
full_chain = SequentialChain(
    chains=[chain1, chain2],
    input_variables=["topic"],
    output_variables=["story", "summary"]
)

四、Agent — 自主行动

Agent 是 LangChain 的高级特性,让 AI 能够自主决定行动方案。

from langchain.agents import Agent, Tool
from langchain.agents import initialize_agent

tools = [
    Tool(name="Search", func=search_fn, description="搜索信息"),
    Tool(name="Calculator", func=calc_fn, description="数学计算")
]

agent = initialize_agent(
    tools, llm, agent_type="zero-shot-react-description", verbose=True
)
agent.run("2024年诺贝尔物理学奖得主是谁?")

五、Memory — 记忆管理

LangChain 提供多种 Memory 实现,让 Agent 具备记忆能力。

from langchain.memory import ConversationBufferMemory

memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)

# 结合 Agent 使用
from langchain.agents import Agent
agent = Agent(llm=llm, tools=tools, memory=memory)

六、实战:用 LangChain 构建本地知识库问答

from langchain.document_loaders import TextLoader
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.vectorstores import Chroma

# 1. 加载文档
loader = TextLoader("docs/*.txt")
docs = loader.load()

# 2. 分块 & 向量化
from langchain.text_splitter import RecursiveCharacterTextSplitter
splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
chunks = splitter.split_documents(docs)

# 3. 存储到向量数据库
db = Chroma.from_documents(chunks, OpenAIEmbeddings())

# 4. 构建 RAG Chain
retriever = db.as_retriever()
qa_chain = RetrievalQA.from_chain_type(llm=llm, retriever=retriever)
result = qa_chain.run("文档中关于什么的?")

七、总结

本文介绍了 LangChain 的四大核心概念:

  • Model I/O:与大模型交互的基础,提供 Prompt 模板和模型调用接口
  • Chain:链式调用,支持 LLMChain、SequentialChain 等多种组合方式
  • Agent:自主行动,通过 ReAct 等策略让 AI 自主决策下一步
  • Memory:记忆管理,支持多种记忆实现方案

掌握这些核心概念后,你就可以构建复杂的 LLM 应用,如本地知识库问答、多步骤自动化任务、智能助手等。

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐