LangChain(二)提示词 & 格式化输出

目录

一.三种模板介绍

二.PromptTemplate

三.ChatPromptTemplate

四.FewShotPromptTemplate

五.企业智能体-提示词管理策略

六.格式化输出


一.3种模板介绍

理解提示词模板在 Agent开发中的核心作用,根据任务类型选择合适模板策略
介绍
Prompt Template 主要用于构建和管理与大语言模型( LLM )交互的提示词(Prompt )

python 复制代码
from langchain.prompts import PromptTemplate

# 基础模板示例
template = """
你是一个专业的{role},请完成以下任务:

任务描述:{task_description}
上下文信息:{context}

要求:
1. {requirement_1}
2. {requirement_2}

请按照以下格式回答:
{output_format}
"""

模板的核心价值

  • 标准化:确保提示结构一致性
  • 参数化:动态注入变量,提高复用性
  • 可维护:集中管理提示逻辑

提示模板分类
1. PromptTemplate
⽤途: 最基础的模板,⽤于将变量填⼊⼀个字符串模板中,⽣成给 LLM 的输⼊
2. ChatPromptTemplate
⽤途: 专为聊天模型(如 ChatGPT、Claude、Qwen-Chat 等)设计,⽀持多轮对话结构,包含不同⻆⾊的消息(system / human / AI / generic)


3. FewShotPromptTemplate ( 了解 )
⽤途: 通过提供少量⽰例(few-shot examples)来引导模型⾏为,常⽤于提升模型在特定任务上的表现
通常包含:

  • 一个 example_prompt (定义每个示例的格式)
  • 一组示例数据
  • 可选的 example_selector (动态选择相关示例)
    选择模板策略

二.PromptTemplate

介绍
PromptTemplate 类用于快速构建 包含变量占位符 的提示词模板,并通过传入不同的参数值 动态生成定制化的提示内容。

主要参数说明

  • template :字符串类型,定义提示词模板。其中可包含普通文本和变量占位符(如 {name})
  • input_variables:列表类型,显式声明模板中需要动态传入的变量名。调用时必须为这些变量提供值
  • partial_variables:字典类型,用于预设模板中部分变量的固定值。这些变量在后续调用时无需重复传入

核心方法

  • format() :接收 input_variables 中定义的参数并进行替换,返回最终的提示词字符串

注意

若模板中包含未在 input_variables 中声明但需替换的占位符,将导致格式化失败; 反之,若 input_variables 中的变量未在模板中使用,则会被自动忽略。

python 复制代码
# ============================================================
# PromptTemplate 构建提示词
# ============================================================
from langchain_core.prompts import PromptTemplate

# ============================================================
# 1. 使用构造方法创建提示词模板
# ============================================================
# 定义模板
template = '你是一个{role},请用{style}风格回答问题:{question}'

# 构造方法来创建提示词模版
prompt_template = PromptTemplate(template=template,
                          # input_variables为了方便维护,变量名要保持一致
                          input_variables=["role","style","question"])
print('构造的模板:')
print(prompt_template)
# 变量的填充
filled_prompt1 = prompt_template.format(role='数学老师',style='通俗易懂',question='勾股定理是什么?')
filled_prompt2 = prompt_template.invoke({'role':'数学老师','style':'通俗易懂','question':'勾股定理是什么?'})
print('填充后的模板(即提示词):')
print(filled_prompt1)
print(filled_prompt2.text)

"""
输出:
构造的模板:
input_variables=['question', 'role', 'style'] input_types={} partial_variables={} template='你是一个{role},请用{style}风格回答问题:{question}'
填充后的模板(即提示词):
你是一个数学老师,请用通俗易懂风格回答问题:勾股定理是什么?
你是一个数学老师,请用通俗易懂风格回答问题:勾股定理是什么?
"""

# ============================================================
# 2. 使用 from_template 方法创建提示词模板
# ============================================================
# 定义模板
template = '你是一个{role},请用{style}风格回答问题:{question}'

# 通过from_template方法来创建提示词模版
prompt_template = PromptTemplate.from_template(template)
print('构造的模板:')
print(prompt_template)
# 变量的填充
filled_prompt1 = prompt_template.format(role='数学老师',style='通俗易懂',question='勾股定理是什么?')
filled_prompt2 = prompt_template.invoke({'role':'数学老师','style':'通俗易懂','question':'勾股定理是什么?'})
print('填充后的模板(即提示词):')
print(filled_prompt1)
print(filled_prompt2.text)

