ChatPromptTemplate和AI Message的用法

ChatPromptTemplate的用法

用法1:

python 复制代码
from langchain.chains import LLMChain
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain.chains import LLMMathChain

prompt= ChatPromptTemplate.from_template("tell me the weather of {topic}")
str = prompt.format(topic="shenzhen")
print(str)

打印出:

bash 复制代码
Human: tell me the weather of shenzhen

最终和llm一起使用:

python 复制代码
import ChatGLM
from langchain.chains import LLMChain
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate

from langchain_community.tools.tavily_search import TavilySearchResults
from langchain.chains import LLMMathChain


prompt = ChatPromptTemplate.from_template("who is {name}")
# str = prompt.format(name="Bill Gates")
# print(str)
llm = ChatGLM.ChatGLM_LLM()
output_parser = StrOutputParser()
chain05 = prompt| llm | output_parser
print(chain05.invoke({"name": "Bill Gates"}))

用法2:

python 复制代码
import ChatGLM
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_messages([
                ("system", "You are a helpful AI bot. Your name is {name}."),
                ("human", "Hello, how are you doing?"),
                ("ai", "I'm doing well, thanks!"),
                ("human", "{user_input}"),
            ])

llm = ChatGLM.ChatGLM_LLM()
output_parser = StrOutputParser()
chain05 = prompt| llm | output_parser
print(chain05.invoke({"name": "Bob","user_input": "What is your name"}))

也可以这样:

python 复制代码
import ChatGLM
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate

llm = ChatGLM.ChatGLM_LLM()

prompt = ChatPromptTemplate.from_messages([
                ("system", "You are a helpful AI bot. Your name is {name}."),
                ("human", "Hello, how are you doing?"),
                ("ai", "I'm doing well, thanks!"),
                ("human", "{user_input}"),
            ])


# a = prompt.format_prompt({name="Bob"})

a = prompt.format_prompt(name="Bob",user_input="What is your name") 
print(a)
print(llm.invoke(a))

参考: https://python.langchain.com/docs/modules/model_io/prompts/quick_start

https://python.langchain.com/docs/modules/model_io/prompts/composition

相关推荐
DBA小马哥42 分钟前
Oracle迁移实战:如何轻松跨越异构数据库的学习与技术壁垒
数据库·学习·oracle·信创·国产化平替
无敌最俊朗@44 分钟前
STL-vector面试剖析(面试复习4)
java·面试·职场和发展
哇哈哈&1 小时前
gcc9.2的离线安装,支持gcc++19及以上版本
linux·运维·服务器
暮乘白帝过重山1 小时前
ArkTS ForEach 参数解析:组件与键值生成器
开发语言·数据库
PPPPickup1 小时前
easychat项目复盘---获取联系人列表,联系人详细,删除拉黑联系人
java·前端·javascript
一条咸鱼¥¥¥1 小时前
【运维经验】使用QQ邮箱SMTP服务器设置ssms计划任务完成时邮件发送
运维·服务器·经验分享·sql·sqlserver
LiamTuc1 小时前
Java构造函数
java·开发语言
长安er1 小时前
LeetCode 206/92/25 链表翻转问题-“盒子-标签-纸条模型”
java·数据结构·算法·leetcode·链表·链表翻转
菜鸟plus+2 小时前
N+1查询
java·服务器·数据库
子夜江寒2 小时前
MySQL 表创建与数据导入导出
数据库·mysql