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

news2024/9/20 5:30:44

🔗 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_value

text: {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 StructuredOutputParser

gift_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.coloradmin.cn/o/1936615.html

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

相关文章

JavaEE (1)

web开发概述 所谓web开发,指的是从网页中向后端程序发送请求,与后端程序进行 交互. 流程图如下 Web服务器是指驻留于因特网上某种类型计算机的程序. 可以向浏览器等Web客户端提供文档,也可以放置网站文件,让全世界浏览; 它是一个容器&…

新时代:让中药煎制自动化、信息化

新时代:让中药煎制自动化、信息化 现代医疗领域,科技创新始终在为传统医疗服务带来革命性的改进。某行业医疗巨头,一家拥有国家专利100多项的创新型企业,不仅推出了多款中药煎药包装设备,还自主研发了一系列医疗健康体…

tailwindcss——vscode好用的插件

tailwindcss极大的减少了css的书写,提升了开发效率。这个插件也特别好用。 Tailwind CSS IntelliSense

【电子数据取证】关于CoblatStrike的流量特征取证分析

文章关键词:电子数据取证、流量分析、流量取证 一、前言 近期,网络安全团队在对公司内部网络进行安全检查时发现,有五台电脑出现了不明的网络流量。这些电脑并没有执行任何明显的操作,但是网络流量却显示它们正在向外传输数据。…

如何使用 Java 框架监控和反馈持续交付状态

如何使用 Java 框架监控和反馈持续交付状态 在持续交付 (CD) 流程中,及时监控和反馈是至关重要的。通过实时获取有关构建、部署和测试的反馈,团队可以迅速发现并解决问题,从而改善软件质量和缩短交付周期。 Java 框架 Java 生态系统提供了…

django学习入门系列之第四点《写JavaScript的位置选择》

文章目录 往期回顾 位置1:head标签的尾部位置2:body标签的尾部 一般推荐放位置二(无论是文件导入还是直接写) 往期回顾 1.【快速开发网站】 2.【浏览器能识别的标签1】 3.【浏览器能识别的标签2】 4.【浏览器能识别的标签3】 5…

Linux云计算 |【第一阶段】SERVICES-DAY4

主要内容: DHCP概述、PXE批量装机、配置PXE引导、Kickstart自动应答、Cobbler装机平台 一、DHCP服务概述及原理 DHCP动态主机配置协议(Dynamic Host Configuration Protocol),由IETF(Internet网络工程师任务小组&…

最新!CSSCI(2023-2024)期刊目录公布!

【SciencePub学术】据鲁迅美术学院7月16日消息,近日,南京大学中国社会科学研究评价中心公布了中文社会科学引文索引(CSSCI)(2023—2024)数据库最新入选目录。 C刊一般指CSSCI来源期刊,即南大核心…

C++ | Leetcode C++题解之第263题丑数

题目&#xff1a; 题解&#xff1a; class Solution { public:bool isUgly(int n) {if (n < 0) {return false;}vector<int> factors {2, 3, 5};for (int factor : factors) {while (n % factor 0) {n / factor;}}return n 1;} };

GPT-4o mini 比gpt-3.5更便宜(2024年7月18日推出)

https://openai.com/index/gpt-4o-mini-advancing-cost-efficient-intelligence/ 人工智能学习网站 https://chat.xutongbao.top

CTFshow--web--xss

目录 web316 web317~319 web320~326 web327 web328 web329 web330 web331 web332 web333 先在自己的服务器写上代码 <?php$content $_GET[1]; if(isset($content)){file_put_contents(flag.txt,$content); }else{echo no data input; }要拿到管理员的cookie , 而…

BUUCTF逆向wp [MRCTF2020]Xor

第一步 查壳&#xff0c;该题是32位&#xff0c;无壳。 第二步 跟进main&#xff0c;发现反汇编不了 通过下图我们可以发现一串类似字符串的东西 第三步 我们看一下汇编 我们可以得到这些信息&#xff1a;flag的长度为27&#xff08;下面是对本条指令cmp edx 27指令的应用…

隐语隐私计算实训营「联邦学习」第 3 课:隐语架构概览

【隐私计算实训营】是蚂蚁集团隐语开源社区出品的线上课程&#xff0c;自实训营上线以来&#xff0c;获得行业内外广泛关注&#xff0c;吸引上千余名开发者报名参与。本次暑期夏令营课程中&#xff0c;除了最新上线的「联邦学习系列」&#xff0c;还包含了「隐私保护数据分析」…

TypeScript 教程(十):项目配置、代码质量与前端框架集成

目录 前言回顾类型声明文件与异步编程1. tsconfig.json 高级配置a. 基本配置b. 高级配置选项 2. 使用 Webpack 构建 TypeScript 项目a. 安装依赖b. 配置 Webpack 3. 使用 Babel 编译 TypeScripta. 安装依赖b. 配置 Babelc. 配置 Webpack 使用 Babel 4. 使用 ESLint 和 TSLinta.…

【Django】django自带后台管理系统样式错乱,uwsgi启动css格式消失的问题

正常情况&#xff1a; ERROR&#xff1a;&#xff08;css、js文件加载失败&#xff09; 问题&#xff1a;CSS加载的样式没有了&#xff0c;原因&#xff1a;使用了django自带的admin&#xff0c;在使用 python manage.py runserver启动 的时候&#xff0c;可以加载到admin的文…

昇思25天学习打卡营第17天 | 基于MindSpore实现BERT对话情绪识别

昇思25天学习打卡营第17天 | 基于MindSpore实现BERT对话情绪识别 文章目录 昇思25天学习打卡营第17天 | 基于MindSpore实现BERT对话情绪识别BERT模型对话情绪识别BERT模型的文本情绪分类任务数据集数据下载数据加载与预处理 模型构建模型验证模型推理 总结打卡 BERT模型 BERT&…

Python+Flask+MySQL/Sqlite的个人博客系统(前台+后端管理)【附源码,运行简单】

PythonFlaskMySQL/Sqlite的个人博客系统&#xff08;前台后端管理&#xff09;【附源码&#xff0c;运行简单】 总览 1、《个人博客系统》1.1 方案设计说明书设计目标工具列表 2、详细设计2.1 管理员登录2.2 程序主页面2.3 笔记新增界面2.4 文章新增界面2.5 文章/笔记管理界面2…

SpreadsheetLLM:微软对Excel编码的“摊膀伏”

--->更多内容&#xff0c;请移步“鲁班秘笈”&#xff01;&#xff01;<--- SpreadsheetLLM Excel的特点是二维数据格式、灵活的布局和多样化的格式选项。微软最近引入了SpreadsheetLLM&#xff0c;开创了一种高效的编码方法&#xff0c;用于释放和优化LLMs在电子表格上…

[CP_AUTOSAR]_分层软件架构_接口之通信模块交互介绍

目录 1、协议数据单元(PDU)传输2、通信模块的案例2.1、SDU、 PCI & PDU2.2、通信模块构成2.3、从数据传输的角度看Communication2.4、Communication中的接口 在前面 《关于接口的一些说明》 以及  《Memory软件模块接口说明》 中&#xff0c;简要介绍了CP_AUTOSAR分层…

农田自动化闸门的结构组成与功能解析

在现代化的农业节水灌溉领域中&#xff0c;农田自动化闸门的应用越来越广泛。它集成了先进的技术&#xff0c;通过自动化控制实现水资源的精准调度和高效利用。本文将围绕农田自动化闸门的结构组成&#xff0c;详细介绍其各个部件的功能和特点。 农田自动化闸门主要由闸门控制箱…