【Langchain大语言模型开发教程】模型、提示和解析

🔗 LangChain for LLM Application Development - DeepLearning.AI

学习目标 

1、使用Langchain实例化一个LLM的接口

2、 使用Langchain的模板功能,将需要改动的部分抽象成变量,在具体的情况下替换成需要的内容,来达到模板复用效果。

3、使用Langchain提供的解析功能,将LLM的输出解析成你需要的格式,如字典。

模型实例化

import os
from dotenv import load_dotenv ,find_dotenv
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
_ = load_dotenv((find_dotenv())) //使用dotenv来管理你的环境变量

 我们选用智谱的API【智谱AI开放平台】来作为我们的基座大模型,通过langchain的chatOpenAI接口来实例化我们的模型。

chat = ChatOpenAI(api_key=os.environ.get('ZHIPUAI_API_KEY'),base_url=os.environ.get('ZHIPUAI_API_URL'),model="glm-4",temperature=0.98)

 这里我们选用的一个例子:通过prompt来转换表达的风格

提示模板化

 我们定义一个prompt

template_string = """Translate the text \
that is delimited by triple backticks \
into a style that is {style}.\
text:```{text}```
"""

使用langchain的模板功能函数实例化一个模板(从输出可以看到这里是需要两个参数style和text)

prompt_template = ChatPromptTemplate.from_template(template_string)'''
ChatPromptTemplate(input_variables=['style', 'text'], 
messages=[HumanMessagePromptTemplate(prompt=PromptTemplate(
input_variables=['style', 'text'], 
template='Translate the text that is delimited 
by triple backticks into a style that is {style}.text:```{text}```\n'))])
'''

 设置我们想要转化的风格和想要转化的内容

#style
customer_style = """American English in a clam and respectful tone"""
#text
customer_email = """
Arrr,I be fuming that me blender lid \
flew off and splattered me kitchen walls \
with smoothie! And to make matters worse, \
the warranty don't cover the cost of \
cleaning up me kitchen. I need yer help \
right now,matey!
"""

 这里我们实例化出我们的prompt

customer_messages = prompt_template.format_messages(style = customer_style,text= customer_email)'''
[HumanMessage(content="Translate the text that is delimited 
by triple backticks into a style 
that is American English in a clam and respectful tone.
text:
```\n
Arrr,I be fuming that me blender lid flew off and 
splattered me kitchen walls with smoothie! 
And to make matters worse, 
the warranty don't cover the cost of cleaning up me kitchen. 
I need yer help right now,matey!
\n```\n")]
'''

这里我们给出一个回复的内容和转化的格式

service_reply= 
"""
Hey there customer,the warranty does 
not cover cleaning expenses for your kitchen 
because it's your fault that you misused your blender 
by forgetting to put the lid on before starting the blender.
Tough luck! see ya!
"""service_style = """
a polite tone that speaks in English pirate
"""

 实例化

service_messages = prompt_template.format_messages(style = service_style , text = service_reply)

 调用LLM查看结果


service_response = chat(service_messages)
print(service_response.content)'''
Avast there, dear customer! Ye be knowin' that the warranty 
be not stretchin' to cover the cleanin' costs of yer kitchen, 
for 'tis a matter of misadventure on yer part. 
Ye did forget to secure the lid upon the blender before engagement, 
leading to a spot o' trouble. Aar, 
such be the ways of the sea! 
No hard feelings, and may the wind be at yer back on the next journey. 
Fare thee well!
'''

 回复结构化

我们现在获得了某个商品的用户评价,我们想要提取其中的关键信息(下面这种形式)

customer_review = """\
This leaf blower is pretty amazing.  It has four settings:\
candle blower, gentle breeze, windy city, and tornado. \
It arrived in two days, just in time for my wife's \
anniversary present. \
I think my wife liked it so much she was speechless. \
So far I've been the only one using it, and I've been \
using it every other morning to clear the leaves on our lawn. \
It's slightly more expensive than the other leaf blowers \
out there, but I think it's worth it for the extra features.
"""{"gift": False,"delivery_days": 5,"price_value": "pretty affordable!"
}

构建一个prompt 模板 

review_template = """\
For the following text, extract the following information:gift: Was the item purchased as a gift for someone else? \
Answer True if yes, False if not or unknown.delivery_days: How many days did it take for the product \
to arrive? If this information is not found, output -1.price_value: Extract any sentences about the value or price,\
and output them as a comma separated Python list.Format the output as JSON with the following keys:
gift
delivery_days
price_valuetext: {text}
"""
prompt_template = ChatPromptTemplate.from_template(review_template)
message = prompt_template.format_messages(text = customer_review)
reponse = chat(message)

 下面是模型的回复看起来好像一样

