LangChain的核心基礎(chǔ)組件

LangChain 的核心優(yōu)勢在于其模塊化的組件設(shè)計,它有一系列基礎(chǔ)組件共同支撐起從“輸入→處理→輸出”的完整流程。下面我會按數(shù)據(jù)流轉(zhuǎn)邏輯分類講解這些核心組件,并用新手友好的示例說明用法,幫你快速理解它們的定位和作用。

一、核心基礎(chǔ)組件分類(按功能場景)

1. 輸入層:Prompt 相關(guān)組件(提示詞模板)

PromptTemplate/ChatPromptTemplate 是構(gòu)建“結(jié)構(gòu)化提示詞”的核心,解決手動拼接字符串易出錯、格式不統(tǒng)一的問題,是連接用戶輸入和模型的橋梁。

核心作用:定義提示詞的固定模板 + 動態(tài)填充變量(比如用戶問題、上下文)。

from langchain_core.prompts import PromptTemplate, ChatPromptTemplate

# 1. 基礎(chǔ)文本提示詞模板(適用于普通LLM)
prompt_template = PromptTemplate(
    input_variables=["question"],  # 聲明需要填充的變量
    template="請用簡潔的語言回答:{question}"  # 模板字符串
)
# 填充變量生成提示詞
prompt = prompt_template.format(question="什么是LangChain?")
print(prompt)  # 輸出:請用簡潔的語言回答:什么是LangChain?

# 2. 對話型提示詞模板(適用于Chat模型,區(qū)分角色)
chat_prompt = ChatPromptTemplate.from_messages([
    ("system", "你是一個編程助手,回答簡潔明了"),  # 系統(tǒng)角色
    ("user", "{question}")  # 用戶輸入變量
])
# 生成對話格式的提示詞
messages = chat_prompt.format_messages(question="Python怎么學(xué)?")
print(messages)  # 輸出:[SystemMessage(content='你是一個編程助手...'), HumanMessage(content='Python怎么學(xué)?')]

2. 執(zhí)行層:LLM/ChatModel(模型調(diào)用)

這是 LangChain 對接大模型的核心組件,分為兩類:

  • LLM:對接文本輸出型模型(如 GPT-3、Claude 文本版),輸出純字符串;
  • ChatModel:對接對話型模型(如 GPT-3.5/4、Claude 3),輸出結(jié)構(gòu)化的對話消息。

核心作用:發(fā)送提示詞給大模型,獲取模型返回結(jié)果。

from langchain_openai import OpenAI, ChatOpenAI
import os

os.environ["OPENAI_API_KEY"] = "你的API Key"

# 1. 基礎(chǔ)LLM(文本輸出)
llm = OpenAI(model="gpt-3.5-turbo-instruct")
result = llm.invoke("請解釋什么是LLM?")
print(result)  # 輸出純文本回答

# 2. ChatModel(對話輸出)
chat_model = ChatOpenAI(model="gpt-3.5-turbo")
result = chat_model.invoke("請解釋什么是ChatModel?")
print(result.content)  # 提取對話消息的內(nèi)容字段

3. 處理層:Runnable(鏈/組合器)

Runnable 是 LangChain 中所有組件的“通用接口”,核心是支持 invoke()(同步調(diào)用)、stream()(流式輸出)等統(tǒng)一方法,常見實現(xiàn)包括:

  • RunnableSequence:按順序執(zhí)行多個組件(用 | 運算符簡化);
  • RunnableParallel:并行執(zhí)行多個組件(合并結(jié)果);
  • 你熟悉的 RunnablePassthrough 也屬于 Runnable 體系。

核心作用:把 Prompt、Model、Passthrough 等組件組合成復(fù)雜的執(zhí)行流程。

from langchain_core.runnables import RunnableSequence, RunnableParallel
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

# 1. 順序鏈(最常用,用|簡化)
prompt = ChatPromptTemplate.from_messages([("user", "{question}")])
model = ChatOpenAI()
chain = prompt | model  # 等價于 RunnableSequence([prompt, model])
result = chain.invoke({"question": "LangChain的核心組件有哪些?"})
print(result.content)

# 2. 并行鏈(同時執(zhí)行多個任務(wù))
parallel_chain = RunnableParallel({
    "short_answer": prompt | model,  # 生成簡短回答
    "original_question": RunnablePassthrough()  # 透傳原始問題
})
result = parallel_chain.invoke({"question": "Python怎么學(xué)?"})
print(result)  # 輸出:{"short_answer": 模型回答, "original_question": {"question": "Python怎么學(xué)?"}}

