自然语言处理从入门到应用——LangChain:链(Chains)-[基础知识]

分类目录:《自然语言处理从入门到应用》总目录


在本文中,我们将学习如何在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的输出连接起来。

要创建一个自定义链式连接:

  1. 创建一个Chain类的子类
  2. 填写input_keysoutput_keys属性
  3. 添加_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/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/53918.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

面试之快速学习计算机网络-http

1. HTTP常见状态码 2. 3开头重定向,4开头客户端错误,5开头服务端错误 2. HTTP 报文 1. start-line:请求行,可以为以下两者之一: 请求行: GET /hello-world2.html HTTP/1.1状态行:HTTP/1.1 200…

数据库——Redis 单线程模型详解

文章目录 Redis 基于 Reactor 模式来设计开发了自己的一套高效的事件处理模型 (Netty 的线程模型也基于 Reactor 模式,Reactor 模式不愧是高性能 IO 的基石),这套事件处理模型对应的是 Redis 中的文件事件处理器(file …

大模型是什么?泰迪大模型能够解决企业哪些痛点?

什么是大模型? 大模型是指模型具有庞大的参数规模和复杂程度的机器学习模型。在深度学习领域,大模型通常是指具有数百万到数十亿参数的神经网络模型。这些模型需要大量的计算资源和存储空间来训练和存储,并且往往需要进行分布式计算和特殊…

共享球拍小程序:打破拥有束缚,尽享运动乐趣

市场前景: 随着健身和运动的流行趋势,越来越多的人加入了各种体育项目。然而,拥有球拍作为体育装备的成本较高,对于想要尝试不同运动的人来说,这可能是个阻碍。共享球拍小程序迎合了这一需求,提供了一个经济…

一百六十五、Kettle——用海豚调度器调度Linux资源库中的kettle任务脚本(亲测、附流程截图)

一、目的 在Linux上脚本运行kettle的转换任务、无论是Linux本地还是Linux资源库都成功后,接下来就是用海豚调度Linux上kettle任务 尤其是团队开发中,基本都要使用共享资源库,所以我直接使用海豚调度Linux资源库的kettle任务脚本 二、前提条…

<C++> 内存管理

1.C/C内存分布 让我们先来看看下面这段代码 int globalVar 1; static int staticGlobalVar 1; void Test() {static int staticVar 1;int localVar 1;int num1[10] {1, 2, 3, 4};char char2[] "abcd";char *pChar3 "abcd";int *ptr1 (int *) mal…

【Java 高阶】一文精通 Spring MVC - 转发重定向(四)

👉博主介绍: 博主从事应用安全和大数据领域,有8年研发经验,5年面试官经验,Java技术专家,WEB架构师,阿里云专家博主,华为云云享专家,51CTO 专家博主 ⛪️ 个人社区&#x…

芯讯通SIMCOM A7680C (4G Cat.1)AT指令测试 TCP通信过程

A7680C TCP通信 1、文档准备 去SIMCOM官网找到A7680C的AT指令集 AT指令官网 进入官网有这么多AT指令文件,只需要找到你需要用到的,这里我们用到了HTTP和TCP的,所以下载这两个即可。 2、串口助手 任意准备一个串口助手即可 这里我使用的是XC…

浅析Python爬虫ip程序延迟和吞吐量影响因素

作为一名资深的爬虫程序员,今天我们很有必要来聊聊Python爬虫ip程序的延迟和吞吐量,这是影响我们爬取效率的重要因素。这里我们会提供一些实用的解决方案,让你的爬虫程序飞起来! 网络延迟 首先,让我们来看看网络延迟对…

软件测试知识点总结(一)

文章目录 前言一. 什么是软件测试二. 软件测试和软件调试的区别三. 软件测试和研发的区别四. 优秀的测试人员所应该具备的素质总结 前言 在现实生活中的很多场景下,我们都会进行测试。 比如买件衣服,我们需要看衣服是不是穿着好看,衣服材质如…

sql server删除历史数据

1 函数 datediff函数: DATEDIFF ( datepart , startdate , enddate )datepart的取值可以是year,quarter,Month,dayofyear,Day,Week,Hour,minute,second,millisecond startdate 是从 enddate 减去。如果 startdate 比 enddate 晚,返回负值。 2 例子 删除2023年以…

如何精通大数据开发技术

要精通大数据开发,以下是一些建议: 学习核心概念:深入理解大数据的核心概念,包括分布式计算、分布式存储、数据处理、数据挖掘等。熟悉各种大数据技术栈,如Hadoop、Spark、Kafka、Hive等。 掌握编程语言和工具&#x…

核污水会造成什么影响

目录 1.什么是核污水 2.什么是氚元素 3.氚元素的半衰期 4.核污水对人类健康的影响 5.我们应该采取什么措施保护自己 1.什么是核污水 核污水是指核设施(如核电站、核燃料回收厂等)产生的含有放射性物质的废水。核污水中可能含有放射性同位素、放射性…

百度Q2财报:营收341亿元实现加速增长,净利润高速增长44%,增长强劲全线重构

北京时间8月22日,百度发布了截至2023年6月30日的第二季度未经审计的财务报告。第二季度,百度实现营收341亿元,同比增长15%;归属百度的净利润(non-GAAP)达到80亿元,同比增长44%。营收和利润双双实…

Oracle查锁表(史上最全)

Oracle查锁表 Oracle分两种锁,一种是DDL锁,一种是DML锁。一、Oracle DDL锁的解锁(dba_ddl_locks视图)1.1、查表的DDL锁的详情(kill session脚本、表名、执行锁表的SQL等)1.2、解锁表的DDL锁1.2.1、解锁表的…

sql入门-多表查询

案例涉及表 ----------------------------------建表语句之前翻看之前博客文章 多表查询 -- 学生表 create table studen ( id int primary key auto_increment comment id, name varchar(50) comment 姓名, no varchar(10) comment 学号 ) comment 学生表; insert…

卷积神经网络——下篇【深度学习】【PyTorch】【d2l】

文章目录 5、卷积神经网络5.10、⭐批量归一化5.10.1、理论部分5.10.2、代码部分 5.11、⭐残差网络(ResNet)5.11.1、理论部分5.11.2、代码部分 话题闲谈 5、卷积神经网络 5.10、⭐批量归一化 5.10.1、理论部分 批量归一化可以解决深层网络中梯度消失和…

使用PyMuPDF添加PDF水印

使用Python添加PDF水印的博客文章。 C:\pythoncode\new\pdfwatermark.py 使用Python在PDF中添加水印 在日常工作中,我们经常需要对PDF文件进行处理。其中一项常见的需求是向PDF文件添加水印,以保护文件的版权或标识文件的来源。本文将介绍如何使用Py…

Eureka:集群环境配置

创建三个集群 导包 <!-- 导包--><dependencies><!-- Eureka -server --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-eureka-server</artifactId><version>1.…

[Open-source tool] 可搭配PHP和SQL的表單開源工具_Form tools(1):簡介和建置

Form tools是一套可搭配PHP和SQL的表單開源工具&#xff0c;可讓開發者靈活運用&#xff0c;同時其有數個表單模板和應用模組供挑選&#xff0c;方便且彈性。Form tools已開發超過20年&#xff0c;為不同領域的需求者或開發者提供一個自由和開放的平台&#xff0c;使他們可建構…