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

相关推荐
RainbowSea18 小时前
12. LangChain4j + 向量数据库操作详细说明
java·langchain·ai编程
RainbowSea18 小时前
11. LangChain4j + Tools(Function Calling)的使用详细说明
java·langchain·ai编程
考虑考虑1 天前
Jpa使用union all
java·spring boot·后端
用户3721574261351 天前
Java 实现 Excel 与 TXT 文本高效互转
java
RestCloud1 天前
SQL Server到Hive:批处理ETL性能提升30%的实战经验
数据库·api
RestCloud1 天前
为什么说零代码 ETL 是未来趋势?
数据库·api
浮游本尊1 天前
Java学习第22天 - 云原生与容器化
java
ClouGence1 天前
CloudCanal + Paimon + SelectDB 从 0 到 1 构建实时湖仓
数据库
渣哥1 天前
原来 Java 里线程安全集合有这么多种
java
间彧1 天前
Spring Boot集成Spring Security完整指南
java