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

【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值。

相关文章:

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

🔗 LangChain for LLM Application Development - DeepLearning.AI 学习目标 1、使用Langchain实例化一个LLM的接口 2、 使用Langchain的模板功能,将需要改动的部分抽象成变量,在具体的情况下替换成需要的内容,来达到模板复用效…...

Flutter 中的基本数据类型:num、int 和 double

在 Dart 编程语言中,数值类型的基础是 num,而 int 和 double 则是 num 的子类型。在开发 Flutter 应用时,理解这三者的区别和使用场景是非常重要的。本文将详细介绍 num、int 和 double 的定义及其使用区别。 num num 是 Dart 中的数值类型…...

基于Python+Django,开发的一个在线教育系统

一、项目简介 使用Python的web框架Django进行开发的一个在线教育系统! 二、所需要的环境与组件 Python3.6 Django1.11.7 Pymysql Mysql pure_pagination DjangoUeditor captcha xadmin crispy_forms 三、安装 1. 下载项目后进入项目目录cd Online-educ…...

密码学原理精解【9】

这里写目录标题 迭代密码概述SPN具体算法过程SPN算法基本步骤举例说明注意 轮换-置换网络一、定义与概述二、核心组件三、加密过程四、应用实例五、总结 轮函数理论定义与作用特点与性质应用实例总结 迭代密码理论定义与原理特点与优势应用场景示例发展趋势 AES特点概述一、算法…...

【Nacos】Nacos服务注册与发现 心跳检测机制源码解析

在前两篇文章,介绍了springboot的自动配置原理,而nacos的服务注册就依赖自动配置原理。 Nacos Nacos核心功能点 服务注册 :Nacos Client会通过发送REST请求的方式向Nacos Server注册自己的服务,提供自身的元数据,比如ip地址、端…...

python 66 个冷知识 0720