"""
输出:
构造的模板:
input_variables=['question', 'role', 'style'] input_types={} partial_variables={} template='你是一个{role},请用{style}风格回答问题:{question}'
填充后的模板(即提示词):
你是一个数学老师,请用通俗易懂风格回答问题:勾股定理是什么?
你是一个数学老师,请用通俗易懂风格回答问题:勾股定理是什么?
"""

# ============================================================
# 3. 使用 partial_variables 参数(部分变量)
# ============================================================
prompt_template = PromptTemplate(
    template = "请评价{product}的优缺点,包括{aspect1}和{aspect2}。",
    input_variables=["product"],
    partial_variables= {"aspect1":"电池","aspect2":"屏幕"}
)
print('构造的模板:')
print(prompt_template)

prompt= prompt_template.format(product="笔记本电脑")
print('填充后的模板(即提示词):')
print(prompt)

"""
输出:
构造的模板:
input_variables=['product'] input_types={} partial_variables={'aspect1': '电池', 'aspect2': '屏幕'} template='请评价{product}的优缺点,包括{aspect1}和{aspect2}。'
填充后的模板(即提示词):
请评价笔记本电脑的优缺点,包括电池和屏幕。
"""

# ============================================================
# 4. 使用 .partial() 方法(部分变量)
# ============================================================
prompt_template = PromptTemplate(
    template = "请评价{product}的优缺点,包括{aspect1}和{aspect2}。",
    input_variables=["product"]
)
prompt_template = prompt_template.partial(aspect1='屏幕',aspect2='电池')
print('构造的模板:')
print(prompt_template)

prompt= prompt_template.format(product="apple笔记本电脑")
print('填充后的模板(即提示词):')
print(prompt)
print('提示词的类型:',type(prompt))

"""
输出:
构造的模板:
input_variables=['product'] input_types={} partial_variables={'aspect1': '屏幕', 'aspect2': '电池'} template='请评价{product}的优缺点,包括{aspect1}和{aspect2}。'
填充后的模板(即提示词):
请评价apple笔记本电脑的优缺点,包括屏幕和电池。
提示词的类型: <class 'str'>
"""


# ============================================================
# 5. 调用千问模型作答
# ============================================================
from dotenv import load_dotenv

# 加载 .env 文件里的变量到进程环境
load_dotenv()

from langchain_qwq import ChatQwen

llm = ChatQwen(
    model="qwen3.7-flash",
    max_tokens=3_000,
    timeout=None,
    max_retries=2,
    # other params...
)

# 使用模型
ai_msg = llm.invoke(prompt)
print(ai_msg)
# 模型返回的评价部分
ai_msg.content

三.ChatPromptTemplate

ChatPromptTemplate 是用于构建聊天消息序列的提示模板,特别适用于包含多角色(如系统、用户、AI)和多轮交互的对话场景。相比普通的 PromptTemplate,它能更自然地模拟真实对话结构。

核心特点

  • 支持多种角色的消息定义,包括 system(系统指令)、human(用户输入)、ai(模型回复)等;
  • 可有效组织和维护对话上下文与历史。

参数格式

模板通过一个消息列表进行定义,列表中的每一项通常是一个二元组(tuple),格式如下: (role: str, content: str)

  • role :指定消息发送者的角色,常用值为 system、human 或 ai;
  • content:消息内容,可以是字符串,也可以是结构化数据(如工具调用、多模态输入等,具体取决于底层模型支持)。

示例

python 复制代码
messages = [
    ("system", "你是一位专业的翻译助手。"),
    ("human", "翻译成中文:Hello, how are you?"),
    ("ai", "你好,你怎么样?")
]

通过这种方式,ChatPromptTemplate 能够灵活构建符合对话逻辑的输入,为大模型提供更清晰的上下文指引。

python 复制代码
# ============================================================
# 对话提示词模版 (ChatPromptTemplate)
# ============================================================
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_core.prompts import ChatPromptTemplate

# 定义模板
sys_template = "你是数学老师,请以{style}的风格回答问题"
user_template = "请用简单易懂的方式解释:{question}"

# 创建对话模板-构造方法
prompt_template1 = ChatPromptTemplate([
    ('system',sys_template),
    ('human',user_template)
])

# 创建对话模板-from_messages
prompt_template2 = ChatPromptTemplate.from_messages([
    ('system',sys_template),
    ('human',user_template)
])

# 创建对话模板
prompt_template3 = ChatPromptTemplate.from_messages([
    SystemMessage(sys_template),
    HumanMessage(user_template)
])

print(prompt_template1)
print(prompt_template2)
print(prompt_template3)

