公司动态

LangChain 高阶 Prompt 模板生产级特性

📅 2026/7/21 16:43:56
LangChain 高阶 Prompt 模板生产级特性
# Concept: # Advanced features include validation, partial variables, output parsers, and conditional logic for production applications. # Template Validation Process: # INPUT # Template Variables # → # VALIDATE # Check Rules # → # OUTPUT # Safe Prompt from langchain_core.prompts import PromptTemplate from langchain_core.output_parsers import PydanticOutputParser from pydantic import BaseModel, Field # 1. Template with Validation def validate_topic_length(topic): if len(topic) 50: raise ValueError(Topic too long!) return True safe_template PromptTemplate( input_variables[topic], templateWrite a summary about {topic}, validate_templateTrue ) # 2. Partial Templates (Pre-filled variables) partial_template PromptTemplate( input_variables[task], templateAs an expert {role}, please help with: {task}, partial_variables{role: AI consultant} ) # 3. Structured Output with Pydantic class ProductReview(BaseModel): rating: int Field(descriptionRating from 1-5) pros: list[str] Field(descriptionList of advantages) cons: list[str] Field(descriptionList of disadvantages) recommendation: str Field(descriptionFinal recommendation) parser PydanticOutputParser(pydantic_objectProductReview) structured_template PromptTemplate( templateReview this product: {product}\n{format_instructions}, input_variables[product], partial_variables{format_instructions: parser.get_format_instructions()} ) # 4. Conditional Templates def create_conditional_template(user_level): if user_level beginner: template Explain {concept} in very simple terms with examples. elif user_level intermediate: template Explain {concept} with some technical details. else: # advanced template Provide a comprehensive technical explanation of {concept}. return PromptTemplate( input_variables[concept], templatetemplate ) # Test all features print(⚡ Advanced Template Features Demo) print( * 45) # Test partial template print(\n1️⃣ Partial Template:) prompt1 partial_template.format(taskoptimize database queries) print(f {prompt1}) # Test structured output print(\n2️⃣ Structured Output Template:) prompt2 structured_template.format(productiPhone 15) print(f {prompt2[:100]}...) # Test conditional templates print(\n3️⃣ Conditional Templates:) for level in [beginner, intermediate, advanced]: template create_conditional_template(level) prompt template.format(conceptmachine learning) print(f {level.upper()}: {prompt}) # Best Practices Summary print(\n Template Best Practices:) best_practices [ Always validate user inputs, Use partial variables for constants, Structure outputs with Pydantic, Make templates conditional when needed, Keep templates readable and maintainable ] for i, practice in enumerate(best_practices, 1): print(f {i}. {practice})完整逐段代码详解LangChain 高阶 Prompt 模板生产级特性一、顶部注释翻译与核心概念python运行# Concept: # Advanced features include validation, partial variables, output parsers, and conditional logic for production applications. # 核心概念生产级场景下的模板高级能力包含输入校验、预填充变量、输出解析器、条件分支逻辑 # Template Validation Process: # INPUT # Template Variables # → # VALIDATE # Check Rules # → # OUTPUT # Safe Prompt # 模板校验流程 # 输入模板 用户传入变量 # 校验执行自定义规则检查拦截非法输入 # 输出安全、合规的提示词适用场景企业 AI 系统、线上机器人防止超长文本、非法参数、模型输出乱格式等线上故障。二、导入依赖python运行from langchain_core.prompts import PromptTemplate # 结构化输出解析器 from langchain_core.output_parsers import PydanticOutputParser # 数据校验、结构化模型定义 from pydantic import BaseModel, FieldPromptTemplate基础提示词模板PydanticOutputParser约束大模型输出为固定 JSON 结构自动解析BaseModel/FieldPydantic 数据模型定义输出字段、类型、描述模块 1模板输入校验 validate_templatepython运行# 1. Template with Validation def validate_topic_length(topic): if len(topic) 50: raise ValueError(Topic too long!) return True safe_template PromptTemplate( input_variables[topic], templateWrite a summary about {topic}, validate_templateTrue )解析自定义校验函数validate_topic_length限制用户传入的主题长度不能超过 50 字符超长直接抛异常拦截。validate_templateTrue开启模板内置校验格式化前检查必填变量是否缺失配合自定义逻辑实现双重防护。业务价值 线上防止用户传入上万字超长文本减少 Token 消耗、避免接口报错。模块 2Partial Templates 预填充固定变量partial_variablespython运行# 2. Partial Templates (Pre-filled variables) partial_template PromptTemplate( input_variables[task], templateAs an expert {role}, please help with: {task}, partial_variables{role: AI consultant} )关键说明模板有两个占位符{role}、{task}partial_variables提前写死固定不变的值不需要调用.format()时传入input_variables只保留动态变化的task渲染示例partial_template.format(taskoptimize database queries)结果plaintextAs an expert AI consultant, please help with: optimize database queries适用场景固定身份、固定规则、固定上下文常量不用每次调用重复传参。模块 3Pydantic 结构化输出约束生产最常用python运行# 3. Structured Output with Pydantic # 定义标准化输出数据结构 class ProductReview(BaseModel): rating: int Field(descriptionRating from 1-5) pros: list[str] Field(descriptionList of advantages) cons: list[str] Field(descriptionList of disadvantages) recommendation: str Field(descriptionFinal recommendation) # 绑定解析器与数据模型 parser PydanticOutputParser(pydantic_objectProductReview) structured_template PromptTemplate( templateReview this product: {product}\n{format_instructions}, input_variables[product], # 预填充自动生成格式要求文本注入提示词 partial_variables{format_instructions: parser.get_format_instructions()} )分步拆解BaseModel定义模型需要返回的字段、数据类型Field给模型字段注释说明PydanticOutputParser根据模型自动生成一段标准指令告诉 LLM 必须输出符合规范的 JSONparser.get_format_instructions()生成格式化规则通过partial_variables预填入模板最终发给 LLM 的 Prompt 会自带强制格式要求模型返回后可直接用parser.parse()转为 Python 对象无需手动字符串分割。业务价值后端可直接读取评分、优缺点列表用于数据库存储、报表统计解决大模型自由文本无法程序解析的痛点。模块 4条件分支模板 Conditional Templatespython运行# 4. Conditional Templates def create_conditional_template(user_level): # 根据用户等级返回不同难度的模板 if user_level beginner: template Explain {concept} in very simple terms with examples. elif user_level intermediate: template Explain {concept} with some technical details. else: # advanced 高阶用户 template Provide a comprehensive technical explanation of {concept}. return PromptTemplate( input_variables[concept], templatetemplate )逻辑根据用户身份 / 权限 / 知识水平动态切换提示词新手通俗大白话 案例中级带少量专业细节专家完整深度技术讲解拓展生产中可结合用户角色、VIP 等级、业务场景动态生成模板一套代码适配多类人群。测试代码执行逻辑python运行# Test all features print(⚡ Advanced Template Features Demo) print( * 45) # 1. 测试预填充变量模板 print(\n1️⃣ Partial Template:) prompt1 partial_template.format(taskoptimize database queries) print(f {prompt1}) # 2. 测试结构化输出模板 print(\n2️⃣ Structured Output Template:) prompt2 structured_template.format(productiPhone 15) print(f {prompt2[:100]}...) # 截取前100字符避免过长 # 3. 测试条件分支模板 print(\n3️⃣ Conditional Templates:) for level in [beginner, intermediate, advanced]: template create_conditional_template(level) prompt template.format(conceptmachine learning) print(f {level.upper()}: {prompt})循环调用不同功能模板打印最终拼接完成的 Prompt 字符串直观查看渲染效果。生产级最佳实践总结python运行# Best Practices Summary print(\n Template Best Practices:) best_practices [ Always validate user inputs, # 始终校验用户输入 Use partial variables for constants, # 固定常量使用预填充变量 Structure outputs with Pydantic, # 使用Pydantic标准化输出 Make templates conditional when needed, # 按需使用条件模板分支 Keep templates readable and maintainable # 保证模板易读、易维护 ] for i, practice in enumerate(best_practices, 1): print(f {i}. {practice})整体四大能力汇总表格功能作用线上优势输入校验拦截超长 / 非法参数减少接口报错、控制 Token 成本partial_variables预填固定常量减少重复传参模板统一管理Pydantic 结构化输出强制 JSON 格式返回程序可直接解析便于入库、统计条件模板动态切换提示词一套代码适配多用户、多业务场景运行前置依赖安装bash运行pip install langchain-core pydantic