提示文章写完后目录可以自动生成如何生成可参考右边的帮助文档文章目录问题背景一、问题复现使用gml4.5进行结构化输出失效使用stepfun/step-3.5-flash:free模型成功二、如何解决结构化输出的问题示例代码总结问题背景让大模型输出结构化的数据是常见的需求比如让大模型输出成一个json或者一个python的对象。我们可以在prompt中要求它输出是一种方式但langchain中使用了更优雅的方式使用Structured output 的方式进行输出。但这种能力是要基于模型的能力的不是所有的大模型都会支持这种方式。一、问题复现使用gml4.5进行结构化输出失效frompydanticimportBaseModel,Field#fromapp.langchain_llm_utilsimportget_zp_llm,get_langchain_llmclassMovie(BaseModel):A movie with details.title:strField(descriptionThe title of the movie)year:intField(descriptionThe year the movie was released)director:strField(descriptionThe director of the movie)rating:floatField(descriptionThe movies rating out of 10)##llmget_zp_llm()# llm get_langchain_llm(stepfun/step-3.5-flash:free)#model_with_structurellm.with_structured_output(Movie,strictTrue)responsemodel_with_structure.invoke(Provide details about the movie Inception limit 200 words)print(response)# Movie(titleInception, year2010, directorChristopher Nolan, rating8.8)print(response.model_dump_json())上述代码十分简单定义了一个pydantic的对象期待使用大模型进行结构化输出类似于Movie(title“Inception”, year2010, director“Christopher Nolan”, rating8.8)。但是在langsmith中看到大模型的回复是它直接输出了prompt的要求的内容并未按要求进行结构化输出。我们来看看大模型的输入包含一个Movie的tool和一个input使用stepfun/step-3.5-flash:free模型成功同样的输入使用stepfun/step-3.5-flash:free模型成功可以看到使用stepfun/step-3.5-flash 成功可见不同模型对于结构化输出的能力支持是不同的。在我尝试的国产模型中GML4.5和qwen3.6-plus都是不支持的。二、如何解决结构化输出的问题在langchain的官网中写的还是比较明确了大部分的大模型都是原生支持结构化输出了但是如果有大模型不支持可以使用output_parsers进行解决。下面我来举个例子看看是如何解决这个问题的。如果结构化输出的问题不能妥善解决后面的流程更无从谈起了。示例代码fromlangchain_core.output_parsersimportPydanticOutputParserfromlangchain_core.promptsimportPromptTemplate#fromlangchain_core.promptsimportPromptTemplate parserPydanticOutputParser(pydantic_objectMovie)promptPromptTemplate(templateAnswer the user query.\n{format_instructions}\n{query}\n,input_variables[query],partial_variables{format_instructions:parser.get_format_instructions()},)chainprompt|llm|parser responsechain.invoke({query:Provide details about the movie Inception limit 200 words})print(response.title)print(response)上述代码还是相对很简单的但是很能说明问题核心思想是要在提示词中说明要转换对象的结构然后使用parser进行转换。可以看到在PromptTemplate的输出中既提出了问题又提出了输出的schema。可以看到解析器成果输出了对象。总结并不是所有大模型都是支持with_structured_output要进行测试。如果模型不支持with_structured_output要自己手动去编写一条简单的从prompt到parser的chain观察langsmith的输入输出可以知道使用parser的它的本质是在prompt中增加输出的schema的说明。with_structured_output支持的模型它能正确的识别tool,它会把要结构化输出的对象识别为是一个tool