"""
输出:
input_variables=['question', 'style'] input_types={} partial_variables={} messages=[SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=['style'], input_types={}, partial_variables={}, template='你是数学老师,请以{style}的风格回答问题'), additional_kwargs={}), HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['question'], input_types={}, partial_variables={}, template='请用简单易懂的方式解释:{question}'), additional_kwargs={})]
input_variables=['question', 'style'] input_types={} partial_variables={} messages=[SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=['style'], input_types={}, partial_variables={}, template='你是数学老师,请以{style}的风格回答问题'), additional_kwargs={}), HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['question'], input_types={}, partial_variables={}, template='请用简单易懂的方式解释:{question}'), additional_kwargs={})]
input_variables=[] input_types={} partial_variables={} messages=[SystemMessage(content='你是数学老师,请以{style}的风格回答问题', additional_kwargs={}, response_metadata={}), HumanMessage(content='请用简单易懂的方式解释:{question}', additional_kwargs={}, response_metadata={})]
"""

# ============================================================
# 填充变量
# ============================================================
prompt1 = prompt_template1.invoke({'style':'通俗易懂','question':'勾股定理是什么?'})
prompt2 = prompt_template1.format(style='通俗易懂',question='勾股定理是什么?')
prompt3 = prompt_template1.format_messages(style='通俗易懂',question='勾股定理是什么?')
prompt4 = prompt_template1.format_prompt(style='通俗易懂',question='勾股定理是什么?')

print(prompt1)
print('-'*50)
print(prompt2)
print('-'*50)
print(prompt3)
print('-'*50)
print(prompt4)

"""
输出:
messages=[SystemMessage(content='你是数学老师,请以通俗易懂的风格回答问题', additional_kwargs={}, response_metadata={}), HumanMessage(content='请用简单易懂的方式解释:勾股定理是什么?', additional_kwargs={}, response_metadata={})]
--------------------------------------------------
System: 你是数学老师,请以通俗易懂的风格回答问题
Human: 请用简单易懂的方式解释:勾股定理是什么?
--------------------------------------------------
[SystemMessage(content='你是数学老师,请以通俗易懂的风格回答问题', additional_kwargs={}, response_metadata={}), HumanMessage(content='请用简单易懂的方式解释:勾股定理是什么?', additional_kwargs={}, response_metadata={})]
--------------------------------------------------
messages=[SystemMessage(content='你是数学老师,请以通俗易懂的风格回答问题', additional_kwargs={}, response_metadata={}), HumanMessage(content='请用简单易懂的方式解释:勾股定理是什么?', additional_kwargs={}, response_metadata={})]
"""

# ============================================================
# 调用模型
# ============================================================
from dotenv import load_dotenv

# 加载 .env 文件里的变量到进程环境
load_dotenv()

from langchain_qwq import ChatQwen

llm = ChatQwen(
    model="qwen3.7-flash",
    max_tokens=3_000,
    timeout=None,
    max_retries=2,
    # other params...
)

# 使用模型
info = llm.invoke(prompt1)
info

info2 = llm.invoke(prompt2)
info2

info3 = llm.invoke(prompt3)
info3

info4 = llm.invoke(prompt4)
info4

info输出是一个AIMessage类型的对象

四.FewShotPromptTemplate

为什么要使用 FewShot Prompting
Zero-shot (零样本学习) 是指模型 在没有任何示例 的情况下,仅凭任务描述或提示词就直接完成任务的能力

python 复制代码
# Zero-shot 示例1:常见任务
res1 = chat_model.invoke("法国的首都是什么?")
print(res1.content)  # 巴黎

# Zero-shot 示例2:简单推理
res2 = chat_model.invoke("如果今天是周一,三天后是周几?")
print(res2.content)  # 周四


# 案例1:特殊格式要求
res = chat_model.invoke("请用以下格式输出答案:答案:{数字}。解释:{理由}")
print(res.content)
# 输出可能不符合要求的格式

# 案例2:特定处理规则
res = chat_model.invoke("提取城市名,只输出城市名本身")
print(res.content)
# 输出可能包含额外信息

Zero-shot 的主要问题
1

  • 符号理解困难:对新符号、自定义符号无法理解
  • 格式控制不精确:难以精确控制输出格式
  • 任务理解偏差:对复杂任务可能出现理解偏差
  • 一致性差:多次运行结果可能不一致

代码示例:

python 复制代码
from dotenv import load_dotenv

# 加载 .env 文件里的变量到进程环境
load_dotenv()

from langchain_qwq import ChatQwen

