当前位置: 首页 > news >正文

langchain链中的高级组件

1.RunnableLambda定义链:将自己写的函数加入链,该函数只支持一个传递一个参数(键值对传参)


(1)注意传入链值的类型
<class 'langchain_core.runnables.base.RunnableSequence'>
<class 'int'>
(2)#itemgetter("foo"):用于从输入的字典中提取键为 "foo" 的值,转为runnable对象

(3)如果是其它静态值,需要先转换为Runnable对象

# 创建返回静态值的 Runnable
static_3 = RunnableLambda(lambda x: 3)
static_5 = RunnableLambda(lambda x: 5)
from operator import itemgetterfrom langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import chain, RunnableLambdaimport utils
import langchain
#开启该参数,会输出调试信息
# langchain.debug = True
#获得访问大模型客户端
client = utils.get_client()#定义提示模版工具
chat_template = ChatPromptTemplate.from_template(" {a} + {b}是多少?")
# chat_template = ChatPromptTemplate.from_template(" {a}是多少?")
#获得字符串的长度
def length_function(text):return len(text)
#将两个字符串长度的数量相乘
def _multiple_length_function(text1, text2):return len(text1) * len(text2)#任何可以转为Lambda的函数,它接受一个参数
#装饰器 @chain是RunnableLambda另外一种写法
@chain
def multiple_length_function(_dict):return _multiple_length_function(_dict["text1"], _dict["text2"])#使用RunnableLambda将函数转换为与LCEL兼容的组件
#itemgetter("foo"):用于从输入的字典中提取键为 "foo" 的值。chain2 = ({"a": itemgetter("foo") | RunnableLambda(length_function),"b": ( {"text1": itemgetter("foo"), "text2": itemgetter("bar")}| multiple_length_function )}| chat_template | client)print(chain2.invoke({"foo": "abc", "bar": "abcd"}))from operator import itemgetterfrom langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import chain, RunnableLambdaimport utils
import langchain
#开启该参数,会输出调试信息
langchain.debug = True
#获得访问大模型客户端
client = utils.get_client()#定义提示模版工具
chat_template = ChatPromptTemplate.from_template("{a}+{b}的值是多少")#定义函数
@chain
def label(x):return x+1# 转为runnablelambda表达式
chain = {"a":(RunnableLambda(lambda x: 3)| label ), "b":(RunnableLambda(lambda x: 5)| label ) }| chat_template | client
print(chain.invoke("计算"))

2.RunnableSequence串行链

里面是一个runnable对象传递

def mul_three(x: int) -> int:
return x * 3
runnable_3 = RunnableLambda(mul_three)#chain = prompt | client | output_parser 和下面的等价
chain = RunnableSequence(chat_template,client,parser)

3.RunableParallelb并行链

里面是一个runnable对象传递

from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableLambda, RunnableParallel
import utilsdef add_one(x: int) -> int:return x + 1def mul_two(x: int) -> int:return x * 2def mul_three(x: int) -> int:return x * 3runnable_1 = RunnableLambda(add_one)
runnable_2 = RunnableLambda(mul_two)
runnable_3 = RunnableLambda(mul_three)client = utils.get_client()# 创建提示模板
pmt1 = ChatPromptTemplate.from_template("{mul_two}+1是多少")
pmt2 = ChatPromptTemplate.from_template("{mul_three}+1是多少")# 正确的链式结构
chain2 = (runnable_1 |RunnableParallel(mul_two=runnable_2, mul_three=runnable_3) |RunnableParallel(result1=(lambda z: pmt1.invoke({"mul_two": z["mul_two"]})) | client,result2=(lambda z: pmt2.invoke({"mul_three": z["mul_three"]})) | client)
)print(chain2.invoke(1))

4.RunablePassthrough数据增强链

    1)用户输入什么,就传递什么,
2)通过assign对数据进行增强,在往后传,原始值和传递后的值