{"gift": true,"delivery_days": 2,"price_value": ["It's slightly more expensive than the other leaf blowers out there, but I think it's worth it for the extra features."]
}

 我们打印他的类型的时候,发现这其实是一个字符串类型,这是不能根据key来获取value值的。

 引入Langchain的ResponseSchema

from langchain.output_parsers import ResponseSchema
from langchain.output_parsers import StructuredOutputParsergift_schema = ResponseSchema(name="gift",description="Was the item purchased as a gift for someone else? Answer True if yes,False if not or unknown.")
delivery_days_schema = ResponseSchema(name="delivery_days", description="How many days did it take for the product to arrive? If this information is not found,output -1.")
price_value_schema = ResponseSchema(name="price_value", description="Extract any sentences about the value or price, and output them as a comma separated Python list.")
response_schemas = [gift_schema,delivery_days_schema,price_value_schema]
output_parser = StructuredOutputParser.from_response_schemas(response_schemas)
format_instructions = output_parser.get_format_instructions()

 查看一下我们构建的这个结构

 重新构建prompt模板,并进行实例

review_template_2 = """\
For the following text, extract the following information:gift: Was the item purchased as a gift for someone else? \
Answer True if yes, False if not or unknown.delivery_days: How many days did it take for the product\
to arrive? If this information is not found, output -1.price_value: Extract any sentences about the value or price,\
and output them as a comma separated Python list.text: {text}{format_instructions}
"""prompt = ChatPromptTemplate.from_template(template=review_template_2)messages = prompt.format_messages(text=customer_review,format_instructions=format_instructions)

 我们将结果进行解析

output_dict = output_parser.parse(reponse.content){'gift': 'True','delivery_days': '2','price_value': "It's slightly more expensive than the other leaf blowers out there, but I think it's worth it for the extra features."
}

 我们再次查看其类型,发现已经变成了字典类型,并可以通过key去获取value值。

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

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

相关文章

【Linux服务器Java环境搭建】012在linux中安装消息队列RabbitMQ,以及对RabbitMQ设置、启动、开启可视化

系列文章目录 【Linux服务器Java环境搭建】 前言 上一篇博客竟然用了不到半小时就写完了,那就继续吧,如果对此系列感兴趣,可以点击系列【Linux服务器Java环境搭建】进行查看哈,这一篇主要是安装和配置消息队列RabbitMQ。 一、消…

[解决方法]git上传的项目markdown文件的图片无法显示

应该有不少初学者会遇到这种情况 以下是本人摸索出的解决方法 我使用的是typora,首先设置typora的图片设置 文件>偏好设置>图像 如下: 选择这个就会在此文件的同级目录下创建一个assets文件夹来存放此markdown文件的所有图片 然后勾选优先使用相…

monocle3拟时序分析怎么做到多样本间pseudotime值可比?

愿武艺晴小朋友一定得每天都开心 monocle3呢,有好多文章分享了它的流程。跟着学呢,也都能计算出一套pseudotime值。 在跑monocle3时,我就有一个困惑产生了:monocle3计算的pseudotime值在多样本间可比,该怎么做到呀&am…

在 ASP.NET Core Web API 中实现审计跟踪

一.介绍 审计跟踪对于跟踪数据变化、维护安全性规至关重要。在本文中,我们将在 ASP.NET Core Web API 中实现审计跟踪。该示例将涵盖从设置项目到执行 CRUD 操作和验证审计日志的所有内容。 二.先决条件 Visual Studio 或 Visual Studio CodeSQL Server&#xff…

学习大数据DAY20 Linux环境配置与Linux基本指令

目录 Linux 介绍 Linux 发行版 Linux 和 Windows 比较 Linux 就业方向: 下载 CentOS Linux 目录树 Linux 目录结构 作业 1 常用命令分类 文件目录类 作业 2 vim 编辑文件 作业 3 你问我第 19 天去哪了?第 19 天在汇报第一阶段的知识总结,没什…

QT5:多窗口跳转

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助 目录 前言 一、环境 二、步骤 三、代码实现 四、效果图 前言 学习使用qt5完成多窗口(界面)跳转:从主界面可分别跳转至界面一和界面二&#xf…

Spring Boot集成SFTP快速入门Demo

1.什么是SFTP? SFTP(SSH File Transfer Protocol,也称 Secret File Transfer Protocol),是一种基于SSH(安全外壳)的安全的文件传输协议。使用SFTP协议可以在文件传输过程中提供一种安全的加密算…

主从复制 哨兵服务 数据类型 持久化

