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

将带with_structured_output的ChatOpenAI封装进LLMChain触发验证错误

LLMChain结合with_structured_output报错的原因与解决方案

这不属于正常行为,问题出在LLMChain的设计逻辑和with_structured_output的返回类型不兼容:

报错原因

LLMChain作为LangChain的旧版链实现,默认会将LLM的输出包装成包含text键的字典返回。但ChatOpenAI.with_structured_output(Card)返回的是Pydantic模型实例(Card对象),而非字符串。当LLMChain尝试把这个对象塞进字典的text字段时,由于无法直接序列化非字符串类型,就会触发错误。

而PydanticOutputParser是先让LLM输出符合格式的字符串,再解析成Pydantic对象,完全适配LLMChain的字符串输出预期,因此能正常运行。

解决方案(使用OpenAI原生结构化输出)

方法1:改用新版Runnable链结构(推荐)

LangChain的新版Runnable体系(通过|运算符组合组件)对结构化输出支持更友好,直接替代LLMChain即可:

from pydantic import BaseModel, Field
from typing import Optional
from langchain_core.prompts import PromptTemplate
from langchain_openai import ChatOpenAI

class Card(BaseModel):
    """Card data."""
    name: Optional[str] = Field(..., description="Character name")
    description: Optional[str] = Field(..., description="Character description")
    
structured_llm = ChatOpenAI().with_structured_output(Card)
prompt = PromptTemplate.from_template("""
    Extract card information from a given page:
    
    ### Page
    {page}
""")

# 用Runnable组合替代LLMChain
chain = prompt | structured_llm
result = chain.invoke({"page": "Card name: Alice and Bob, Description: An example card"})
print(result)
# 输出:Card(name='Alice and Bob', description='An example card')

方法2:适配LLMChain(不推荐,仅作兼容)

如果必须使用LLMChain,可以指定output_key并手动处理输出:

from langchain.chains import LLMChain

chain = LLMChain(
    llm=structured_llm,
    prompt=prompt,
    verbose=True,
    output_key="card"  # 替换默认的text键,避免序列化冲突
)
result = chain.invoke({"page": "Card name: Alice and Bob, Description: An example card"})
print(result["card"])
# 输出:Card(name='Alice and Bob', description='An example card')

总结

LLMChain是针对字符串输出设计的旧组件,对OpenAI原生结构化输出(返回Pydantic实例)的支持不完善。优先使用新版Runnable链结构,既能保留OpenAI原生结构化输出的优势,又能避免兼容问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 21:57:18