#RunnablePassthrough的使用
#RunnablePassthrough的两种用法都将在我们后面的课程中看到
from langchain_core.runnables import RunnableParallel, RunnablePassthrough# RunnablePassthrough对数据增强后传递
runnable = RunnableParallel(passed = RunnablePassthrough().assign(query=lambda x: x["num"] + 2),modified = lambda x: x["num"] + 1,
)
print(runnable.invoke({"num": 1}))#结果
{'passed': {'num': 1, 'query': 3}, 'modified': 2}

5.ChatMessageHistory:存储历史消息,聊天记录本

  • 单纯存储所有聊天记录的数据库

  • 没有智能。它不知道如何利用这些历史记录,也不会主动把历史记录发送给AI模型。它只是被动地存储数据。

chat_history = ChatMessageHistory()

(1)存储历史消息

chat_template = ChatPromptTemplate.from_messages(
[
SystemMessagePromptTemplate.from_template("你是人工智能助手"),
("placeholder","{messages}")
]
)

(2)添加消息

chat_history.add_user_message

chat_history.add_ai_message

(3)取出历史消息

chat_history.messages

from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate
from langchain_community.chat_message_histories import ChatMessageHistory
import utils#想让大模型知道我们聊天中每次的会话内容,提示词中有专门的地方存放我们的聊天的历史
chat_template = ChatPromptTemplate.from_messages([SystemMessagePromptTemplate.from_template("你是人工智能助手"),("placeholder","{messages}")]
)client = utils.get_client()
parser = StrOutputParser()
chain = chat_template | client | parser#引入消息历史组件
chat_history = ChatMessageHistory()
chat_history.add_user_message("你好,我是云帆,我爱吃苹果")
res=chain.invoke({"messages":chat_history.messages})
print(res)
chat_history.add_ai_message(res)
print("chat_history:",chat_history.messages)chat_history.add_user_message("你好,我是谁?我爱吃什么") #把用户的提问加入消息历史
print(chain.invoke({"messages": chat_history.messages}))

6.RunnableWithMessageHistory:拥有记忆功能的智能聊天机器人

负责自动化地管理对话上下文能记住各个用户的历史的对话代理

http://www.dtcms.com/a/395700.html

相关文章:

  • 鸿蒙:使用animation或animateTo实现图片无限旋转效果
  • 02)阿里 Arthas(阿尔萨斯)开源的 Java 诊断工具原理分析、JVM动态加载“代理程序“(Agent) 的机制、vm.loadAgent原理
  • [学习笔记][机器学习-周志华] 第1章 绪论
  • Node.js面试题及详细答案120题(111-120) -- 进阶与扩展篇
  • 鞋底布线前传:CAD三维建模如何实现精准凸起设计
  • 华为无线网络技术基础
  • Django 模型与 ORM 全解析(二):数据库操作
  • Python 2025:AI与自动化运维的融合新纪元
  • MySQL 核心函数与约束详解
  • 设计模式简要
  • 服务扩容与容量评估手册
  • Pyside6 + QML - 信号与槽08 - 一个函数被多个信号触发(带参数)
  • 【第十一章】Python 调用 MySQL 全面指南:从基础到实践​
  • 新手玩家如何使用云手机
  • 【Datawhale组队学习202509】AI硬件与机器人大模型 task02 视觉感知与手眼协调
  • 基础算法---【前缀和】
  • YOLO系统——yolov1工作原理
  • 第20讲 机器学习中的分类数据
  • 《前端学习总结:GitLab、状态管理、组件库与 Umi.js》
  • 【论文阅读】理解世界还是预测未来?—— 世界模型全面综述
  • AR眼镜:远程协作与精准操作的未来之眼
  • 【论文阅读】GR-2:用于机器人操作的生成式视频-语言-动作模型
  • maven GAVP 的含义
  • 【Android】录制视频
  • RK3576-Android15_Usb白名单功能实现篇二
  • Spring中使用Apache Http客户端调第三方系统接口临时查看请求体参数
  • Linux系统-debian系的软件包管理
  • PCB工艺中的深微孔
  • 关于Pycharm中在运行出现语法错误:Non-UTF-8 code starting with
  • 构建AI智能体:四十一、大模型思维链提示工程:技术原理与行业应用案例分析