从指令编排到结构化返回:LangChain Model IO 核心组件深度实践
一、Prompt 模板与提示词工程提示词工程解决输入问题通常使用PromptTemplate管理单段提示词PromptTemplate适合普通文本提示词使用ChatPromptTemplate管理聊天消息ChatPromptTemplate会生成消息列表适合聊天模型。基础示例PromptTemplatefrom 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)ChatPromptTemplatefrom langchain_core.prompts import ChatPromptTemplate chat_prompt ChatPromptTemplate.from_messages([ (system, 你是简历信息提取助手严格按照格式提取信息), (human, {user_content}) ]) # 填充占位变量 messages chat_prompt.invoke({user_content: 我叫张三30岁从事大模型开发10年})提示词工程不只是 “写提示词”在项目中目标明确清晰定义模型角色、输出约束统一指令格式降低模型输出随机性预留占位符支持业务动态数据注入为后续结构化输出打下基础。二、第四章结构化输出与 OutputParser2.1 业务痛点大模型原生返回自由自然语言文本后端程序无法直接读取字段。 例如简历提取场景我们需要直接拿到姓名、年龄、工作年限、技能列表结构化数据而不是一段自由文字。LangChain 提供三套主流方案实现结构化输出StrOutputParser将模型回复转换成字符串PydanticOutputParser传统解析方案提示词约束 文本解析with_structured_output()官方推荐现代方案优先利用模型 Function Calling2.2实例代码StrOutputParserfrom langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from utils.model_factory import get_deepSeek_model modelget_deepSeek_model() chat_promptChatPromptTemplate.from_messages( [ (system,你是一个内容编辑工程师擅长提炼文本重点), (human,请将下面内容总结成一句话不超过 50 字。 内容{question}) ] ) promptchat_prompt.invoke({ question:LangChain 是一个用于开发大模型应用的框架 提供模型调用、Prompt 管理、文档处理、检索和工具调用等能力。 }) respmodel.invoke(prompt) # 第一种写法 print(resp.content) # 第二种写法也是我们建议的写法 parserStrOutputParser() textparser.invoke(resp) print(text)实例代码PydanticOutputParserfrom 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 modelget_deepSeek_model() class ResumeInfo(BaseModel): name:strField(description姓名) years_of_experience: int Field(description工作年限) skills: list[str] Field(description掌握的技术技能) target_position: str Field(description目标岗位) parserPydanticOutputParser(pydantic_objectResumeInfo) # 格式化指令 format_instructionsparser.get_format_instructions() templateChatPromptTemplate.from_messages([ (system, 你是一名招聘信息分析助手。 请严格按照指定格式返回结果。 {format_instructions} ), (human,{resume_content}) ]) resume_content 我叫张三我干大模型开发10年了我擅长的技术是 python,langchain,fastapi等我比较喜欢养猫养狗我想找一份智能体开发的工作。 prompttemplate.invoke({ format_instructions:format_instructions, resume_content:resume_content }) # 调用大模型获取AIMessage responsemodel.invoke(prompt) # 将大模型的返回值进行格式化输出 resultparser.invoke(response) print(result) print(result.name) print(result.years_of_experience) print(result.skills) print(result.target_position)实例代码with_structured_outputfrom 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() templateChatPromptTemplate.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_modelmodel.with_structured_output( ReviewAnalysis, methodjson_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 的基础。