You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LangChain 0.1.12中ChatPromptTemplate结合PyDantic结构化输出报错

LangChain 0.1.12 结构化输出兼容问题解决

问题描述

之前在LangChain 0.2.8环境下正常运行的代码,迁移到0.1.12后调用self.llm.with_structured_output(Sentences)时触发两类错误:

  • 初始报错:__init__ takes 1 positional argument but 2 were provided
  • 调整OPEN_API_VERSION后触发:NotImplementedError(对应LLM类未实现该方法)

原因

LangChain 0.1.x版本的with_structured_output API与0.2.x差异极大,且多数LLM类在0.1.12中尚未实现该方法,直接沿用0.2.x的写法会出现兼容性问题。

解决方案

改用0.1.x版本中稳定支持的结构化输出解析器实现需求,具体代码修改如下:

from langchain.output_parsers import PydanticOutputParser
from pydantic import BaseModel

system_string = """
    [THIS CONTAINS INSTRUCTIONS ABOUT WHAT THE SYSTEM IS SUPPOSED TO DO]
    {format_instructions}
"""

class Sentences(BaseModel):
    sentences: list[str]

# 基于Pydantic模型生成解析器
output_parser = PydanticOutputParser(pydantic_object=Sentences)
# 获取格式说明,用于告知模型输出结构
format_instructions = output_parser.get_format_instructions()

propositioning_prompt = ChatPromptTemplate([
    ("system", system_string),
    ("human", "Decompose the following: {input}"),
])

# 构建链:prompt -> LLM -> 解析器
propositioning_chain = propositioning_prompt | self.llm | output_parser

returned_list = []
if len(paragraph.lstrip()) > 5:
    sentences = propositioning_chain.invoke({
        "input": paragraph,
        "format_instructions": format_instructions
    })
    returned_list = sentences.sentences

return returned_list

补充说明

  • 若无需Pydantic实例,仅需字典结果,可改用StructuredOutputParser配合ResponseSchema定义结构
  • 必须在system prompt中加入{format_instructions}占位符,确保模型输出符合指定结构

内容的提问来源于stack exchange,提问作者Rasputin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 22:33:17