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

相关推荐
一颗青果10 分钟前
C++的锁 | RAII管理锁 | 死锁避免
java·开发语言·c++
Gofarlic_oms113 分钟前
跨国企业Cadence许可证全球统一管理方案
java·大数据·网络·人工智能·汽车
七七七七0725 分钟前
【Redis】Ubuntu22.04安装redis++
数据库·redis·缓存
J_liaty44 分钟前
Spring Security整合JWT与Redis实现权限认证
java·redis·spring·spring-security
子非鱼9211 小时前
MyBatisPlus快速上手
数据库·spring boot·mybatisplus
DBA小马哥1 小时前
从传统数据库到金仓数据库:时序数据迁移的挑战与解决方案
数据库·时序数据库·dba
xlq223221 小时前
4.LInux权限
linux·运维·服务器
txinyu的博客1 小时前
(续篇):手写 C++ 完整 HTTP/1.1 服务器
服务器·网络协议·http
什么都不会的Tristan1 小时前
redis-原理篇-Dict
数据库·redis·缓存
三角叶蕨1 小时前
【苍穹外卖】day1
java