深入理解 invoke、Prompt Template 与 Tools
深入理解 invoke、Prompt Template 与 Tools
用了一段时间 LangChain,回过头来把基础概念梳理清楚。这篇聊 invoke 的几种调用方式、Prompt Template 的用法,以及 Tools 的工作原理。
invoke 的三种输入格式
from langchain.chat_models import init_chat_model
from langchain_core.messages import SystemMessage, HumanMessage
model = init_chat_model("openai:gpt-4.1-mini")
# 格式一:纯字符串
response = model.invoke("你好")
# 格式二:字典列表(最灵活)
messages = [
{"role": "system", "content": "你是 Python 专家"},
{"role": "user", "content": "什么是生成器?"},
]
response = model.invoke(messages)
# 格式三:消息对象列表
messages = [
SystemMessage(content="你是 Python 专家"),
HumanMessage(content="什么是生成器?"),
]
response = model.invoke(messages)
三种格式都能用。字典列表最灵活,纯字符串最简单,消息对象类型最安全。
invoke 返回的是 AIMessage 对象,除了 content 还有 response_metadata 包含模型名、token 用量等信息。
Prompt Template
模板让你把变量和提示词分离:
from langchain_core.prompts import ChatPromptTemplate, PromptTemplate
# 简单模板
translator = PromptTemplate.from_template(
"将以下{source_lang}文本翻译成{target_lang}: \n{text}"
)
prompt = translator.format(source_lang="英语", target_lang="中文", text="Hello")
# 对话模板
template = ChatPromptTemplate.from_messages([
("system", "你是一个{role}"),
("user", "{question}")
])
重点是 LCEL 链式调用,用管道符把模板和模型串起来:
chain = template | model
response = chain.invoke({
"role": "数学专家",
"question": "一句话介绍勾股定理"
})
这样写代码很简洁,而且每个环节都可以单独测试。
Tools 的工作原理
工具就是带 @tool 装饰器的函数,docstring 是 AI 的说明书:
from langchain_core.tools import tool
@tool
def get_weather(city: str) -> str:
"""获取指定城市的天气信息"""
return "晴天,温度 15°C"
model_with_tools = model.bind_tools([get_weather])
response = model_with_tools.invoke("北京天气如何?")
if response.tool_calls:
print("AI 想调用工具:", response.tool_calls)
bind_tools 把工具信息告诉模型。模型不会直接执行工具,而是返回 tool_calls 告诉你它想调哪个工具、传什么参数。执行由你或框架来做。
小结
invoke 三种格式、Prompt Template 的链式调用、Tools 的声明式定义,这三个是 LangChain 的基本功。理解透了,后面写 Agent 会顺畅很多。