llm = ChatQwen(
    model="qwen3.7-flash",
    max_tokens=3_000,
    timeout=None,
    max_retries=2,
    # other params...
)

# Zero-shot 失败的情况
print("=== Zero-shot 失败 ===")
question = "2 ✿ 3 是多少?"
res_zero = llm.invoke(question)
print(f"问题:{question}")
print(f"回答:{res_zero}")  # 无法理解 ✿ 的含义
'''
=== Zero-shot 失败 ===
问题:2 ✿ 3 是多少?
回答:content='"✿" 并不是一个标准的数学运算符号。不过,根据常见的输入错误或语境,你可能是在问以下几种情况之一:\n\n1.  **如果是除法 (2 ÷ 3)**:\n    *   分数形式:**$\\frac{2}{3}$** (三分之二)\n    *   小数形式:**$0.666\\dots$** (6 无限循环,约等于 0.67)\n\n2.  **如果是乘法 (2 × 3)**:\n    *   结果:**6**\n\n3.  **如果是加法 (2 + 3)**:\n    *   结果:**5**\n\n如果这不是普通的算术题,而是一个特定游戏、谜题或代码中的符号,请提供更多背景信息,以便我给出更准确的答案。' additional_kwargs={'refusal': None, 'reasoning_content': 'Here\'s a thinking process that leads to the suggested answer:\n\n1.  **Analyze the Input:**\n    *   Expression: $2 \\div 3$ (Wait, looking at the symbol "✿". It looks like a flower or a snowflake, but in mathematical contexts, it might be a typo for a division sign $\\div$ or just a separator).\n    *   Context: "2 ✿ 3 是多少?" (What is 2 [s ......
'''


# Few-shot 解决方案
# print("\n=== Few-shot 解决 ===")

# 定义示例
examples = [
    {"input": "2 ✿ 3", "output": "6 (因为 ✿表示乘法)"},
    {"input": "3 ✿ 7", "output": "21 (因为 ✿ 表示乘法)"},
]

# 构建 Few-shot 提示
from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate

# 普通提示词模版
example_prompt = PromptTemplate.from_template("输入:{input}\n输出:{output}")
# 少量样本提示词模版
prompt = FewShotPromptTemplate(
    # 样例
    examples=examples,
    # 样例提示词模版
    example_prompt=example_prompt,
    # 前缀
    suffix="输入:{input}\n输出:",
    input_variables=["input"]
)

# 构建提示词
few_shot_prompt = prompt.format(input="6 ✿ 6")

res_few = llm.invoke(few_shot_prompt)

print(f"Few-shot 提示:\n{few_shot_prompt}")
print(f"\nFew-shot 回答:{res_few.content}")  # 36 (因为 ✿ 表示乘法)
'''
Few-shot 提示:
输入:2 ✿ 3
输出:6 (因为 ✿表示乘法)

输入:3 ✿ 7
输出:21 (因为 ✿ 表示乘法)

输入:6 ✿ 6
输出:

Few-shot 回答:36
'''

# 1. 准备示例(城市提取场景)
examples = [
    {"input": "北京天气怎么样", "output": "北京市"},
    {"input": "南京下雨吗", "output": "南京市"},
    {"input": "武汉热吗", "output": "武汉市"}
]

# 2. 创建示例模板
example_prompt = PromptTemplate.from_template(
    "Input: {input}\nOutput: {output}"
)

# 3. 构建 FewShot 提示
few_shot_prompt = FewShotPromptTemplate(
    examples=examples,
    example_prompt=example_prompt,
    suffix="Input: {city_input}\nOutput:",
    input_variables=["city_input"]
)

# 4. 格式化和调用
prompt_text = few_shot_prompt.format(city_input="长沙多少度")

print("=== 生成的 Prompt ===")
print(prompt_text,end="\n")

print("=== 调用模型作答 ===")
# 5. 调用模型
info = llm.invoke(prompt_text)
print(info.content)

'''
=== 生成的 Prompt ===
Input: 北京天气怎么样
Output: 北京市

Input: 南京下雨吗
Output: 南京市

Input: 武汉热吗
Output: 武汉市

Input: 长沙多少度
Output:
=== 调用模型作答 ===
长沙市
'''

五.企业智能体-提示词管理策略

了解提示词管理的不同方案及其优缺点 ,掌握不同场景下的提示词管理策略选择


常见管理方案对比

1.硬编码方案

