【LangChain入门 6 Chain组件】单链和多链

一、单链

1.1 LCEL的语法

| 为关键字,使用 | 作为链接符号

python 复制代码
from langchain_core.output_parsers import StrOutputParser
from langchain_ollama import ChatOllama
llm = ChatOllama( model="deepseek-r1:7b")
parser = StrOutputParser() # 加了这段后,会讲Chunk类转化成字符串,也就是获取Chunk类中的content内容

chain = prompt | llm | parser  # 使用LCEL语法创建链
response = chain.invoke({"input":"宠物"})
print(response)

1.2 LLMChain

LLMChain 是 LangChain 中最基本且最常用的链式结构,广泛应用于 LangChain 的其他复杂链和代理程序中。它由以下两个主要部分组成:

  • PromptTemplate:用于定义提示模板,将用户输入动态格式化为语言模型能够理解的提示。
  • 语言模型(LLM 或聊天模型):用于处理格式化后的提示,并生成响应。
python 复制代码
from langchain.chains import LLMChain
from langchain_core.prompts import ChatPromptTemplate

# 1 实例化模型
llm = ChatOllama( model="deepseek-r1:7b")
# 2 定义模板
prompt = ChatPromptTemplate.from_template("给我取一个关于{input}的店名")

# 3 构建Chain,将大模型与prompt组合在一起
chain = LLMChain(prompt=prompt, llm=llm)

# 4 执行Chain
response = chain.invoke({"input":"宠物"})
print(response)

input_list = [{"input":"宠物"}, {"input":"鲜花"}]
response = chain.apply(input_list) # 批量输出

三、多链组装

将多个链条融合在一起

LangChain 提供了强大的多链功能,允许用户通过组合多个链(Chain)来实现复杂的任务。这些链可以按顺序执行,也可以并行执行,从而实现高效的模型协作和协调

  1. 串联多个链(Sequential Chains)
    通过 SimpleSequentialChain 或管道操作符 |,可以将多个链按顺序串联起来。前一个链的输出会自动作为下一个链的输入。
  2. LangChain 支持并行执行多个链,这在需要同时处理多个任务时非常有用
  3. 分支和合并(Branching and Merging) LangChain 支持创建复杂的计算图,允许将一个组件的输出分叉为多个组件的输入,并在后续步骤中合并结
python 复制代码
from langchain_ollama import ChatOllama
from langchain_core.prompts import ChatPromptTemplate
from langchain.chains import SimpleSequentialChain, LLMChain

prompt = ChatPromptTemplate.from_template("给我取一个关于{input}的店名")
llm = ChatOllama( model="deepseek-r1:7b")

prompt_second = ChatPromptTemplate.from_template("给我的跑车取一个关于{input}的名字")

first_chain = LLMChain(prompt=prompt, llm=llm) # 创建第一个链
second_chain = LLMChain(prompt=prompt_second, llm=llm)

all_chain = SimpleSequentialChain(chains=[first_chain, second_chain], 
                                  verbose=True)

response = all_chain.invoke({"input":"狗"})
相关推荐
数据智能老司机1 小时前
构建由 LLM 驱动的 Neo4j 应用程序——LLM、RAG 与 Neo4j 知识图谱简介
langchain·llm·aigc
ClouGence18 小时前
RAG 青铜升级:知识库召回率优化实战攻略
后端·langchain
老周聊大模型20 小时前
大模型如何突破“认知茧房”?RAG+MCP构建外部脑接口
langchain·agent·mcp
小森( ﹡ˆoˆ﹡ )21 小时前
LangChain聊天机器人教程
大数据·langchain·机器人
AIGC包拥它2 天前
RAG项目实战:LangChain 0.3集成 Milvus 2.5向量数据库,构建大模型智能应用
人工智能·python·langchain·prompt·个人开发·milvus
&梧桐树夏2 天前
【AI】文生图&文生视频
人工智能·ai·langchain
ak啊2 天前
LangChain:让语言模型成为你的应用逻辑组件
python·langchain
后端小张2 天前
智谱AI图生视频:从批处理到多线程优化
开发语言·人工智能·ai·langchain·音视频
雷渊3 天前
LangChain4j-ChatMessage的种类以及作用
langchain·llm
都叫我大帅哥3 天前
🤖 玩转LangChain的ChatPromptTemplate:从入门到“放弃”
python·langchain·ai编程