Langchain Chat Model 和 Chat Prompt Template

0. 简介

Chat Model 不止是一个用于聊天对话的模型抽象,更重要的是提供了多角色提示能力(System,AI,Human,Function)。
Chat Prompt Template 则为开发者提供了便捷维护不同角色的提示模板与消息记录的接口。

1. 构造 ChatPromptTemplate

from langchain.prompts.chat import (ChatPromptTemplate,SystemMessagePromptTemplate,AIMessagePromptTemplate,HumanMessagePromptTemplate,
)import os
from dotenv import load_dotenv, find_dotenv# 删除all_proxy环境变量
if 'all_proxy' in os.environ:del os.environ['all_proxy']# 删除ALL_PROXY环境变量
if 'ALL_PROXY' in os.environ:del os.environ['ALL_PROXY']_ = load_dotenv(find_dotenv())template = ("""You are a translation expert, proficient in various languages. \nTranslates English to Chinese."""
)
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
print(type(system_message_prompt))
print(system_message_prompt)human_template = "{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
print(type(human_message_prompt))
print(human_message_prompt)print("*"*40)
# 使用 System 和 Human 角色的提示模板构造 ChatPromptTemplate
chat_prompt_template = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]
)
print(type(chat_prompt_template))
print(chat_prompt_template)print("*"*50)
chat_prompt_prompt_value = chat_prompt_template.format_prompt(text="I love python.")
print(type(chat_prompt_prompt_value))
print(chat_prompt_prompt_value)print("*"*60)
chat_prompt_list = chat_prompt_template.format_prompt(text="I love python.").to_messages()
print(type(chat_prompt_list))
print(chat_prompt_list)

输出:

<class 'langchain_core.prompts.chat.SystemMessagePromptTemplate'>
prompt=PromptTemplate(input_variables=[], input_types={}, partial_variables={}, template='You are a translation expert, proficient in various languages. \n\n    Translates English to Chinese.') additional_kwargs={}
<class 'langchain_core.prompts.chat.HumanMessagePromptTemplate'>
prompt=PromptTemplate(input_variables=['text'], input_types={}, partial_variables={}, template='{text}') additional_kwargs={}
****************************************
<class 'langchain_core.prompts.chat.ChatPromptTemplate'>
input_variables=['text'] input_types={} partial_variables={} messages=[SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=[], input_types={}, partial_variables={}, template='You are a translation expert, proficient in various languages. \n\n    Translates English to Chinese.'), additional_kwargs={}), HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['text'], input_types={}, partial_variables={}, template='{text}'), additional_kwargs={})]
**************************************************
<class 'langchain_core.prompt_values.ChatPromptValue'>
messages=[SystemMessage(content='You are a translation expert, proficient in various languages. \n\n    Translates English to Chinese.', additional_kwargs={}, response_metadata={}), HumanMessage(content='I love python.', additional_kwargs={}, response_metadata={})]
************************************************************
<class 'list'>
[SystemMessage(content='You are a translation expert, proficient in various languages. \n\n    Translates English to Chinese.', additional_kwargs={}, response_metadata={}), HumanMessage(content='I love python.', additional_kwargs={}, response_metadata={})]

2. LCEL 执行