python 复制代码
# 示例:提示词直接写在代码中
class ChatAgent:
   def get_welcome_prompt(self):
       return """你是一个客户服务助手,请友好地回
答用户问题。
要求:
1. 使用中文回复
2. 保持专业但亲切的语气
3. 如果不知道答案,诚实地告知
4. 不要编造信息"""

问题
当需要修改提⽰词时,必须修改代码并重新部署
2.JSON 文件管理方案
prompts.json

bash 复制代码
{
  "customer_service": {
    "welcome": {
      "system": "你是一个{{company_name}}的客户服务助手,请友好地回答用户问题。",
      "requirements": [
        "使用中文回复",
        "保持专业但亲切的语气",
        "如果不知道答案,诚实地告知",
        "不要编造信息"
      ],
      "version": "1.0",
      "last_updated": "2050-01-15"
    },
    "complaint_handling": {
      "system": "处理客户投诉时,首先要表达理解和歉意。",
      "steps": [
        "倾听并确认问题",
        "表达理解和歉意",
        "提供解决方案",
        "确认客户满意度"
      ]
    }
  }
}

(1)普通字符串和f-string字符串的区别:

普通字符串 s = "abc"

复制代码
s1 = "你好,name"
s2 = '你好,name'
s3 = """多行
文本"""
  • 内容固定,写死是什么就是什么;

  • {、} 没有特殊含义,就是普通字符;

  • 转义只认 \ 开头:\n、\t 等;

  • 不能直接嵌入变量运算。

拼接变量要靠 + 或者 % / .format():

复制代码
name = "张三"
s = "你好," + name

f-string f"abc {expr}"

复制代码
name = "张三"
s = f"你好,{name}"
  • 以 f / F 前缀开头;

  • { 里面可以放任意 Python 表达式:变量、计算、函数调用 },运行时求值转成字符串;

  • 若想输出字面的 { / },必须双写 {``{、}};

  • 支持格式控制:f"{price:.2f}";

  • 仍然支持 \ 转义(换行、制表符等)。

(2)Python****加载代码:

python 复制代码
import json


class PromptManager:
    def __init__(self,config_path:str='prompts.json'):
        with open(config_path,'r',encoding='utf-8') as f:
            # json对象
            self.prompts = json.load(f)

    def get_prompt(self,category:str,key:str,**kwargs) -> str:
        prompt_data =  self.prompts.get(category).get(key)
        prompt = prompt_data.get('system')   # 获取提示词
        print(prompt,end='\n\n')

        if "requirements" in prompt_data:
            prompt += '\n要求:'
            # 遍历要求列表,添加到提示词中,1代表从1开始编号,0代表从0开始编号
            for i,req in enumerate(prompt_data.get('requirements'),1):
                prompt += f'\n{i}. {req}'
            print(type(prompt))
            print(prompt,end='\n\n')

        # 变量的赋值
        if kwargs:
            for key,value in kwargs.items():
                # 在f-string中,两侧最外面的四层花括号转义为{{}},对应着json中的{{}}
                # 最里面一层的{}则为f-string中传入变量的格式,代表着key是一个变量
                prompt = prompt.replace(f'{{{{{key}}}}}',str(value))
                
        return prompt


manager = PromptManager()
prompt = manager.get_prompt(
    category='customer_service',
    key='welcome',
    company_name='ABC公司'
)
print(prompt)

输出:

bash 复制代码
你是一个{{company_name}}的客户服务助手,请友好地回答用户问题。

<class 'str'>
你是一个{{company_name}}的客户服务助手,请友好地回答用户问题。
要求:
1. 使用中文回复
2. 保持专业但亲切的语气
3. 如果不知道答案,诚实地告知
4. 不要编造信息

你是一个ABC公司的客户服务助手,请友好地回答用户问题。
要求:
1. 使用中文回复
2. 保持专业但亲切的语气
3. 如果不知道答案,诚实地告知
4. 不要编造信息

那为什么json中不写成{company_name},get_prompt中不写成f'{{{key}}}',这样不是更省事吗?

答:行业标准,

模板惯例:{``{ }} 是主流模板引擎的"官方定界符"

Jinja2、Go Template、Django 这些模板引擎里,占位符一律是 {``{ variable }}。提示词模板选用双括号,等于从一开始就采用了行业标准写法,占位符在正文中"一眼可辨",不会和内容混在一起。
迁移性:未来可以零成本升级到 Jinja2。

3.YAML****文件管理方案
prompts.yaml