配置主从复制 一主多从结构 配置一主一从结构 修改配置文件 配置salve服务器 配置带验证的主从复制 查看密码,默认redis服务没有密码 192.168.88.61:6379> config get requirepass 设置密码 192.168.88.61:6379> config set requirepass 123456 输入密码…

Spring Boot2(Spring Boot 的Web开发 springMVC 请求处理 参数绑定 常用注解 数据传递)

目录 一、Spring Boot 的Web开发 1. 静态资源映射规则 2. enjoy模板引擎 二、springMVC 1. springMVC-请求处理 测试: 以post方式请求 限制请求携带的参数 GetMapping 查询 PostMapping 新增 DeleteMapping删除 PutMapping 修改 2. springMVC-参…

HarmonyOS鸿蒙- 跳转系统应用能力

一、通过弹窗点击设置跳转系统应用能力 1、 自定义弹窗效果图 2、 自定义弹窗代码 import { common, Want } from kit.AbilityKit; import { BusinessError } from kit.BasicServicesKit;export function alertDialog() {AlertDialog.show({title: ,message: 当前功能依赖定位…

ranger审计日志对接CDH solr

作者:耀灵 一、准备条件 1、已安装完毕ranger-admin 2、已在CDH上部署solr(注意在安装solr时更改下solr在zk上的节点信息) 二、更改相关配置 1、修改ranger-2.1.0-admin/contrib/solr_for_audit_setup/install.properties SOLR_USERsolr …

音视频环境搭建

整体流程参考: Windows 10开发环境搭建 这里记录一下期间的遇到的问题: 下载的ffmpeg,将ffmpeg的bin目录添加到系统环境变量,然后将SDL的dll动态库拷贝到ffmpeg的bin目录下或将其所在的目录也添加到环境变量,不一定非要…

huawei USG6001v1学习---防火墙相关知识(2)

目录 1.安全策略 2.防火墙的状态检测和会话表技术 3.FTP 4.用户认证 5.认证策略 1.安全策略 传统包过滤技术 --- 其本质就是ACL访问控制列表,根据数据包的特征进行过滤,对比规则, 执行对应的动作; 这里数据包的特征 --- …

题解|2024暑期杭电多校01

【原文链接】 1001.循环位移 字符串 题目大意 给定两个字符串 A , B A,B A,B 。 定义 [ A ] [A] [A] 为字符串 A A A 的循环位移任意次可以得到的所有字符串的集合。 求 B B B 包含 [ A ] [A] [A] 中元素的个数。 解题思路 利用字符串Hash快速匹配。 将 [ A ] [A] …

switch可应用于哪些数据类型说说java中的数组和多维数组

switch可以用于哪些数据类型? switch是一种条件控制语句,根据不同的条件执行不同的代码块。switch使用一个或者多个不同的值来匹配某个表达式的值,并且根据结果来匹配不同的值。switch的语句基本格式 switch(expression&#xf…

Web安全:未验证的重定向和转发.

Web安全:未验证的重定向和转发. 未验证的重定向和转发漏洞是一种常见的Web安全漏洞,它允许攻击者将用户重定向到一个恶意的URL,而不是预期的安全URL。这种漏洞通常发生在应用程序处理重定向和转发请求时,未能对目标URL进行适当的…

探索 PDF 转 Markdown 的项目:MinerU 和 pdfParser

pdfParser 项目是在MinerU 项目 的基础上开发的,增加了表格识别功能 MinerU:综合数据提取工具 MinerU 项目 是一款一站式、开源、高质量的数据提取工具,支持 PDF、网页和电子书的提取。其 Magic-PDF 模块可以将 PDF 转换为 Markdown 格式&a…

display: flex 和 justify-content: center 强大居中

你还在为居中而烦恼吗,水平居中多个元素、创建响应式布局、垂直和水平同时居中内容。它,display: flex 和 justify-content: center 都可以完成! display: flex:将元素定义为flex容器 justify-content:定义项目在主轴…

el-popover嵌套select弹窗点击实现自定义关闭

需求 el-popover弹窗内嵌套下拉选择框,点击el-popover弹出外部区域需关闭弹窗,点击查询、重置需关闭弹窗, 实现 根据需求要自定义弹窗的关闭和显示,首先想到的是visible属性,在实现过程中经过反复的测验&#xff0…

区块链技术实现数字电网内数据可信共享 |《超话区块链》直播预告

随着全球电力市场朝着构建“SmartGrid”和“IntelliGrid”的目标发展,国内电力公司也提出了构建“数字电网”的愿景。清大科越推出新型电力系统区块链服务平台,通过便捷的建链、上链、用链及治链能力,有效解决数字电网各主体间数据共享的信任…