from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser
from langchain.prompts.chat import (ChatPromptTemplate,SystemMessagePromptTemplate,AIMessagePromptTemplate,HumanMessagePromptTemplate,
)
import os
from dotenv import load_dotenv, find_dotenv# 删除all_proxy环境变量
if 'all_proxy' in os.environ:del os.environ['all_proxy']# 删除ALL_PROXY环境变量
if 'ALL_PROXY' in os.environ:del os.environ['ALL_PROXY']_ = load_dotenv(find_dotenv())# 为了结果的稳定性,将 temperature 设置为 0
translation_model = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0)template = ("""You are a translation expert, proficient in various languages. \nTranslates {source_language} to {target_language} in the style of {name}."""
)
system_message_prompt = SystemMessagePromptTemplate.from_template(template)human_template = "{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)# 使用 System 和 Human 角色的提示模板构造 ChatPromptTemplate
m_chat_prompt_template = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]
)
output_parser = StrOutputParser()m_translation_chain = m_chat_prompt_template| translation_model |  StrOutputParser(callbacks=[callback_handler])# Prepare input data
input_data = {"source_language": "English","target_language": "Chinese","name": "严复","text": "Life is full of regrets. All we can do is to minimize them.",
}
input_data1 = {"source_language": "English","target_language": "Chinese","name": "李白","text": "Life is full of regrets. All we can do is to minimize them.",
}# Format the prompt
prompt_value = m_chat_prompt_template.format_prompt(**input_data)
print(type(prompt_value))
print(prompt_value)print(type(prompt_value.to_messages()))
print(prompt_value.to_messages())result = translation_model.invoke(prompt_value)
print(result)
result = m_translation_chain.invoke(input_data)
print(result)
result = m_translation_chain.invoke(input_data1)
print(result)

输出:

<class 'langchain_core.prompt_values.ChatPromptValue'>
messages=[SystemMessage(content='You are a translation expert, proficient in various languages. \n\n    Translates English to Chinese in the style of 严复.', additional_kwargs={}, response_metadata={}), HumanMessage(content='Life is full of regrets. All we can do is to minimize them.', additional_kwargs={}, response_metadata={})]
<class 'list'>
[SystemMessage(content='You are a translation expert, proficient in various languages. \n\n    Translates English to Chinese in the style of 严复.', additional_kwargs={}, response_metadata={}), HumanMessage(content='Life is full of regrets. All we can do is to minimize them.', additional_kwargs={}, response_metadata={})]
content='人生充满了遗憾。我们所能做的就是尽量减少它们。' additional_kwargs={'refusal': None} response_metadata={'token_usage': {'completion_tokens': 31, 'prompt_tokens': 53, 'total_tokens': 84, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'gpt-3.5-turbo-0125', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None} id='run-676a9818-bbbc-44f7-a30e-0ec065aa502f-0' usage_metadata={'input_tokens': 53, 'output_tokens': 31, 'total_tokens': 84, 'input_token_details': {}, 'output_token_details': {}}
人生充满了遗憾。我们所能做的就是尽量减少它们。
人生充滿遺憾,唯有盡量減少。

translation_model.invoke(input_data) 输入参数是字典时报错

result = translation_model.invoke(input_data)
print(result)

报错:

ValueError: Invalid input type <class 'dict'>. Must be a PromptValue, str, or list of BaseMessages.

m_translation_chain.invoke(prompt_value) 输入参数是prompt_value时报错

result = m_translation_chain.invoke(prompt_value)
print(result)

报错:

TypeError: Expected mapping type as input to ChatPromptTemplate. Received <class 'langchain_core.prompt_values.ChatPromptValue'>.

查看属性:

input_schema = m_translation_chain.input_schema.model_json_schema()
print(input_schema)
output_schema = m_translation_chain.output_schema.model_json_schema()
print(output_schema)

输出:

{'properties': {'name': {'title': 'Name', 'type': 'string'}, 'source_language': {'title': 'Source Language', 'type': 'string'}, 'target_language': {'title': 'Target Language', 'type': 'string'}, 'text': {'title': 'Text', 'type': 'string'}}, 'required': ['name', 'source_language', 'target_language', 'text'], 'title': 'PromptInput', 'type': 'object'}{'title': 'StrOutputParserOutput', 'type': 'string'}

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

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

相关文章

对话 Project Astra 研究主管:打造通用 AI 助理,主动视频交互和全双工对话是未来重点

Project Astra 愿景之一&#xff1a;「系统不仅能在你说话时做出回应&#xff0c;还能在持续的过程中帮助你。」 近期&#xff0c;Google DeepMind 的 YouTube 频道采访了 Google DeepMind 研究主管格雷格韦恩 (Greg Wayne)。 格雷格韦恩的研究工作为 DeepMind 的诸多突破性成…

全国青少年信息学奥林匹克竞赛(信奥赛)备考实战之循环结构(for循环语句)(四)

实战训练1—最大差值 问题描述&#xff1a; 输入n个非负整数&#xff0c;找出这个n整数的最大值与最小值&#xff0c;并求最大值和最小值的差值。 输入格式&#xff1a; 共两行&#xff0c;第一行为整数的个数 n&#xff08;1≤n≤1000)。第二行为n个整数的值&#xff08;整…

纯Dart Flutter库适配HarmonyOS

纯Dart Flutter库适配HarmonyOS介绍&#xff1a; Flutter基本组件、Flutter布局组件、Flutter图片组件、Flutter字体、Flutter图标、Fluter路由、flutter动画、 Flutter表单、flutter异步等&#xff0c;纯Dart库无需任何处理&#xff0c;可以直接编译成HarmonyOs应用。 具体步…

LunarVim安装

LunarVim以其丰富的功能和灵活的定制性&#xff0c;迅速在Nvim用户中流行开来。它不仅提供了一套完善的默认配置&#xff0c;还允许用户根据自己的需求进行深度定制。无论是自动补全、内置终端、文件浏览器&#xff0c;还是模糊查找、LSP支持、代码检测、格式化和调试&#xff…

剑指Offer|LCR 015. 找到字符串中所有字母异位词

LCR 015. 找到字符串中所有字母异位词 给定两个字符串 s 和 p&#xff0c;找到 s 中所有 p 的 变位词 的子串&#xff0c;返回这些子串的起始索引。不考虑答案输出的顺序。 变位词 指字母相同&#xff0c;但排列不同的字符串。 示例 1&#xff1a; 输入: s "cbaebaba…

高质量 Next.js 后台管理模板源码分享,开发者必备

高质量 Next.js后台管理模板源码分享&#xff0c;开发者必备 Taplox 是一个基于 Bootstrap 5 和 Next.js 构建的现代化后台管理模板和 UI 组件库。它不仅设计精美&#xff0c;还提供了一整套易用的工具&#xff0c;适合各种 Web 应用、管理系统和仪表盘项目。无论你是初学者还是…

开发场景中Java 集合的最佳选择

在 Java 开发中&#xff0c;集合类是处理数据的核心工具。合理选择集合&#xff0c;不仅可以提高代码效率&#xff0c;还能让代码更简洁。本篇文章将重点探讨 List、Set 和 Map 的适用场景及优缺点&#xff0c;帮助你在实际开发中找到最佳解决方案。 一、List&#xff1a;有序存…

Java包装类型的缓存

Java 基本数据类型的包装类型的大部分都用到了缓存机制来提升性能。 Byte,Short,Integer,Long 这 4 种包装类默认创建了数值 [-128&#xff0c;127] 的相应类型的缓存数据&#xff0c;Character 创建了数值在 [0,127] 范围的缓存数据&#xff0c;Boolean 直接返回 True or Fal…

工程师 - MinGW

MinGW Minimalist GNU for Windows&#xff0c;前身为mingw32&#xff0c;是一个免费开源的软件开发环境&#xff0c;从2010年开始项目停止并不再使用。后续提供MinGW-w64。 MinGW包括: - 移植到Windows上的GNU编译器集&#xff08;GCC&#xff09;&#xff0c;包括C、C、ADA和…

EasyExcel(读取操作和填充操作)

文章目录 1.准备Read.xlsx&#xff08;具有两个sheet&#xff09;2.读取第一个sheet中的数据1.模板2.方法3.结果 3.读取所有sheet中的数据1.模板2.方法3.结果 EasyExcel填充1.简单填充1.准备 Fill01.xlsx2.无模版3.方法4.结果 2.列表填充1.准备 Fill02.xlsx2.模板3.方法4.结果 …

CKA认证 | Day7 K8s存储

第七章 Kubernetes存储 1、数据卷与数据持久卷 为什么需要数据卷&#xff1f; 容器中的文件在磁盘上是临时存放的&#xff0c;这给容器中运行比较重要的应用程序带来一些问题。 问题1&#xff1a;当容器升级或者崩溃时&#xff0c;kubelet会重建容器&#xff0c;容器内文件会…

Python调用R语言中的程序包来执行回归树、随机森林、条件推断树和条件推断森林算法

要使用Python调用R语言中的程序包来执行回归树、随机森林、条件推断树和条件推断森林算法&#xff0c;重新计算中国居民收入不平等&#xff0c;并进行分类汇总&#xff0c;我们可以使用rpy2库。rpy2允许在Python中嵌入R代码并调用R函数。以下是一个详细的步骤和示例代码&#x…

关于JAVA方法值传递问题

1.1 前言 之前在学习C语言的时候&#xff0c;将实参传递给方法&#xff08;或函数&#xff09;的方式分为两种&#xff1a;值传递和引用传递&#xff0c;但在JAVA中只有值传递&#xff08;颠覆认知&#xff0c;基础没学踏实&#xff09; 参考文章&#xff1a;https://blog.csd…

Excel基础知识

一&#xff1a;数组 一行或者一列数据称为一维数组&#xff0c;多行多列称为二维数组&#xff0c;数组支持算术运算&#xff08;如加减乘除等&#xff09;。 行&#xff1a;{1,2,3,4} 数组中的每个值用逗号分隔列&#xff1a;{1;2;3;4} 数组中的每个值用分号分隔行列&#xf…

基于DIODES AP43781+PI3USB31531+PI3DPX1207C的USB-C PD Video 之全功能显示器连接端口方案

随着USB-C连接器和PD功能的出现&#xff0c;新一代USB-C PD PC显示器可以用作个人和专业PC工作环境的电源和数据集线器。 虽然USB-C PD显示器是唯一插入墙壁插座的交流电源输入设备&#xff0c;但它可以作为数据UFP&#xff08;上游接口&#xff09;连接到连接到TCD&#xff0…

gazebo_world 基本围墙。

如何使用&#xff1f; 参考gazebo harmonic的官方教程。 本人使用harmonic的template&#xff0c;在里面进行修改就可以分流畅地使用下去。 以下是world 文件. <?xml version"1.0" ?> <!--Try sending commands:gz topic -t "/model/diff_drive/…

解决无法在 Ubuntu 24.04 上运行 AppImage 应用

在 Ubuntu 24.04 中运行 AppImage 应用的完整指南 在 Ubuntu 24.04 中&#xff0c;许多用户可能会遇到 AppImage 应用无法启动的问题。即使你已经设置了正确的文件权限&#xff0c;AppImage 仍然拒绝运行。这通常是由于缺少必要的库文件所致。 问题根源&#xff1a;缺少 FUSE…

Pytorch使用手册-DCGAN 指南(专题十四)

1. Introduction 本教程将通过一个示例介绍 DCGANs(深度卷积生成对抗网络)。我们将训练一个生成对抗网络(GAN),在给它展示大量真实名人照片后,它能够生成新的“名人”图片。这里的大部分代码来源于 PyTorch 官方示例中的 DCGAN 实现,而本文档将对该实现进行详细解释,并…

springboot配置oracle+达梦数据库多数据源配置并动态切换

项目场景&#xff1a; 在工作中很多情况需要跨数据库进行数据操作,自己总结的经验希望对各位有所帮助 问题描述 总结了几个问题 1.识别不到mapper 2.识别不到xml 3.找不到数据源 原因分析&#xff1a; 1.配置文件编写导致识别mapper 2.配置类编写建的格式有问题 3.命名…

html+css+js网页设计 美食 家美食1个页面

htmlcssjs网页设计 美食 家美食1个页面 网页作品代码简单&#xff0c;可使用任意HTML辑软件&#xff08;如&#xff1a;Dreamweaver、HBuilder、Vscode 、Sublime 、Webstorm、Text 、Notepad 等任意html编辑软件进行运行及修改编辑等操作&#xff09;。 获取源码 1&#xf…