bash 复制代码
customer_service:
  welcome:
    system: "欢迎使用{{company_name}}的客户服务!很高兴为您服务。"
    requirements:
      - 使用友好、专业的语气
      - 主动了解客户需求
      - 及时响应客户问题
  complaint:
    system: "抱歉给您带来不便,{{company_name}}非常重视您的反馈。"
    requirements:
      - 表达歉意
      - 认真记录问题
      - 承诺处理时效

代码:

python 复制代码
import yaml  # pip install pyyaml


class YamlPromptManager:
    def __init__(self,config_path:str='prompts.yaml'):
        with open(config_path,'r',encoding='utf-8') as f:
            # dict类型
            self.prompts = yaml.safe_load(f)
            print(type(self.prompts),end='\n\n')

    def get_prompt(self,category:str,key:str, **kwargs) ->str:
        # {}是默认值
        prompt_data = self.prompts.get(category,{}).get(key,{})

        if not prompt_data:
            raise ValueError(f'找不到提示词:{category}.{key}')
        
        prompt = prompt_data.get('system','')  # 获取提示词

        # 添加要求列表
        if 'requirements' in prompt_data:
            prompt += '\n要求:'
            for i ,req in enumerate(prompt_data.get('requirements',[]),1):
                prompt += f'\n{i}. {req}'

        # 变量替换
        if kwargs:
            for var_key,var_value in kwargs.items():
                prompt = prompt.replace(f'{{{{{var_key}}}}}',str(var_value))

        return prompt
yaml_prompt = YamlPromptManager()
prompt = yaml_prompt.get_prompt(
    'customer_service',
    'welcome',
    company_name='ABC公司'
    )
print(prompt)

六.格式化输出

介绍

在 LangChain 中,输出格式化(Output Parsing)是关键功能之一,用于将大语言模型(LLM)的原始输出(通常是自由格式的文本)解析为结构化的数据格式,如 JSON、字典或自定义对象。这不仅便于后续处理,还能提高输出的可读性和一致性。

核心价值

  • 确保格式一致性:强制 LLM 按照预定格式输出

  • 提升数据可用性:将文本转换为程序可操作的对象

  • 降低错误率:通过验证机制减少格式错误

  • 简化下游处理:为后续流程提供标准化的数据结构

举例

假设你让 LLM 回答:"请提取用户姓名、年龄和兴趣爱好。" 模型可能返回: "我叫李明,今年28岁,喜欢爬山和摄影。" 这种自由文本难以直接用于程序逻辑。

而通过 PydanticOutputParser,我们可以强制模型输出: {"name": "李明", "age": 28, "hobbies": ["爬山", "摄影"]}

调用流程


输出解析器的分类

解析器类型 主要优势 适用场景 性能考虑 学习曲线
PydanticOutputParser 类型安全,验证严格,IDE支持好 生产环境,复杂数据结构,需要验证 中等,验证开销 中等
JsonOutputParser 灵活,兼容性好,流式支持 Web API,前后端交互,动态结构 较高,解析快 简单
XMLOutputParser 层级结构清晰,兼容旧系统 企业集成,文档处理,配置管理 中等,标签解析 中等
CommaSeparatedListOutputParser 简单高效,内存占用小 标签提取,简单列表,关键词 很高 简单
StructuredOutputParser 完全自定义,灵活性最高 特殊格式需求,原型开发 取决于复杂度 较高

json:

python 复制代码
from langchain_core.output_parsers import JsonOutputParser

parser = JsonOutputParser()
# 获取格式的提示词
format_inst = parser.get_format_instructions()
# 提示词,f-string类型的字符串
prompt_text = f"""
请分析以下产品评价,并返回一个JSON对象。
要求:包含product_name(产品名)、rating(评分1-5)、pros(优点列表)、cons(缺点列表)

格式要求:
{format_inst}

评价内容:这款手机电池续航很好,能使用一整天,但摄像头效果一般,价格偏高。
"""

# 获取模型输出并解析
raw_output = llm.invoke(prompt_text)
print(raw_output)
print(raw_output.content)
print(type(raw_output),end='\n\n')

#parse函数接收
rs = parser.parse(raw_output.content)

print('解析后的JSON数据:')
print(rs)
print(f'产品名: {rs.get("product_name")}')

输出:

pydantic:

python 复制代码
from typing import List  # noqa: UP035

from langchain_core.output_parsers import PydanticOutputParser
from pydantic import BaseModel, Field


# 定义结构
class ArticleSummary(BaseModel):
    title: str = Field(description="文章标题")
    author: str = Field(description="作者")
    key_points: List[str] = Field(description="关键点列表", min_length=3)
    summary: str = Field(description="文章摘要", min_length=50)

