一、Prompt 模板与提示词工程
提示词工程,解决输入问题
- 通常使用
PromptTemplate管理单段提示词,PromptTemplate适合普通文本提示词 - 使用
ChatPromptTemplate管理聊天消息,ChatPromptTemplate会生成消息列表,适合聊天模型。
基础示例:
PromptTemplate:
from langchain_core.prompts import PromptTemplate prompt_template = PromptTemplate.from_template( "请为商品 {product_name} 写一句广告语,突出卖点:{selling_points}" ) prompt = prompt_template.invoke( { "product_name": "无线鼠标", "selling_points": "静音、续航长、轻便", } ) print(prompt.text)ChatPromptTemplate:
from langchain_core.prompts import ChatPromptTemplate chat_prompt = ChatPromptTemplate.from_messages([ ("system", "你是简历信息提取助手,严格按照格式提取信息"), ("human", "{user_content}") ]) # 填充占位变量 messages = chat_prompt.invoke({"user_content": "我叫张三,30岁,从事大模型开发10年"})提示词工程不只是 “写提示词”,在项目中目标明确:
- 清晰定义模型角色、输出约束;
- 统一指令格式,降低模型输出随机性;
- 预留占位符,支持业务动态数据注入;
- 为后续结构化输出打下基础。
二、第四章:结构化输出与 OutputParser
2.1 业务痛点
大模型原生返回自由自然语言文本,后端程序无法直接读取字段。 例如简历提取场景,我们需要直接拿到姓名、年龄、工作年限、技能列表结构化数据,而不是一段自由文字。
LangChain 提供三套主流方案实现结构化输出:
- StrOutputParser:将模型回复转换成字符串
PydanticOutputParser:传统解析方案(提示词约束 + 文本解析)with_structured_output():官方推荐现代方案(优先利用模型 Function Calling)
2.2实例代码StrOutputParser:
from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from utils.model_factory import get_deepSeek_model model=get_deepSeek_model() chat_prompt=ChatPromptTemplate.from_messages( [ ("system","你是一个内容编辑工程师,擅长提炼文本重点"), ("human","""请将下面内容总结成一句话,不超过 50 字。 内容:{question}""") ] ) prompt=chat_prompt.invoke({ "question":"LangChain 是一个用于开发大模型应用的框架," "提供模型调用、Prompt 管理、文档处理、检索和工具调用等能力。" }) resp=model.invoke(prompt) # 第一种写法 print(resp.content) # 第二种写法,也是我们建议的写法 parser=StrOutputParser() text=parser.invoke(resp) print(text)实例代码PydanticOutputParser:
from langchain_core.output_parsers import PydanticOutputParser from langchain_core.prompts import ChatPromptTemplate from pydantic import BaseModel, Field from utils.model_factory import get_deepSeek_model model=get_deepSeek_model() class ResumeInfo(BaseModel): name:str=Field(description="姓名") years_of_experience: int = Field(description="工作年限") skills: list[str] = Field(description="掌握的技术技能") target_position: str = Field(description="目标岗位") parser=PydanticOutputParser(pydantic_object=ResumeInfo) # 格式化指令 format_instructions=parser.get_format_instructions() template=ChatPromptTemplate.from_messages([ ("system",""" 你是一名招聘信息分析助手。 请严格按照指定格式返回结果。 {format_instructions} """), ("human","{resume_content}") ]) resume_content=""" 我叫张三,我干大模型开发10年了,我擅长的技术是 python,langchain,fastapi等,我比较喜欢养猫养狗,我想找一份智能体开发的工作。 """ prompt=template.invoke({ "format_instructions":format_instructions, "resume_content":resume_content }) # 调用大模型,获取AIMessage response=model.invoke(prompt) # 将大模型的返回值,进行格式化输出 result=parser.invoke(response) print(result) print(result.name) print(result.years_of_experience) print(result.skills) print(result.target_position)实例代码with_structured_output:
from typing import Literal from langchain_core.prompts import ChatPromptTemplate from pydantic import BaseModel, Field from utils.model_factory import get_deepSeek_model class ReviewAnalysis(BaseModel): sentiment:Literal["正面","负面","中性"]=Field(description="情感分析的值") keywords: list[str] = Field(description="评论中的关键词") summary: str = Field(description="对评论的简短总结") needs_reply: bool = Field(description="商家是否需要回复") model = get_deepSeek_model() template=ChatPromptTemplate.from_messages([ ("system","""你是专业商品评论分析助手,严格遵守以下规则,仅输出纯JSON,无任何多余文字、解释、markdown: 1. 输出JSON必须包含4个字段:sentiment、keywords、summary、needs_reply,缺一不可; 2. sentiment 仅允许三个中文值:「正面」「中性」「负面」,绝对不能使用 mixed / positive / negative 等英文; 3. keywords 是字符串数组,提取评论核心描述词; 4. summary 用一句话概括整条评论优缺点; 5. needs_reply:商品存在质量问题、故障、严重不满设为true,单纯好评设为false。 """), ("human",""" 请分析下面的商品评论: {review} """) ]) prompt = template.invoke({ "review":"鼠标手感不错,也很安静,但是用了两周滚轮就有异响。" }) structurted_model=model.with_structured_output( ReviewAnalysis, method="json_mode" ) response= structurted_model.invoke(prompt) print(response) print(response.sentiment) print(response.keywords) print(response.summary) print(response.needs_reply)三、总结与工程落地建议
- 提示词层面:使用
ChatPromptTemplate管理所有指令,杜绝字符串硬拼接,方便后期迭代、调优提示词; - 结构化输出选型:新项目优先使用
with_structured_output;仅当模型不支持工具调用时,备选PydanticOutputParser; - 模型适配:不同厂商、不同系列模型参数约束存在差异,开发前查阅接口文档,警惕预览版 / 高速模型的参数限制;
- 容错设计:线上环境针对结构化解析增加异常捕获与重试逻辑,防止模型输出格式异常导致服务崩溃。
掌握提示词模板与输出解析,标志着开发从 “简单调用 LLM 对话” 进阶到可落地业务 AI 应用开发,也是后续学习 RAG 知识库、智能体 Agent 的基础。