4. 輸出層:OutputParser(輸出解析器)

大模型返回的是文本/對話消息,OutputParser 可以把非結(jié)構(gòu)化輸出轉(zhuǎn)換成結(jié)構(gòu)化數(shù)據(jù)(如 JSON、列表、自定義類),解決“解析模型輸出”的痛點。

核心作用:標(biāo)準(zhǔn)化模型輸出格式,方便后續(xù)處理。

from langchain_core.output_parsers import (
    StrOutputParser,  # 轉(zhuǎn)字符串
    JsonOutputParser,  # 轉(zhuǎn)JSON
    ListOutputParser   # 轉(zhuǎn)列表
)
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

# 1. 字符串解析器(最基礎(chǔ))
model = ChatOpenAI()
str_parser = StrOutputParser()
chain = prompt | model | str_parser
result = chain.invoke({"question": "Python怎么學(xué)?"})
print(type(result))  # 輸出:<class 'str'>

# 2. JSON解析器(指定格式讓模型輸出JSON)
json_parser = JsonOutputParser()
# 提示詞中明確要求輸出JSON格式
prompt = ChatPromptTemplate.from_messages([
    ("user", "請列出3個Python學(xué)習(xí)網(wǎng)站,輸出JSON格式,字段為name和url")
])
chain = prompt | model | json_parser
result = chain.invoke({})
print(result)  # 輸出:[{"name": "菜鳥教程", "url": "https://www.runoob.com/"}, ...]
print(type(result))  # 輸出:<class 'list'>

5. 數(shù)據(jù)層:Document/TextSplitter(文檔處理)

如果需要處理長文本(如PDF、文章),這兩類組件是基礎(chǔ):

  • Document:標(biāo)準(zhǔn)化文本數(shù)據(jù)結(jié)構(gòu)(包含 page_content 內(nèi)容字段 + metadata 元數(shù)據(jù)字段);
  • TextSplitter:把長文本分割成小片段(適配模型上下文窗口限制)。

核心作用:處理外部文本數(shù)據(jù),為“檢索增強(qiáng)生成(RAG)”打基礎(chǔ)。

from langchain_core.documents import Document
from langchain_text_splitters import CharacterTextSplitter

# 1. 定義Document
doc = Document(
    page_content="LangChain是一個大模型應(yīng)用開發(fā)框架,支持RAG、Agent等場景。它的核心是模塊化組件。",
    metadata={"source": "官方文檔", "type": "introduction"}
)

# 2. 分割長文本
text_splitter = CharacterTextSplitter(
    chunk_size=50,  # 每個片段最大字符數(shù)
    chunk_overlap=10  # 片段間重疊字符數(shù)(保證上下文連續(xù))
)
splits = text_splitter.split_documents([doc])
print(len(splits))  # 輸出:2(分割成2個片段)
print(splits[0].page_content)  # 輸出第一個片段內(nèi)容

二、其他常用基礎(chǔ)組件

組件類型 代表組件 核心作用
檢索組件 VectorStore/Retriever 存儲文本向量、檢索相關(guān)上下文(RAG核心)
記憶組件 ChatMessageHistory 保存對話歷史,實現(xiàn)多輪對話
工具調(diào)用組件 Tool/Toolkit 讓模型調(diào)用外部工具(如搜索、計算器)
異常處理組件 RunnableRetry 失敗重試(如模型調(diào)用超時/報錯時重試)

總結(jié)

  1. 核心流轉(zhuǎn)邏輯PromptTemplate(構(gòu)造提示詞)→ ChatModel/LLM(調(diào)用模型)→ OutputParser(解析輸出),通過 Runnable 組合流程,RunnablePassthrough 負(fù)責(zé)數(shù)據(jù)透傳/加工;
  2. 擴(kuò)展能力Document/TextSplitter 處理外部文本,VectorStore 實現(xiàn)檢索增強(qiáng),ChatMessageHistory 實現(xiàn)多輪對話;
  3. 統(tǒng)一接口:所有組件都實現(xiàn) Runnable 接口,支持 invoke()/stream() 等統(tǒng)一調(diào)用方式,降低組合復(fù)雜度。

這些組件的核心設(shè)計思想是“模塊化+可組合”,你可以像搭積木一樣,用基礎(chǔ)組件組合出復(fù)雜的大模型應(yīng)用(如RAG、智能體Agent)。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容