提示模板

使用 LangChain 开发 LLM 应用

Jonathan Bennion

AI Engineer & LangChain Contributor

提示模板

  • 为大语言模型定义提示的"配方"
  • 可包含:指令、示例、补充上下文

带有输入变量占位符的提示模板。

使用 LangChain 开发 LLM 应用

提示模板

from langchain_core.prompts import PromptTemplate


template = "Expain this concept simply and concisely: {concept}"
prompt_template = PromptTemplate.from_template( template=template )
prompt = prompt_template.invoke({"concept": "Prompting LLMs"}) print(prompt)
text='Expain this concept simply and concisely: Prompting LLMs'
使用 LangChain 开发 LLM 应用
llm = HuggingFacePipeline.from_model_id(
    model_id="meta-llama/Llama-3.3-70B-Instruct",
    task="text-generation"
)

llm_chain = prompt_template | llm
concept = "Prompting LLMs" print(llm_chain.invoke({"concept": concept}))
Prompting LLMs (Large Language Models) refers to the process of giving a model a
specific input or question to generate a response.
  • LangChain 表达式语言(LCEL):|(管道)运算符
  • 链(Chain):连接不同组件的调用
使用 LangChain 开发 LLM 应用

聊天模型

  • 聊天角色:systemhumanai
from langchain_core.prompts import ChatPromptTemplate


template = ChatPromptTemplate.from_messages( [ ("system", "You are a calculator that responds with math."), ("human", "Answer this math question: What is two plus two?"), ("ai", "2+2=4"), ("human", "Answer this math question: {math}") ] )
使用 LangChain 开发 LLM 应用

集成 ChatPromptTemplate

llm = ChatOpenAI(model="gpt-4o-mini", api_key='<OPENAI_API_TOKEN>')


llm_chain = template | llm
math='What is five times five?'
response = llm_chain.invoke({"math": math}) print(response.content)
5x5=25
使用 LangChain 开发 LLM 应用

开始练习!

使用 LangChain 开发 LLM 应用

Preparing Video For Download...