# 初始化
parser = PydanticOutputParser(pydantic_object=ArticleSummary)

# 获取类型提示词
instructions = parser.get_format_instructions()

user_query = "请总结《红楼梦》前五回的主要内容"

prompt = f"""
你是一个文学分析助手。
请根据用户请求分析文章内容。

输出格式必须严格遵守:
{instructions}

用户请求:{user_query}
"""

response = llm.invoke(prompt)
response

XML:

python 复制代码
from langchain_core.output_parsers import XMLOutputParser

parser = XMLOutputParser()
query = "请提供《三体》这本书的信息"
# 提供结构模板(不带具体值!)
xml_template = """
<book>
    <title>书名</title>
    <author>作者</author>
    <year>年份</year>
    <genre>类型</genre>
</book>
"""
prompt = f"""
你是一个图书数据库助手。请根据你的知识,以严格的XML格式回答以下请求。

要求:
- 只输出XML,不要任何其他文字、解释或Markdown。
- 使用以下结构(可重复<genre>标签表示多个类型):
{xml_template}

请求:{query}
"""
response = llm.invoke(prompt)
print(response,end='\n\n')
print(response.content,end='\n\n')
xml_result = parser.parse(response.content)
print("解析结果:", xml_result)

输出:

另一种写法:

python 复制代码
from langchain_core.output_parsers import XMLOutputParser
from langchain_core.prompts import PromptTemplate

query = "请提供《三体》这本书的信息"

parser = XMLOutputParser()

prompt = """
{format_str}

要求:
- 只输出XML,不要任何其他文字、解释或Markdown

请求:{query}
"""

template = PromptTemplate.from_template(prompt)
template = template.partial(format_str=parser.get_format_instructions())

response = llm.invoke(template.format(query=query))

print("解析结果:", response)

列表:

python 复制代码
from langchain_core.output_parsers import CommaSeparatedListOutputParser

parser = CommaSeparatedListOutputParser()

# 构建提示
format_str = parser.get_format_instructions()
text_to_analyze = "人工智能、机器学习、深度学习、神经网络、自然语言处理、计算机视觉"

prompt = f"""
请从以下文本中提取所有的技术术语:
{text_to_analyze}

要求:
{format_str}

注意:只提取技术术语,不要添加解释。
"""

# 调用并解析
response = llm.invoke(prompt)
result_list = parser.parse(response.content)

print(f"提取到 {len(result_list)} 个术语:")
for i, term in enumerate(result_list, 1):
    print(f"{i}. {term}")

输出:

提取到 6 个术语: 1. 人工智能 2. 机器学习 3. 深度学习 4. 神经网络 5. 自然语言处理 6. 计算机视觉

python 复制代码
# 直接处理已知的逗号分隔字符串
csv_string = "Python,JavaScript,Java,C++,Go"
parsed_from_string = parser.parse(csv_string)
print(f"\n直接解析CSV字符串:{parsed_from_string}")
csv_string.split(',')

输出:

自定义结构化

python 复制代码
from langchain_core.output_parsers import BaseOutputParser


class KeyValueParser(BaseOutputParser):
    def parse(self,text:str) -> dict:
        result = {}    # 存放结果字典
        lines = text.strip().split('\n')   # 数据预处理

        for line in lines:
            if ':' in line:
                # 1代表只分割一次,后面再有冒号就不管了
                key,value = line.split(':',1)
                # 存入字典
                result[key.strip()] = value.strip()
        return result

    def get_format_instructions(self):
        return '请使用键值对格式输出,每行一个,格式为:key:value'
    
# 创建对象
parser = KeyValueParser()

format_str = parser.get_format_instructions()

prompt = f"""
请提取以下文本中的关键信息:
"姓名:张三,年龄:30,职业:软件工程师,城市:北京"

输出格式:
{format_str}
"""

response = llm.invoke(prompt)

data = parser.parse(response.content)
print(data,end='\n\n')
print('自定义解析器结果:')
for key,value in data.items():
    print(f'{key}:{value}')

输出:


选择建议:
1

  • 新项目开发:优先考虑 PydanticOutputParser 或 JsonOutputParser
  • 企业集成:考虑 XMLOutputParser 或 StructuredOutputParser
  • 简单任务:使用CommaSeparatedListOutputParser
  • 流式需求:选择 JsonOutputParser或支持流式的解析器
  • 验证需求强:首选PydanticOutputParser

