哪家网络公司做网站好/报个计算机培训班多少钱
分类目录:《自然语言处理从入门到应用》总目录
在本文中,我们将学习如何在LangChain中创建简单的链式连接并添加组件以及运行它。链式连接允许我们将多个组件组合在一起,创建一个统一的应用程序。例如,我们可以创建一个链式连接,接收用户输入,使用PromptTemplate
对其进行格式化,然后将格式化后的响应传递给LLM。我们可以通过将多个链式连接组合在一起或将链式连接与其他组件组合来构建更复杂的链式连接。
快速入门:使用LLMChain
LLMChain是一个简单的链式连接,它接收一个prompt
模板,使用用户输入对其进行格式化,并返回LLM的响应。要使用LLMChain,首先创建一个prompt
模板。
from langchain.prompts import PromptTemplate
from langchain.llms import OpenAIllm = OpenAI(temperature=0.9)
prompt = PromptTemplate(input_variables=["product"],template="What is a good name for a company that makes {product}?",
)
现在,我们可以创建一个非常简单的链式连接,它将接收用户输入,使用它来格式化prompt
,并将其发送到LLM。
from langchain.chains import LLMChain
chain = LLMChain(llm=llm, prompt=prompt)# 仅指定输入变量运行链式连接。
print(chain.run("colorful socks"))
输出:
Colorful Toes Co.
如果有多个变量,我们可以使用字典一次输入它们。
prompt = PromptTemplate(input_variables=["company", "product"],template="What is a good name for {company} that makes {product}?",
)
chain = LLMChain(llm=llm, prompt=prompt)
print(chain.run({'company': "ABC Startup",'product': "colorful socks"}))
输出:
Socktopia Colourful Creations.
我们也可以在LLMChain中使用聊天模型:
from langchain.chat_models import ChatOpenAI
from langchain.prompts.chat import (ChatPromptTemplate,HumanMessagePromptTemplate,
)human_message_prompt = HumanMessagePromptTemplate(prompt=PromptTemplate(template="What is a good name for a company that makes {product}?",input_variables=["product"],))chat_prompt_template = ChatPromptTemplate.from_messages([human_message_prompt])
chat = ChatOpenAI(temperature=0.9)
chain = LLMChain(llm=chat, prompt=chat_prompt_template)
print(chain.run("colorful socks"))
输出:
Rainbow Socks Co.
调用链式连接的不同方式
所有继承自Chain
的类都提供了几种运行链式连接逻辑的方式。其中最直接的一种方式是使用 __call__
:
chat = ChatOpenAI(temperature=0)
prompt_template = "Tell me a {adjective} joke"
llm_chain = LLMChain(llm=chat,prompt=PromptTemplate.from_template(prompt_template)
)llm_chain(inputs={"adjective":"corny"})
输出:
{'adjective': 'corny','text': 'Why did the tomato turn red? Because it saw the salad dressing!'}
默认情况下,__call__
方法会返回输入和输出的键值对。我们可以通过将return_only_outputs
设置为True
来配置它仅返回输出的键值对。
llm_chain("corny", return_only_outputs=True)
{'text': 'Why did the tomato turn red? Because it saw the salad dressing!'}
如果Chain
只输出一个输出键(即其output_keys
中只有一个元素),则可以使用run
方法。需要注意的是,run
方法输出一个字符串而不是字典。
# llm_chain only has one output key, so we can use run
llm_chain.output_keys
输出:
['text']
输入:
llm_chain.run({"adjective":"corny"})
输出:
'Why did the tomato turn red? Because it saw the salad dressing!'
在只有一个输入键的情况下,我们可以直接输入字符串,无需指定输入映射。
# These two are equivalent
llm_chain.run({"adjective":"corny"})
llm_chain.run("corny")# These two are also equivalent
llm_chain("corny")
llm_chain({"adjective":"corny"})
输出:
{'adjective': 'corny','text': 'Why did the tomato turn red? Because it saw the salad dressing!'}
我们可以通过Chain
对象的run
方法将其作为Agent
中的Tool
进行简单集成。
为链式连接添加记忆
Chain
支持将BaseMemory
对象作为其memory
参数,从而使Chain
对象能够在多次调用之间保留数据。换句话说,memory
参数使Chain
成为一个有状态的对象。
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemoryconversation = ConversationChain(llm=chat,memory=ConversationBufferMemory()
)conversation.run("Answer briefly. What are the first 3 colors of a rainbow?")
# -> The first three colors of a rainbow are red, orange, and yellow.
conversation.run("And the next 4?")
# -> The next four colors of a rainbow are green, blue, indigo, and violet.
输出:
'The next four colors of a rainbow are green, blue, indigo, and violet.'
基本上,BaseMemory
定义了langchain
存储记忆的接口。它允许通过load_memory_variables
方法读取存储的数据,并通过save_context
方法存储新数据。我们可以在《自然语言处理从入门到应用——LangChain:记忆(Memory》系列文章了解更多信息。
调试链式连接
仅从输出中调试Chain
对象可能会很困难,因为大多数Chain
对象涉及相当数量的输入prompt
预处理和LLM输出后处理。将verbose
设置为True
将在运行时打印出Chain
对象的一些内部状态。
conversation = ConversationChain(llm=chat,memory=ConversationBufferMemory(),verbose=True
)
conversation.run("What is ChatGPT?")
日志输出:
> Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.Current conversation:Human: What is ChatGPT?
AI:> Finished chain.
输出:
'ChatGPT is an AI language model developed by OpenAI. It is based on the GPT-3 architecture and is capable of generating human-like responses to text prompts. ChatGPT has been trained on a massive amount of text data and can understand and respond to a wide range of topics. It is often used for chatbots, virtual assistants, and other conversational AI applications.'
使用SequentialChain将链式连接组合起来
在调用语言模型之后的下一步是对语言模型进行一系列的调用。我们可以使用顺序链式连接来实现这一点,顺序链式连接按照预定义的顺序执行其链接。具体而言,我们将使用SimpleSequentialChain
。这是最简单的顺序链式连接类型,其中每个步骤都具有单个输入/输出,一个步骤的输出是下一个步骤的输入。在本文中,我们的顺序链式连接将首先为产品创建一个公司名称,我们将重用之前初始化的LLMChain
来创建这个公司名称。然后再为产品创建一个口号。我们将初始化一个新的LLMChain
来创建这个口号:
second_prompt = PromptTemplate(input_variables=["company_name"],template="Write a catchphrase for the following company: {company_name}",
)
chain_two = LLMChain(llm=llm, prompt=second_prompt)
现在我们可以将这两个LLMChain结合起来,这样我们就可以一步创建一个公司名称和一个标语。
from langchain.chains import SimpleSequentialChain
overall_chain = SimpleSequentialChain(chains=[chain, chain_two], verbose=True)# Run the chain specifying only the input variable for the first chain.
catchphrase = overall_chain.run("colorful socks")
print(catchphrase)
日志输出:
> Entering new SimpleSequentialChain chain...
Rainbow Socks Co."Put a little rainbow in your step!"> Finished chain.
输出:
"Put a little rainbow in your step!"
使用Chain类创建自定义链式连接
LangChain提供了许多现成的链式连接,但有时我们可能希望为特定的用例创建自定义链式连接。在这个例子中,我们将创建一个自定义链式连接,它将两个LLMChain的输出连接起来。
要创建一个自定义链式连接:
- 创建一个
Chain
类的子类 - 填写
input_keys
和output_keys
属性 - 添加
_call
方法,展示如何执行链式连接
下面的示例演示了这些步骤:
from langchain.chains import LLMChain
from langchain.chains.base import Chainfrom typing import Dict, Listclass ConcatenateChain(Chain):chain_1: LLMChainchain_2: LLMChain@propertydef input_keys(self) -> List[str]:# Union of the input keys of the two chains.all_input_vars = set(self.chain_1.input_keys).union(set(self.chain_2.input_keys))return list(all_input_vars)@propertydef output_keys(self) -> List[str]:return ['concat_output']def _call(self, inputs: Dict[str, str]) -> Dict[str, str]:output_1 = self.chain_1.run(inputs)output_2 = self.chain_2.run(inputs)return {'concat_output': output_1 + output_2}
现在,我们可以尝试运行我们调用的链:
prompt_1 = PromptTemplate(input_variables=["product"],template="What is a good name for a company that makes {product}?",
)
chain_1 = LLMChain(llm=llm, prompt=prompt_1)prompt_2 = PromptTemplate(input_variables=["product"],template="What is a good slogan for a company that makes {product}?",
)
chain_2 = LLMChain(llm=llm, prompt=prompt_2)concat_chain = ConcatenateChain(chain_1=chain_1, chain_2=chain_2)
concat_output = concat_chain.run("colorful socks")
print(f"Concatenated output:\n{concat_output}")
输出:
Concatenated output:Funky Footwear Company"Brighten Up Your Day with Our Colorful Socks!"
参考文献:
[1] LangChain官方网站:https://www.langchain.com/
[2] LangChain 🦜️🔗 中文网,跟着LangChain一起学LLM/GPT开发:https://www.langchain.com.cn/
[3] LangChain中文网 - LangChain 是一个用于开发由语言模型驱动的应用程序的框架:http://www.cnlangchain.com/
相关文章:

自然语言处理从入门到应用——LangChain:链(Chains)-[基础知识]
分类目录:《自然语言处理从入门到应用》总目录 在本文中,我们将学习如何在LangChain中创建简单的链式连接并添加组件以及运行它。链式连接允许我们将多个组件组合在一起,创建一个统一的应用程序。例如,我们可以创建一个链式连接&a…...

[ubuntu]linux服务器每次重启anaconda环境变量失效
云服务器每次重启后conda不能用了,应该是系统自动把设置环境变量清除了。如果想继续使用,则可以运行一下 minconda3激活方法: source ~/miniconda3/bin/activate anaconda3激活方法: source ~/anaconda3/bin/activate 你也修改b…...

【数据结构】如何用栈实现队列?图文解析(LeetCode)
LeetCode链接:232. 用栈实现队列 - 力扣(LeetCode) 注:本文默认读者已掌握栈与队列的基本操作 可以看这篇文章熟悉知识点:【数据结构】栈与队列_字节连结的博客-CSDN博客 目录 做题思路 代码实现 1. MyQueue 2. …...

蓝桥杯上岸每日N题 (闯关)
大家好 我是寸铁 希望这篇题解对你有用,麻烦动动手指点个赞或关注,感谢您的关注 不清楚蓝桥杯考什么的点点下方👇 考点秘籍 想背纯享模版的伙伴们点点下方👇 蓝桥杯省一你一定不能错过的模板大全(第一期) 蓝桥杯省一你一定不…...

基于Python3 的 简单股票 可转债 提醒逻辑
概述 通过本地的定时轮训,结合本地建议数据库。检查股票可转债价格的同事,进行策略化提醒 详细 前言 为什么会有这么个东西出来呢,主要是因为炒股软件虽然有推送,但是设置了价格之后,看到推送也未必那么及时&#…...

Python“牵手”京东工业商品详情数据采集方法,京东工业商数据API申请步骤说明
京东工业平台介绍 京东工业平台是京东集团旗下的一个B2B电商平台,主要面向企业客户提供一站式的采购服务。京东工业平台依托京东强大的供应链和配送能力,为企业用户提供全品类、全渠道、全场景的采购解决方案,涵盖电子元器件、机械配件、办公…...

【LeetCode-中等题】3. 无重复字符的最长子串
题目 题解一:单指针,滑动窗口 思路: 设置一个左指针,来判断下一个元素是否在set集合中,如果不在,就加入集合,right继续,如果在,就剔除重复的元素,计算串的长度…...

【教程】Java 集成Mongodb
【教程】Java 集成Mongodb 依赖 <dependency><groupId>org.mongodb</groupId><artifactId>mongo-java-driver</artifactId><version>3.12.14</version></dependency> <dependency><groupId>cn.hutool</groupId…...

ARM开发,stm32mp157a-A7核中断实验(实现按键中断功能)
1.实验目的:实现KEY1/LEY2/KE3三个按键,中断触发打印一句话,并且灯的状态取反; key1 ----> LED3灯状态取反; key2 ----> LED2灯状态取反; key3 ----> LED1灯状态取反; 2.分析框图: …...

kafka常用命名
kafka服务启动 $KAFKA_HOME/bin/kafka-server-start.sh -daemon config/server.properties 创建Topic $KAFKA_HOME/bin/kafka-topics.sh --create --topic test0--zookeeper 127.0.0.1:2181 --config max.message.bytes12800000 --config flush.messages1 --partitions 5 …...

华为云开发工具CodeArts IDE for C/C++ 开发使用指南
简介 CodeArts IDE是一个集成开发环境(IDE),它提供了开发语言和调试服务。本文主要介绍CodeArts IDE for C/C的基本功能。 1.下载安装 CodeArts IDE for C/C 已开放公测,下载获取免费体验 2.新建C/C工程 CodeArts IDE for C/…...

如何选择最适合你的SOLIDWORKS版本 硕迪科技
SOLIDWORKS是一款广泛应用于工程设计领域的三维计算机辅助设计(CAD)软件,因其强大的功能和易学易用的界面而备受工程师们的青睐。面对众多的SOLIDWORKS版本,比如SW专业版、白金版,租赁订阅版,以及solidwork…...

通过双层负载均衡实现HTTPS代理的高并发处理和容错能力
在互联网应用中,HTTPS代理服务器是承担用户请求的重要角色。当网站面临高并发请求时,单一的服务器可能无法满足需求,会导致性能下降和容错能力不足。为了解决这个问题,我们可以通过双层负载均衡技术来实现高并发处理和容错能力的提…...

Redis 整合中 Redisson 的使用
大家好 , 我是苏麟 , 今天带来 Redisson 使用 . 官方文档 : GitHub - redisson/redisson: Redisson - Easy Redis Java client with features of In-Memory Data Grid. Sync/Async/RxJava/Reactive API. Over 50 Redis based Java objects and services: Set, Multimap, Sorte…...

数据结构(5)
堆 堆可以看作一颗完全二叉树的数组对象。 特性: 1.堆是完全二叉树,除了树最后一层不需要满,其余层次都需要满,如果最后一层不是满的,那么要求左满右不满 2.通常使用数组实现,将二叉树结点依次放入数组中…...

R语言实现网状Meta分析(1)
#R语言实现网状Meta library(gemtc) help(package"gemtc") data<-gemtc::smoking #注意按照实例格式编写数据 net<-mtc.network(data$data.ab) #网状图 plot(net,mode"circle",displaylabelsT,boxed.labelF) summary(net) #网状model model<-mtc…...

Reactor 第十篇 定制一个生产的WebClient
1 为什么要用 WebClient 刚开始尝试使用 Spring WebFlux 的时候,很多人都会使用 Mono.fromFuture() 将异步请求转成 Mono 对象,或者 Mono.fromSupplier() 将请求转成 MOno 对象,这两种方式在响应式编程中都是不建议的,都会阻塞当…...

桃子叶片病害识别(Python代码,pyTorch框架,深度卷积网络模型,很容易替换为其它模型,带有GUI识别界面)
1.分为三类 健康的桃子叶片 ,251张 桃疮痂病一般,857张 桃疮痂病严重,770 张 2. GUI界面识别效果和predict.py识别效果如视频所示桃子叶片病害识别(Python代码,pyTorch框架,深度卷积网络模型࿰…...

matlab使用教程(21)—求函数最值
1. 求函数最优值 1.1求一元函数的最小值 如果给定了一个一元数学函数,可以使用 fminbnd 函数求该函数在给定区间中的局部最小值。例如,请考虑 MATLAB 提供的 humps.m 函数。下图显示了 humps 的图。 x -1:.01:2; y humps(x); plot(x,y) xlabel(x)…...

Redis中 为什么Lua脚本可以保证原子性?
Redis中 为什么Lua脚本可以保证原子性?...

tda4 videnc-test-app: CONTINUOUS and STEPWISE FRAMEINTERVALS not supported
/* videnc-test-app */ https://git.ti.com/cgit/jacinto7_multimedia/ git clone https://git.ti.com/git/jacinto7_multimedia/videnc-test-app.git // 编译 ./autogen.sh ./configure --enable-maintainer-mode --buildi386-linux --hostaarch64-none-linux CC/home/share…...

[已解决] libGL error: MESA-LOADER: failed to open swrast
在新的服务器中配置好虚拟环境后,利用已有的预训练模型test后,可视化时遇到: libGL error: MESA-LOADER: failed to open swrast: /usr/lib/dri/swrast_dri.so: cannot open shared object file: No such file or directory (search paths /u…...

JVM及垃圾回收机制
文章目录 1、JVM组成?各部分作用?1.1 类加载器(Class Loaders)1.2 运行时数据区(Runtime Data Area)1.3 执行引擎(Execution Engine)1.4 本地方法接口(Native Interface&…...

windows11不允许安装winpcap4.1.3
问题:下载安装包后在安装时显示与电脑系统不兼容,不能安装。 原因:winpcap是一个用于Windows操作系统的网络抓包库,有一些安全漏洞,存在被黑客攻击的风险。Windows11为了加强系统安全而禁用了这个库,因此不…...

matlab使用教程(23)—优化函数的参数
本博客向您介绍如何存储或访问向 MATLAB 复合函数(如 fzero 或 integral)传递的数学函数的额外参数。 MATLAB 复合函数基于某个值范围计算数学表达式。这些函数之所以称为复合函数是因为它们是接受函数句柄(函数的指针)作为输入…...

基于“互联网+ 服务供应链”的汽车道路救援系统对策分析
1。 建立“互联网服务供应链”背景下汽车道路救援系统 基于互联网的汽车道路救援,两级服务供应链结构是由服务提供商、服务 集成商和客户组成。“互联网服务供应链”背景下汽车道路救援系统组成, 它是一种 B2B2C 的形式,与前述传统汽车道路…...

浅谈泛在电力物联网在电力设备状态在线监测中的应用
安科瑞 华楠 摘要:随着信息化水平的不断发展,泛在电力物联网的建设提上日程,这对提升变电站电力设备在线监测水平,推动智能电网发展具有重要的指导意义。对基于物联网的电力设备状态监测系统进行了研究,概括了泛在电力…...

低通滤波器和高通滤波器
应用于图像低通滤波器和高通滤波器的实现 需要用到傅里叶变换 #include <opencv2/opencv.hpp> #include <Eigen> #include <iostream> #include <vector> #include <cmath> #include <complex>#define M_PI 3.14159265358979323846…...

VS中插入Qt插件后配置项目笔记
Project下要创建四个文件夹: bin(输出目录\工作目录) 、include(头文件目录) 、lib(动态库目录) 、src(源码目录) 一、主项目模块配置: 1.配置属性——>常规——>输出目录加入(..\..\bin\) 2.配置属性——>调试——>工作目录加入($(OutDir)) 备注&am…...

Hugo·Stack主题·使用及修改
代码折叠 cp themes/hugo折-themt-saick/exampleSlte/config.yamsclass"codefold"><summary class"codefold__title"><span class"codefold__title-text">" {{ with .Get 0}}{{.}}{{else}}click to expand{{ end }} "&…...