66个有趣的Python冷知识 一行反转列表 使用切片一行反转列表:reversed_list my_list[::-1] 统计文件单词数量 使用 collections.Counter 统计文件中每个单词的数量:from collections import Counter; with open(file.txt) as f: word_count Counter(f…...

利用PyTorch进行模型量化

利用PyTorch进行模型量化 目录 利用PyTorch进行模型量化 一、模型量化概述 1.为什么需要模型量化? 2.模型量化的挑战 二、使用PyTorch进行模型量化 1.PyTorch的量化优势 2.准备工作 3.选择要量化的模型 4.量化前的准备工作 三、PyTorch的量化工具包 1.介…...

Android 小白菜鸟从入门到精通教程

前言 Android一词最早出现于法国作家利尔亚当(Auguste Villiers de l’Isle-Adam)在1886年发表的科幻小说《未来的夏娃》(L’ve future)中。他将外表像人的机器起名为Android。从初学者的角度出发,通过通俗易懂的语言…...

php相关

php相关 ​ 借鉴了小迪安全以及各位大佬的博客,如果一切顺利,会不定期更新。 如果感觉不妥,可以私信删除。 默认有php基础。 文章目录 php相关1. php 缺陷函数1. 与2. MD53. intval()4. preg_match() 2. php特性1. php字符串解析特性2. 杂…...

uniapp上传功能用uni-file-picker实现

文章目录 html代码功能实现css样式代码 html代码 <uni-file-pickerselect"onFileSelected"cancel"onFilePickerCancel"limit"1"class"weightPage-upload-but"file-mediatype"image"></uni-file-picker><imag…...

【PPT笔记】1-3节 | 默认设置/快捷键/合并形状

文章目录 说明笔记1 默认设置1.1 OFFICE版本选择1.1.1 Office某某数字专属系列1.1.2 Office3651.1.3 产品信息怎么看 1.2 默认设置1.2.1 暗夜模式1.2.2 无限撤回1.2.3 自动保存&#xff08;Office2013版本及以上&#xff09;1.2.4 图片压缩1.2.5 字体嵌入1.2.6 多格式导出1.2.7…...

Qt中的高分辨率及缩放处理

写在前面 使用Qt开发界面客户端&#xff0c;需要考虑不同分辨率及缩放对UI界面的影响&#xff0c;否则会影响整体的交互使用。 问题 高分辨率/缩放设备上图片/图标模糊 若不考虑高分辨及缩放处理&#xff0c;在高分辨率/缩放设备上&#xff0c;软件中的图片、图标可能会出现…...

电机泵盖机器人打磨去毛刺,选德国进口高精度主轴

机器人打磨去毛刺该如何选择主轴呢&#xff1f;首先我们需要考虑的是工件的材质&#xff0c;电机泵盖通常使用铸铁、不锈钢、合金钢等金属材质&#xff0c;因此这类保持的硬度较高&#xff0c;一般会选择功率、扭矩较大的德国进口高精度主轴Kasite 4060 ER-S。 Kasite 4060 ER-…...

Android init.rc各阶段的定义和功能

Android开机优化系列文档-CSDN博客 Android 14 开机时间优化措施汇总-CSDN博客Android 14 开机时间优化措施-CSDN博客根据systrace报告优化系统时需要关注的指标和优化策略-CSDN博客Android系统上常见的性能优化工具-CSDN博客Android上如何使用perfetto分析systrace-CSDN博客A…...

.net dataexcel 脚本公式 函数源码

示例如: ScriptExec(""sum(1, 2, 3, 4)"") 结果等于10 using Feng.Excel.Builder; using Feng.Excel.Collections; using Feng.Excel.Interfaces; using Feng.Script.CBEexpress; using Feng.Script.Method; using System; using System.Collections.Gen…...

HarmonyOS ArkUi @CustomDialog 和promptAction.openCustomDialog踩坑以及如何选择

CustomDialog 内使用Link&#xff0c;如何正常使用 错误使用方式&#xff1a; 定义一个函数&#xff0c;在函数内使用弹窗&#xff0c;如下面代码showDialog&#xff1a; 这种使用方式&#xff0c;无法在自定义的CustomDialog内使用 Link&#xff0c;进行父子双向绑定&#x…...

Python面试题:详细讲解Python的多线程与多进程编程问题

在 Python 中&#xff0c;多线程和多进程编程是并发编程的两种主要方式&#xff0c;用于提高程序的执行效率和响应性。虽然它们都可以实现并发执行&#xff0c;但它们的工作原理和适用场景有所不同。以下是对 Python 多线程和多进程编程的详细讲解&#xff0c;包括它们的工作原…...

前端Canvas入门——用canvas写五子棋?

前言 五子棋的实现其实不难&#xff0c;因为本身就是一个很小的游戏。 至于画线什么的&#xff0c;其实很简单&#xff0c;都是lineTo()&#xff0c;moveTo()就行了。 难的在于——怎么让棋子落入到指定的格子上&#xff0c;怎么判断连子胜利。 当然啦&#xff0c;这部分是…...

[PaddlePaddle飞桨] PaddleDetection-通用目标检测-小模型部署

PaddleDetection的GitHub项目地址 推荐环境&#xff1a; PaddlePaddle > 2.3.2 OS 64位操作系统 Python 3(3.5.1/3.6/3.7/3.8/3.9/3.10)&#xff0c;64位版本 pip/pip3(9.0.1)&#xff0c;64位版本 CUDA > 10.2 cuDNN > 7.6pip下载指令&#xff1a; python -m pip i…...

Golang | Leetcode Golang题解之第239题滑动窗口最大值

题目&#xff1a; 题解&#xff1a; func maxSlidingWindow(nums []int, k int) []int {n : len(nums)prefixMax : make([]int, n)suffixMax : make([]int, n)for i, v : range nums {if i%k 0 {prefixMax[i] v} else {prefixMax[i] max(prefixMax[i-1], v)}}for i : n - 1…...

用ChatGPT 10分钟生成TikTok爆款脚本:5步工作流+3类高转化话术模板(附Prompt库下载)

更多请点击&#xff1a; https://intelliparadigm.com 第一章&#xff1a;ChatGPT TikTok视频创意 在短视频爆发式增长的今天&#xff0c;TikTok 内容创作者亟需高效、可复用的创意生成机制。ChatGPT 可作为智能脚本引擎&#xff0c;将抽象主题快速转化为结构化、高传播性的视…...

Boomi宣布2026财年亚太及日本地区合作伙伴奖得主

数据激活公司Boomi™今日公布其2026财年亚太及日本地区合作伙伴奖获奖名单。该奖项旨在表彰在该地区推动创新和为客户创造可衡量业务成果的Boomi合作伙伴。 本次获奖企业充分运用Boomi企业平台的全面能力实现数据激活、简化复杂流程和加速智能体转型&#xff0c;帮助客户更快创…...

别墅装修里的石材,选错是费钱,用错是麻烦

每次去工地&#xff0c;尤其是那些还没完工的别墅&#xff0c;总能看到角落里堆着几块大板。业主或者设计师会指着它们&#xff0c;兴奋地描述这里用爵士白&#xff0c;那里用鱼肚灰。但说实话&#xff0c;很多时候&#xff0c;这些选择在落地前&#xff0c;就已经埋下了后期保…...

PasteMD:一键解决AI内容到Office文档的格式转换难题

1. 项目概述与痛点解析如果你经常需要写论文、做报告&#xff0c;或者整理从各种AI助手&#xff08;比如ChatGPT、DeepSeek、Kimi&#xff09;那里得到的答案&#xff0c;那你一定遇到过这个让人头疼的问题&#xff1a;辛辛苦苦从网页上复制下来的内容&#xff0c;一粘贴到Word…...

Win10+Ubuntu双系统避坑指南:从Legacy到UEFI启动模式切换的完整流程

Win10Ubuntu双系统避坑指南&#xff1a;从Legacy到UEFI启动模式切换的完整流程 每次看到朋友在双系统安装过程中反复重启、对着报错界面抓耳挠腮的样子&#xff0c;我都会想起自己第一次尝试时连续报废三块硬盘的惨痛经历。特别是当Windows 10已经以Legacy模式安装在MBR磁盘上&…...

HTML5中Canvas文本对齐TextAlign与基线控制

...

谷歌报告:犯罪黑客用AI发现零日漏洞,AI黑客攻击已成为现实!

AI零日漏洞攻击首现周一&#xff0c;谷歌发布报告&#xff0c;首次确认犯罪黑客使用AI大模型发现了一个此前未知的零日漏洞&#xff0c;差点发动大规模攻击。这意味着安全界担心多年的「AI自动挖洞」从理论变为现实。在Anthropic的Mythos模型已找到数千个零日漏洞的背景下&…...

Applite:用图形化界面轻松管理Mac软件的终极解决方案

Applite&#xff1a;用图形化界面轻松管理Mac软件的终极解决方案 【免费下载链接】Applite User-friendly GUI macOS application for Homebrew Casks 项目地址: https://gitcode.com/gh_mirrors/ap/Applite 还在为Mac上繁琐的软件管理而烦恼吗&#xff1f;Applite作为一…...

终极图片去重指南:用AntiDupl.NET轻松释放存储空间,告别重复图片困扰

终极图片去重指南&#xff1a;用AntiDupl.NET轻松释放存储空间&#xff0c;告别重复图片困扰 【免费下载链接】AntiDupl A program to search similar and defect pictures on the disk 项目地址: https://gitcode.com/gh_mirrors/an/AntiDupl 你是否曾为电脑里堆积如山…...

Discord服务器日活破5万后ChatGPT机器人崩了?百万级消息队列+状态分片架构设计(附GitHub星标1.2k的开源模板)

更多请点击&#xff1a; https://intelliparadigm.com 第一章&#xff1a;Discord服务器日活破5万后ChatGPT机器人崩了&#xff1f; 当 Discord 社区日活跃用户突破 5 万时&#xff0c;一个基于 OpenAI API 的 ChatGPT 机器人在高峰时段突然出现 98% 的请求超时与 429&#xf…...