LangChain学习笔记--Model I/O 模块部分 1.5 Prompt Template(提示词模板)
LangChain学习笔记--Model I/O 模块部分 1.5 Prompt Template(提示词模板)
介绍
Prompt Template 可以理解为一种“提示词模板”。来自langchain_core.prompts中
它的核心是:把固定的提示内容先写好,并预留几个可替换的位置,等实际运行时再把具体内容填进去,生成最终给模型的输入。
它的主要作用有三点:
第一,方便复用。
同一类任务只需要换问题、上下文或主题时,不必每次都重写整段提示词。
第二,让提示更清晰。
可以把“固定指令”和“变化内容”分开,结构更规整,也更容易维护。
第三,便于和 LangChain 的其他组件配合。
比如用户问题、检索到的资料、系统要求,都可以统一填进模板,再交给模型处理。
简要说,Prompt Template 的价值就是:
把 prompt 从“临时拼接的文本”变成“可复用、可管理的模板”。
如果你接着学 LangChain,下一个常见问题就是它和 ChatPromptTemplate 有什么区别。
有哪些常用的模板?
1. PromptTemplate
最基础的文本模板。
适合把一整段提示词写成固定格式,再把变量填进去。
适用场景:
- 单轮问答
- 摘要
- 翻译
- 分类
- 信息抽取
2. ChatPromptTemplate
专门给聊天模型用的模板。
它不是一整块纯文本,而是把 prompt 按角色拆成不同消息,比如:
- system:系统要求
- human:用户输入
- ai:示例回答
这是现在最常用的一类,因为大多数模型都是聊天式接口。
3. MessagesPlaceholder
用于在聊天模板里插入一段“已有消息”。
常见用途:
- 插入聊天历史
- 插入 memory 里的上下文
- 把前面对话接到当前 prompt 中
它本质上不是单独完成任务的模板,而是聊天模板里的一个占位组件。
4. Few-shot Prompt Template
用于在 prompt 里放多个示例,让模型照着示例风格输出。
适用场景:
- 固定输出格式
- 分类任务
- 信息抽取
- 让模型模仿某种回答方式
它的核心思想是:先给几个例子,再给新问题。
PromptTemplate类的使用
PromptTemplate类介绍
from typing import Any
from langchain_core.prompts import PromptTemplate
# =============================================================================
# PromptTemplate 参数说明
# =============================================================================
# 标识规则:
# [必需] : 定义模板时必须明确的参数
# [常用] : 业务开发中高频使用的参数
# [可选] : 按具体场景决定是否配置
# [扩展] : 用于类型约束、解析、追踪等扩展能力
# =============================================================================
prompt = PromptTemplate(
# -------------------------------------------------------------------------
# template: str
# -------------------------------------------------------------------------
# [必需] [常用]
#
# 作用:
# 定义模板正文。
#
# 使用方式:
# 在字符串中使用 {变量名} 表示占位符。
#
# 示例:
# "请用{style}风格解释:{topic}"
#
template="请用{style}风格解释:{topic}",
# -------------------------------------------------------------------------
# input_variables: list[str]
# -------------------------------------------------------------------------
# [常用]
#
# 作用:
# 声明模板渲染时需要提供的输入变量。
#
# 使用方式:
# 列表中的变量名必须与 template 中的占位符保持一致。
#
# 注意:
# - 少传变量会报错
# - 变量名写错会报错
#
# 示例:
# template 中有 {style} 和 {topic}
# 则 input_variables=["style", "topic"]
#
# 必填变量:
# - style
# - topic
#
input_variables=["style", "topic"],
# -------------------------------------------------------------------------
# partial_variables: dict[str, Any]
# -------------------------------------------------------------------------
# [常用] [可选]
#
# 作用:
# 预先绑定部分变量,减少重复传参。
#
# 使用方式:
# 将固定变量放入字典中,在渲染时自动参与填充。
#
# 示例:
# partial_variables={"role": "Python教师"}
#
# 说明:
# 如果 template 中包含 {role},且此处已提供 role,
# 则 format() / invoke() 时无需再次传入 role。
#
partial_variables={},
# -------------------------------------------------------------------------
# template_format: str
# -------------------------------------------------------------------------
# [常用] [可选]
#
# 作用:
# 指定模板解析格式。
#
# 使用方式:
# 根据模板语法选择解析器。
#
# 可选值:
# - "f-string"
# - "jinja2"
# - "mustache"
#
# 示例:
# template_format="f-string"
#
template_format="f-string",
# -------------------------------------------------------------------------
# validate_template: bool
# -------------------------------------------------------------------------
# [常用] [可选]
#
# 作用:
# 在模板创建阶段校验模板内容与变量定义的一致性。
#
# 使用方式:
# 设置为 True 时,会在初始化阶段检查占位符与变量声明。
#
# 示例:
# validate_template=True
#
validate_template=True,
# -------------------------------------------------------------------------
# optional_variables: list[str]
# -------------------------------------------------------------------------
# [可选] [扩展]
#
# 作用:
# 声明模板中的可选变量。
#
# 使用方式:
# 将允许缺省的变量名加入列表。
#
# 示例:
# optional_variables=["context"]
#
optional_variables=[],
# -------------------------------------------------------------------------
# input_types: dict[str, Any]
# -------------------------------------------------------------------------
# [可选] [扩展]
#
# 作用:
# 描述输入变量的类型信息。
#
# 使用方式:
# 以变量名为键、类型为值进行声明。
#
# 示例:
# input_types={"age": int, "name": str}
#
input_types={},
# -------------------------------------------------------------------------
# output_parser: Any
# -------------------------------------------------------------------------
# [可选] [扩展]
#
# 作用:
# 为模板关联输出解析器。
#
# 使用方式:
# 将解析器对象传入该参数,用于后续结果解析。
#
# 示例:
# output_parser=some_parser
#
output_parser=None,
# -------------------------------------------------------------------------
# metadata: dict[str, Any]
# -------------------------------------------------------------------------
# [可选] [扩展]
#
# 作用:
# 记录模板相关元信息。
#
# 使用方式:
# 以键值对形式附加调试、追踪或业务标识信息。
#
# 示例:
# metadata={"scene": "tutorial", "version": "v1"}
#
metadata={},
# -------------------------------------------------------------------------
# tags: list[str]
# -------------------------------------------------------------------------
# [可选] [扩展]
#
# 作用:
# 为模板添加分类标签。
#
# 使用方式:
# 以列表形式添加标签字符串。
#
# 示例:
# tags=["tutorial", "prompt_template"]
#
tags=[],
)
# =============================================================================
# 当前模板变量说明
# =============================================================================
# template:
# "请用{style}风格解释:{topic}"
#
# 输入变量:
# style -> [必需] 解释风格
# topic -> [必需] 解释主题
#
# 说明:
# 由于 partial_variables 未预绑定变量,
# 因此 style 和 topic 需要在渲染时显式提供。
# =============================================================================
result = prompt.format(
style="简洁", # [必需] 解释风格
topic="PromptTemplate", # [必需] 解释主题
)
print(result)
# 输出:
# 请用简洁风格解释:PromptTemplate
# =============================================================================
# partial_variables 使用示例
# =============================================================================
# 说明:
# role 在模板创建阶段已经预绑定,
# 因此渲染时只需要传入 topic。
# =============================================================================
prompt_with_partial = PromptTemplate(
template="你是一名{role},请解释:{topic}",
input_variables=["topic"],
partial_variables={"role": "Python教师"},
template_format="f-string",
validate_template=True,
)
result_with_partial = prompt_with_partial.format(
topic="PromptTemplate", # [必需] 解释主题
)
print(result_with_partial)
# 输出:
# 你是一名Python教师,请解释:PromptTemplate
# =============================================================================
# optional_variables 使用示例
# =============================================================================
# 说明:
# context 被声明为可选变量。
# 当业务逻辑允许缺省该变量时,可通过预处理逻辑统一补值。
# =============================================================================
prompt_with_optional = PromptTemplate(
template="问题:{question}\n补充信息:{context}",
input_variables=["question"],
optional_variables=["context"],
partial_variables={"context": "无"},
validate_template=True,
)
result_with_optional = prompt_with_optional.format(
question="什么是 PromptTemplate?", # [必需] 问题内容
)
print(result_with_optional)
# 输出:
# 问题:什么是 PromptTemplate?
# 补充信息:无
# =============================================================================
# input_types / metadata / tags 使用示例
# =============================================================================
# 说明:
# 这些参数不影响模板字符串的渲染结果,
# 主要用于类型描述、元信息附加和标签管理。
# =============================================================================
prompt_with_meta = PromptTemplate(
template="姓名:{name}\n年龄:{age}",
input_variables=["name", "age"],
input_types={"name": str, "age": int},
metadata={"scene": "user_profile", "version": "v1"},
tags=["profile", "demo"],
validate_template=True,
)
result_with_meta = prompt_with_meta.format(
name="Alice", # [必需] 姓名
age=18, # [必需] 年龄
)
print(result_with_meta)
# 输出:
# 姓名:Alice
# 年龄:18
f-string 模板
# 输出:
# text='请用通俗风格解释:PromptTemplate'
# 具体显示形式取决于当前版本返回对象的打印结果
# =============================================================================
# 花括号转义示例
# =============================================================================
# 说明:
# 在 f-string 模板格式中,普通花括号需要使用双花括号转义。
# =============================================================================
prompt_with_braces = PromptTemplate(
template='请输出 JSON: {{"name": "{name}"}}',
input_variables=["name"],
template_format="f-string",
validate_template=True,
)
result_with_braces = prompt_with_braces.format(
name="Alice", # [必需] 姓名
)
print(result_with_braces)
# 输出:
# 请输出 JSON: {"name": "Alice"}
调用示例
from_template() 方法(常用)
from langchain_core.prompts import PromptTemplate
# =============================================================================
# PromptTemplate.from_template(...) 参数说明
# =============================================================================
# 标识规则:
# [必需] : 调用该方法时必须提供的参数
# [常用] : 实际开发中高频使用的参数
# [可选] : 按具体场景决定是否配置
# [扩展] : 用于补充模板对象的附加配置
#
# 方法说明:
# PromptTemplate.from_template(...) 是类方法。
#
# 作用:
# 根据模板字符串直接创建 PromptTemplate 对象。
#
# 返回值:
# PromptTemplate
# =============================================================================
prompt = PromptTemplate.from_template(
# -------------------------------------------------------------------------
# template: str
# -------------------------------------------------------------------------
# [必需] [常用]
#
# 作用:
# 定义模板正文。
#
# 使用方式:
# 在字符串中使用 {变量名} 表示占位符。
#
# 示例:
# "请用{style}风格解释:{topic}"
#
"请用{style}风格解释:{topic}",
# -------------------------------------------------------------------------
# template_format: str
# -------------------------------------------------------------------------
# [常用] [可选]
#
# 作用:
# 指定模板解析格式。
#
# 使用方式:
# 根据模板语法选择解析方式。
#
# 可选值:
# - "f-string"
# - "jinja2"
# - "mustache"
#
# 示例:
# template_format="f-string"
#
template_format="f-string",
# -------------------------------------------------------------------------
# partial_variables: dict[str, Any]
# -------------------------------------------------------------------------
# [常用] [可选]
#
# 作用:
# 预先绑定部分变量,减少渲染时的重复传参。
#
# 使用方式:
# 将固定变量放入字典中,在 format() / invoke() 时自动参与填充。
#
# 示例:
# partial_variables={"role": "Python教师"}
#
# 说明:
# 如果模板中包含已预绑定变量,则渲染时无需再次提供该变量。
#
partial_variables={},
)
partial()方法--等同于partial_variables
"""
功能:部分填充提示模板变量,返回新的模板对象,支持分步传参
接收常用参数:
self (BasePromptTemplate):当前提示词模板实例
**kwargs (str | Callable[[], str]):要预先填充的变量,支持固定字符串/无参返回字符串的函数
输出参数:
BasePromptTemplate:已预填充部分变量的新提示模板
"""
from langchain_core.prompts import PromptTemplate
#定义多变量模板
template1 = PromptTemplate(
template="请评价{product}的优缺点,包括{aspect1}和{aspect2}。",
input_variables=["product"],
)
# partial()调用完以后,不会对调用者这个模板对象产生影响;而其返回值是一个新的模板
template1 = template.partial(aspect1="电池续航",aspect2="拍照质量")
#上部分等同于(14-20行)
template = PromptTemplate(
template="请评价{product}的优缺点,包括{aspect1}和{aspect2}。",
input_variables=["product", "aspect1", "aspect2"],
).partial(aspect1="电池续航",aspect2="拍照质量")
#使用模板生成提示词
prompt_1 = template1.format(product="智能手机")
print("提示词1:",prompt_1)
给模板赋值的两种方式 invoke 和 format
format在上述提及,讲invoke
format() : 参数部分:给变量赋值; 返回值:str类型
invoke() : 参数部分:使用的是字典; 返回值:PromptValue类型 ---推荐!
invoke()方法
# =============================================================================
# invoke() 使用示例
# =============================================================================
# 说明:
# invoke() 以字典形式传入变量,适合 Runnable 风格调用。
# =============================================================================
from langchain_core.prompts import PromptTemplate
#定义多变量模板
template = PromptTemplate.from_template(
template="请评价{product}的优缺点,包括{aspect1}和{aspect2}。")
#使用模板生成提示词
prompt_1 = template.invoke(
input={
'product':'智能手机',
'aspect1':'电池续航',
'aspect2':'拍照质量'
}
)
print(prompt_1)
print(type(prompt_1))
几条常用原则(个人观点):
- 赋值时 invoke 多于 format
- 创建模板时,from_template() 多于直接向类传值
结合大模型的使用
from langchain_openai import ChatOpenAI
from langchain_core.prompts import PromptTemplate
import os
import dotenv
#加载配置文件
dotenv.load_dotenv()
chat_model = ChatOpenAI(
temperature=0.7,
model="GLM-4.5-Air",
openai_api_key=os.getenv("ZHIPUAI_API_KEY"),
openai_api_base=os.getenv("ZHIPUAI_BASE_URL")
)
# 生成提示词模板
template = PromptTemplate.from_template(
template="请简要评价{product}的优缺点,包括{aspect1}和{aspect2}。字数100字以内")
# 给模板的变量赋值
prompt = template.invoke(
input={"product":"智能手机","aspect1":"电池续航","aspect2":"拍照质量"}
)
# 调用大模型,将提示词传入
response= chat_model.invoke(prompt)
print(response.content)
print(type(response))
具体使用:ChatPromptTemplate
4.4.1 使用说明
ChatPromptTemplate是创建 聊天消息列表 的提示模板。它比普通 PromptTemplate 更适合处理多角色、多轮次的对话场景。
特点:
支持 System / Human / AI 等不同角色的消息模板
对话历史维护
参数类型:列表参数格式是tuple类型( role :str content :str 组合最常用)
元组的格式为:
(role: str | type, content: str | list[dict] | list[object])
其中 role 是:字符串(如 "system" 、 "human" 、 "ai" )
实例化方式
- 使用构造方法
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
# 创建实例
chat_prompt_template = ChatPromptTemplate(
messages=[
("system", "你是一个AI助手,你的名字叫{name}"),
("human", "我的问题是{question}")
],
input_variables=["name", "question"],
)
response = chat_prompt_template.invoke(input={"name": "小智", "question": "1 + 2 * 3 = ?"})
更简洁的创建
from langchain_core.prompts import ChatPromptTemplate
# 创建实例
chat_prompt_template = ChatPromptTemplate([
("system", "你是一个AI助手,你的名字叫{name}"),
("human", "我的问题是{question}")
])
- 方式2:调用from_messages()
from langchain_core.prompts import ChatPromptTemplate
# 创建实例
# chat_prompt_template = ChatPromptTemplate([
# ("system","你是一个AI助手,你的名字叫{name}"),
# ("human","我的问题是{question}")
# ])
chat_prompt_template = ChatPromptTemplate.from_messages([
("system", "你是一个AI助手,你的名字叫{name}"),
("human", "我的问题是{question}")
])
response = chat_prompt_template.invoke({"name": "小智", "question": "1 + 2 * 3 = ?"})
模板调用的几种方式
invoke() 、 format() 、 format_messages() 、 format_prompt()
invoke()传入的是字典,返回ChatPromptValue
from langchain_core.prompts import ChatPromptTemplate
# 创建实例
chat_prompt_template = ChatPromptTemplate.from_messages([
("system", "你是一个AI助手,你的名字叫{name}"),
("human", "我的问题是{question}")
])
response = chat_prompt_template.invoke({"name": "小智", "question": "1 + 2 * 3 = ?"})
print(response)
print(type(response)) #<class 'langchain_core.prompt_values.ChatPromptValue'>
format()传入变量的值,返回str
from langchain_core.prompts import ChatPromptTemplate
# 创建实例
chat_prompt_template = ChatPromptTemplate.from_messages([
("system", "你是一个AI助手,你的名字叫{name}"),
("human", "我的问题是{question}")
])
response = chat_prompt_template.format(name="小智", question="1 + 2 * 3 = ?")
print(response)
print(type(response))
format_messages()传入变量的值,返回消息构成的list
from langchain_core.prompts import ChatPromptTemplate
# 创建实例
chat_prompt_template = ChatPromptTemplate.from_messages([
("system", "你是一个AI助手,你的名字叫{name}"),
("human", "我的问题是{question}")
])
response = chat_prompt_template.format_messages(name="小智", question="1 + 2 * 3 = ?")
print(response)
print(type(response)) #<class 'list'>
format_prompt()传入变量的值,返回ChatPromptValue
from langchain_core.prompts import ChatPromptTemplate
# 创建实例
chat_prompt_template = ChatPromptTemplate.from_messages([
("system", "你是一个AI助手,你的名字叫{name}"),
("human", "我的问题是{question}")
])
response = chat_prompt_template.format_prompt(name="小智", question="1 + 2 * 3 = ?")
print(response)
print(type(response)) #<class 'langchain_core.prompt_values.ChatPromptValue'>
如何实现ChatPromptValue与list[messages]、字符串之间的转换
from langchain_core.prompts import ChatPromptTemplate # 创建实例 chat_prompt_template = ChatPromptTemplate.from_messages([ ("system", "你是一个AI助手,你的名字叫{name}"), ("human", "我的问题是{question}") ]) # response = chat_prompt_template.format_prompt(name="小智", question="1 + 2 * 3 = ?") response = chat_prompt_template.invoke({"name": "小智", "question": "1 + 2 * 3 = ?"}) # 将ChatPromptValue类型转换为消息构成的list response_messages = response.to_messages() # print(response_messages) # print(type(response_messages)) # 将ChatPromptValue类型转换为字符串类型 response_to_string = response.to_string() print(response_to_string) print(type(response_to_string))
更丰富的实例化参数类型(创建的时候能传入什么)
本质:不管使用构造方法、还是使用from_message()来创建ChatPromptTemplate的实例,本质上来讲,传入的都是消息构成的列表。
从调用上来讲,我们看到,不管使用构造方法,还是使用from_message(),messages参数的类型都是列表,但是列表的元素的类型是多样的。元素可以是:
字符串类型、字典类型、消息类型、元组构成的列表(最常用、最基础、最简单)、Chat提示词模板类型、消息提示词模板类型
from langchain_core.prompts import ChatPromptTemplate
#第1种方式 元组1
chat_prompt_template1 = ChatPromptTemplate(
messages=[
("system", "你是一个AI助手,你的名字叫{name}"),
("human", "我的问题是{question}")
]
)
#第1种方式 元组2
chat_prompt_template2 = ChatPromptTemplate.from_messages([
("system", "你是一个AI助手,你的名字叫{name}"),
("human", "我的问题是{question}")
])
response = chat_prompt_template1.invoke({"name": "小智", "question": "1 + 2 * 3 = ?"})
# 第2种方式 字符串
hat_prompt_template = ChatPromptTemplate.from_messages([
"我的问题是{question}" #默认的角色是:human !
])
#
response = chat_prompt_template.invoke({"question": "1 + 2 * 3 = ?"})
print(response)
# 第3种方式 字典
chat_prompt_template = ChatPromptTemplate.from_messages([
{"role": "system", "content": "我是一个人工智能助手,我的名字叫{name}"},
{"role": "human", "content": "我的问题是{question}"},
])
response = chat_prompt_template.invoke({"name": "小智", "question": "1 + 2 * 3 = ?"})
print(response)
# 第4种方式 消息类型
chat_prompt_template = ChatPromptTemplate.from_messages([
SystemMessage(content="我是一个人工智能助手,我的名字叫{name}"),
HumanMessage(content="我的问题是{question}")
])
# response = chat_prompt_template.invoke({"name":"小智", "question":"1 + 2 * 3 = ?"})
response = chat_prompt_template.invoke({})
print(response)
# 第5种方式 Chat提示词模板类型
## 使用 BaseChatPromptTemplate(嵌套的 ChatPromptTemplate)
nested_prompt_template1 = ChatPromptTemplate.from_messages([
("system", "我是一个人工智能助手,我的名字叫{name}")
])
nested_prompt_template2 = ChatPromptTemplate.from_messages([
("human", "很高兴认识你,我的问题是{question}")
])
prompt_template = ChatPromptTemplate.from_messages([
nested_prompt_template1,
nested_prompt_template2
])
prompt_template.format_messages(name="小智", question="你为什么这么帅?")
# 第6种方式 消息提示词模板类型
# 创建消息模板
system_template = "你是一个专家{role}"
system_message_prompt = SystemMessagePromptTemplate.from_template(system_template)
human_template = "给我解释{concept},用浅显易懂的语言"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
# 组合成聊天提示模板
chat_prompt = ChatPromptTemplate.from_messages([
system_message_prompt,
human_message_prompt
])
# 格式化提示
formatted_messages = chat_prompt.format_messages(
role="物理学家",
concept="相对论"
)
print(formatted_messages)
结合LLM
# 1、提供大模型
from langchain_openai import ChatOpenAI
import os
import dotenv
#加载配置文件
dotenv.load_dotenv()
# 获取对话模型:
chat_model = ChatOpenAI(
model="glm-4.5-air",
temperature=0.7,
openai_api_key=os.getenv("ZHIPUAI_API_KEY"),
openai_api_base=os.getenv("ZHIPUAI_BASE_URL")
)
# 2、通过Chat提示词模板,创建提示词
from langchain_core.prompts import ChatPromptTemplate
# 创建实例
chat_prompt_template = ChatPromptTemplate.from_messages([
("system", "你是一个AI助手,你的名字叫{name}"),
("human", "我的问题是{question}")
])
prompt_response = chat_prompt_template.invoke({"name": "小智", "question": "1 + 2 * 3 = ?"})
# 3、通过大模型调用提示词,得到响应数据
response = chat_model.invoke(prompt_response)
print(response.content)
具体使用: 少量示例的提示词模板的使用
FewShotPromptTemplate: 与PromptTemplate一起使用
FewShotChatMessagePromptTemplate:与ChatPromptTemplate一起使用
Few-shot Prompt Template的使用
给模型一个小的示例,从而学习会新的规则
import os
import dotenv
from langchain_core.prompts import FewShotPromptTemplate
from langchain_openai import ChatOpenAI
dotenv.load_dotenv()
# # 未提供示例的情况
# chat_model = ChatOpenAI(model="glm-4.5-air",
# temperature=0.4,
# api_key=os.getenv("ZHIPUAI_API_KEY"),
# base_url=os.getenv("ZHIPUAI_BASE_URL")
# )
# res = chat_model.invoke("2 🦜 9是多少?")
# print(res.content)
import os
import dotenv
from langchain_core.prompts import FewShotPromptTemplate
from langchain_openai import ChatOpenAI
dotenv.load_dotenv()
# 提供示例的情况
from langchain_core.prompts import PromptTemplate
# 创建PromptTemplate的实例
example_prompt = PromptTemplate.from_template(
template="input:{input}\noutput:{output}",
)
# 提供一些示例
examples = [
{"input": "北京天气怎么样", "output": "北京市"},
{"input": "南京下雨吗", "output": "南京市"},
{"input": "武汉热吗", "output": "武汉市"}
]
# 创建FewShotPromptTemplate的实例
few_shot_template = FewShotPromptTemplate(
example_prompt=example_prompt,
examples = examples,
suffix="input:{input}\noutput:", #声明在示例后面的提示词模板
input_variables=["input"],
)
chat_prompt = few_shot_template.format_prompt(input="天津会下雨吗?")
chat_model = ChatOpenAI(
model="glm-4.5-air",
temperature=0.4,
api_key=os.getenv("ZHIPUAI_API_KEY"),
base_url=os.getenv("ZHIPUAI_BASE_URL")
)
res = chat_model.invoke(chat_prompt)
print(res.content)
chat_model = ChatOpenAI(model="glm-4.5-air",
temperature=0.4,
api_key=os.getenv("ZHIPUAI_API_KEY"),
base_url=os.getenv("ZHIPUAI_BASE_URL")
)
res = chat_model.invoke("2 🦜 9是多少?")
print(res.content)
第二个例子
#1、创建提示模板
from langchain_core.prompts import PromptTemplate
# 创建提示模板,配置一个提示模板,将一个示例格式化为字符串
prompt_template = "你是一个数学专家,算式: {input} 值: {output} 使用: {description} "
# 这是一个提示模板,用于设置每个示例的格式
prompt_sample = PromptTemplate.from_template(prompt_template)
#2、提供示例
examples = [
{"input": "2+2", "output": "4", "description": "这是加法运算"},
{"input": "5-2", "output": "3", "description": "这是减法运算"},
]
#3、创建一个FewShotPromptTemplate对象
from langchain_core.prompts.few_shot import FewShotPromptTemplate
prompt = FewShotPromptTemplate(
examples=examples,
example_prompt=prompt_sample,
suffix="算式: {input} 值: {output}",
input_variables=["input", "output"]
)
print(prompt.invoke({"input":"2*5", "output":"10"}))
#4、初始化大模型,然后调用
import os
import dotenv
from langchain_openai import ChatOpenAI
dotenv.load_dotenv()
chat_model = ChatOpenAI(model="glm-4.5-air",
temperature=0.8,
api_key=os.getenv("ZHIPUAI_API_KEY"),
base_url=os.getenv("ZHIPUAI_BASE_URL")
)
result = chat_model.invoke(prompt.invoke({"input":"2*5", "output":"10"}))
print(result.content) # 使用: 乘法运算
更多推荐


所有评论(0)