常⻅问题
模型仍可能不遵守格式 → 可结合 retry 机制或使⽤StructuredTool + OpenAIFunctionCalling
中⽂模型对英⽂字段名可能混淆 → 建议字段描述⽤中⽂流式输出时需注意解析器是否⽀持(如 JsonOutputParser ⽀持,但 Pydantic 在流式中需额外处理)

工程上的重要区别:

  • 解析器本质是:让模型按提示写出文本,再在代码里解析校验,存在模型输出格式翻车风险;
  • 声明式结构化输出with_structured_output/ 原生工具调用:是模型协议层面约束,稳定度更高,是现在生产首选。声明式结构化输出是 LangChain 在 2025‒2026 年推动的核⼼范
    式转变

声明式结构化输出

python 复制代码
from pydantic import BaseModel, Field


class UserProfile(BaseModel):
    name:str =Field(description='用户名')
    age:int = Field(description='年龄')
    is_student:bool = Field(description='是否为在校学生')
    tags:list[str] = Field(description='兴趣标签',default_factory=list)

# 声明式模型
# 注意:不是所有模型⽀持这个⽅法,需要测试
structured_llm = llm.with_structured_output(UserProfile)

# 调用模型
rs = structured_llm.invoke("用户叫李四,25岁,在读研究生,喜欢AI和编程。")
print(rs)
print(type(rs))
rs.model_dump() #转为json

输出:


但是现在新版的langchain已经更改了,上面介绍的几种解析器已经不推荐了(声明式结构化输出现在推荐**),具体的新方式可以参考官网的结构化输出页面进行学习,点这里**

但是官网的示例的输出都是json或字典的,那么想输出XML或者列表的话,该如何设置呢?

create_agent 结构化输出:列表 / XML 输出方案

关键点:**create_agent 的 response_format(ProviderStrategy / ToolStrategy)底层完全依赖【模型原生 JSON Schema / Function‑call 工具调用】,只能输出 JSON 兼容的数据结构(对象、数组),**不能直接输出原始 XML 字符串文本 **。

  • ✅ Python list(数组)可以直接通过 JSON‑Schema/Pydantic 数组类型实现,存入structured_response

  • ❌ 原始 XML 文本不能交给response_format做 schema 校验;response_format 不会生成 XML 标签文本,只能输出 JSON 可解析数据

例如:

输出 Python List(列表)

列表本质就是 JSON 的array类型,可以直接写 Pydantic 模型(字段用list[T]),直接传给response_format即可,agent 返回structured_response就是 python list 对象。

Pydantic 模型(推荐,自动选 ProviderStrategy/ToolStrategy)

python 复制代码
from pydantic import BaseModel, Field
from langchain.agents import create_agent

# 外层包一个对象,内部字段为list;不可以直接把list类型裸传给response_format
class ItemList(BaseModel):
    items: list[str] = Field(description="结果条目列表")

agent = create_agent(
    model="gpt-6.1-sol",
    tools=[],
    response_format=ItemList
)

res = agent.invoke({
    "messages": [{"role":"user","content":"提取下面句子的关键词:苹果、香蕉、橘子"}]
})
print(res["structured_response"].items)
# >>> ['苹果','香蕉','橘子'] 原生python list

输出 XML(原始 XML 标签文本)

使用上面的XML解析器;或者直接加入系统提示词,强制模型输出XML;或者先用 response_format 拿结构化数据,再代码层序列化为 XML(最稳定)

相关推荐
香吧香21 分钟前
BM25 是什么 详解
大模型
云上工程笔记21 分钟前
优刻得UCloud技术实践:中立云定位、自建智算中心与AI工厂方案怎么落地
人工智能
Java与AI落地1 小时前
AI 接口日志脱敏:log-prompt 关掉之后,prompt 里的内网地址怎么删
人工智能
逆光重构1 小时前
Amazon 类目属性填充实践:为什么 AI 只该填那些真正空着的必填项
人工智能
Sevennn1 小时前
Tiny Context:轻量读写、带大小约束的 Coding Agent 项目记忆方案
人工智能
Thomas.Sir1 小时前
第026讲:AI模型开发|脏数据 taxonomy:五类噪声的形态与影响:把脏数据分门别类,才谈得上治理
人工智能·ai
武子康1 小时前
GameEval第一轮先测什么:正常对照、已知故障与未知探索
大数据·数据库·人工智能
天空属于哈夫克32 小时前
企业微信API赋能智能办公与流程自动化
人工智能·自动化·企业微信
微三云云仔2 小时前
2026东莞品牌营销排名观察:从传统咨询到GEO,企业如何选对增长伙伴
大数据·人工智能·geo·ai搜索优化·微三云