news 2026/6/15 10:07:49

[对比学习LangChain和MAF-09]利用结构化输出生成指定结构的内容

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
[对比学习LangChain和MAF-09]利用结构化输出生成指定结构的内容

AI Agent的结构化输出是指Agent在执行任务时,不再返回自然语言文本,而是严格按照预定义的格式(如JSON、XML、YAML 或特定数据对象)输出数据。这是将AI从能聊天的Agent演变为能精确执行工业级业务流的系统的核心技术。下来我们来看看LangChain和MAF是如何支持Agent的结构化输出的。

1. LangChain

LangChain针对结构化输出提供了两种编程模式,一种是采用采用promp | llm | output_parser这种基于基于LXEL表达式构建的处理管道,另一种就是在调用create_agent函数创建Agent的时候,利用response_format参数指定输出的格式。

1.1 基于LCEL表达式构建处理管道

promp | llm | output_parser构成了经典的三段式处理管道,其中prompt用来定义输入LLM的提示词,llm用来指定采用哪个语言模型,output_parser用来定义如何解析LLM的输出。通过这种方式构建的处理管道可以很方便地实现结构化输出,因为我们可以在prompt中明确地告诉LLM按照什么样的格式来生成输出,然后在output_parser中编写相应的解析逻辑来将这个输出转换成我们需要的数据结构。

在如下的这段演示程序中,我们定义了一个UserInfo的数据模型来描述用户信息,然后利用JsonOutputParser这个预定义的输出解析器来将LLM的输出解析成UserInfo对象。在prompt中,我们通过{format_instructions}占位符来插入JsonOutputParser生成的格式化指令,告诉LLM按照UserInfo的格式来生成输出。最后我们将这个处理管道连接成一个chain,并调用它来处理一个包含用户信息的查询,最终得到一个UserInfo对象。

fromlangchain_core.output_parsersimportJsonOutputParserfromlangchain_core.promptsimportPromptTemplatefromlangchain_openaiimportChatOpenAIfrompydanticimportBaseModel,Fieldfromdotenvimportload_dotenv load_dotenv()classUserInfo(BaseModel):name:str=Field(description="user's name")age:int=Field(description="user's age")hobbies:list[str]=Field(description="user's hobbies")parser=JsonOutputParser(pydantic_object=UserInfo)template="""\ Extract information from the following text. {format_instructions} context: {query}"""prompt=(PromptTemplate.from_template(template).partial(format_instructions=parser.get_format_instructions()))llm=ChatOpenAI(model="gpt-5.2-chat")chain=prompt|llm|parser query="My name is Jayden, I am 18 years old and I like hiking and painting."use_info=chain.invoke({"query":query})assertisinstance(use_info,UserInfo)assertuse_info.name=="Jayden"assertuse_info.age==18assertuse_info.hobbies==["hiking","painting"]

LangChain提供了很多预定义的输出解析器,除了JsonOutputParser之外,还有XMLOutputParserPydanticOutputParserListOutputParser等,满足不同的结构化输出需求。针对它们的详细介绍可以参考我如下两篇文章:

  • 针对模型输出的解析(上篇)
  • 针对模型输出的解析(下篇)

1.2 设置Agent的response_format

数据只有具有希望的结构才可能被有效地处理,我们在调用create_agent函数创建Agent的时候,可以利用response_format控制输出的格式。我们可以定义一个Pydantic模型类表表示期望输出的结构,如果将此类型表示成ResponseT,我们可以直接将此类型作为response_format参数的值,也可以将此参数赋值为ResponseFormat[ResponseT]。除此之外,我们也可以创建一个表示JSON Schema的字典作为response_format参数的值。ResponseFormat实际上针对ToolStrategyProviderStrategyAutoStrategy三个类型的联合。ToolStrategyProviderStrategy代表了两种实现结构化输出的不同技术路径。

defcreate_agent(...response_format:ResponseFormat[ResponseT]|type[ResponseT]|dict[str,Any]|None=None,...)ResponseFormat=ToolStrategy[SchemaT]|ProviderStrategy[SchemaT]|AutoStrategy[SchemaT]

组成ResponseFormat的三个类型代表了结构化输出的三种策略:

  • ToolStrategy:利用工具调用来实现结构化输出,Agent在调用LLM的时候会将工具的定义(包括输入输出的格式)作为提示词的一部分传入LLM,LLM在生成输出的时候按照工具的定义来生成工具调用的意图,Agent在解析到这个工具调用意图之后就会调用对应的工具来获取结构化的数据结果;
  • ProviderStrategy:利用Provider来实现结构化输出,Agent在调用LLM的时候会将Provider的定义(包括输入输出的格式)作为提示词的一部分传入LLM,LLM在生成输出的时候按照Provider的定义来生成调用Provider的意图,Agent在解析到这个调用Provider的意图之后就会调用对应的Provider来获取结构化的数据结果;
  • AutoStrategy:Agent会自动地在ToolStrategyProviderStrategy之间进行选择,如果LLM支持则采用ProviderStrategy,否则采用ToolStrategy

在如下的演示程序中,我们在调用create_agent函数创建Agent的时候,将response_format参数设置为AutoStrategy[UserInfo],告诉Agent我们希望它能够按照UserInfo的格式来生成输出。Agent会自动地选择合适的策略来实现这个结构化输出的需求。由于指定的模型自身对结构化输出提供支持,所以Agent会优先选择ProviderStrategy来实现结构化输出。

fromlangchain.agentsimportcreate_agentfromlangchain.agents.structured_outputimportAutoStrategyfromlangchain_openaiimportChatOpenAIfrompydanticimportBaseModel,Fieldfromdotenvimportload_dotenv load_dotenv()classUserInfo(BaseModel):name:str=Field(description="user's name")age:int=Field(description="user's age")hobbies:list[str]=Field(description="user's hobbies")agent=create_agent(model=ChatOpenAI(model="gpt-5.2-chat"),response_format=AutoStrategy(schema=UserInfo),)query="My name is Jayden, I am 18 years old and I like hiking and painting."query=f"""\ Extract information from the following text. context:{query}"""result=agent.invoke(input={"messages":[{"role":"user","content":query}]})use_info=result["structured_response"]assertisinstance(use_info,UserInfo)assertuse_info.name=="Jayden"assertuse_info.age==18assertuse_info.hobbies==["hiking","painting"]

关于三种策略的实现原理,可以参考我之前写的这篇文章:结构化输出的两种实现方式。

2. MAF

在MAF中,AIAgent定义了如下四个重载的RunAsync<T>方法,它们的返回值都是AgentResponse<T>类型,其中泛型参数T表示结构化输出的类型。在得到作为返回值的AgentResponse<T>对象之后,我们可以通过它的Result属性来获取结构化输出的结果。AgentResponse<T>类型继承自AgentResponse,并新增了一个IsWrappedInObject属性用来指示结构化输出的结果是否被包装在一个对象中。

publicabstractclassAIAgent{publicTask<AgentResponse<T>>RunAsync<T>(AgentSession?session=null,JsonSerializerOptions?serializerOptions=null,AgentRunOptions?options=null,CancellationTokencancellationToken=default);publicTask<AgentResponse<T>>RunAsync<T>(stringmessage,AgentSession?session=null,JsonSerializerOptions?serializerOptions=null,AgentRunOptions?options=null,CancellationTokencancellationToken=default);publicTask<AgentResponse<T>>RunAsync<T>(ChatMessagemessage,AgentSession?session=null,JsonSerializerOptions?serializerOptions=null,AgentRunOptions?options=null,CancellationTokencancellationToken=default);publicasyncTask<AgentResponse<T>>RunAsync<T>(IEnumerable<ChatMessage>messages,AgentSession?session=null,JsonSerializerOptions?serializerOptions=null,AgentRunOptions?options=null,CancellationTokencancellationToken=default);}publicclassAgentResponse<T>:AgentResponse{publicboolIsWrappedInObject{get;init;}publicvirtualTResult{get;}}

所以上面采用LangChain演示的实例在MAF中可以改写成如下的形式:

usingdotenv.net;usingMicrosoft.Extensions.AI;usingOpenAI;usingSystem.ClientModel;usingSystem.ComponentModel;usingSystem.Diagnostics;DotEnv.Load();varmodel=Environment.GetEnvironmentVariable("MODEL")!;varapiKey=Environment.GetEnvironmentVariable("API_KEY")!;varopenAIUrl=Environment.GetEnvironmentVariable("OPENAI_URL")!;varagent=newOpenAIClient(credential:newApiKeyCredential(key:apiKey),options:newOpenAIClientOptions{Endpoint=newUri(openAIUrl)}).GetChatClient(model:model).AsIChatClient().AsAIAgent();varquery="My name is Jayden, I am 18 years old and I like hiking and painting.";query=$""" Extract informationfromthe following text.context:{query}""";varresponse=awaitagent.RunAsync<UserInfo>(message:query);varuserInfo=response.Result;Debug.Assert(userInfo.Name=="Jayden");Debug.Assert(userInfo.Age==18);Debug.Assert(userInfo.Hobbies.SequenceEqual(new[]{"hiking","painting"}));publicclassUserInfo{[Description("user's name")]publicstring?Name{get;set;}[Description("user's age")]publicintAge{get;set;}[Description("user's hobbies")]publicstring[]Hobbies{get;set;}=[];}

AIAgent执行时由AgentRunOptionsResponseFormat属性来控制结构化输出的格式。上面四个泛型的RunAsync<T>方法最终会根据泛型参数T创建一个代表其JSON Schema的ChatResponseFormat对象,并将这个对象赋值给传入方法的AgentRunOptionsResponseFormat属性。待接收到LLM的响应之后,对JSON文本进行反序列化。

publicclassAgentRunOptions{publicChatResponseFormat?ResponseFormat{get;set;}}

所以上面演示程序中与下面这段是完全等效的:

usingdotenv.net;usingMicrosoft.Agents.AI;usingMicrosoft.Extensions.AI;usingOpenAI;usingSystem.ClientModel;usingSystem.ComponentModel;usingSystem.Diagnostics;usingSystem.Text.Json;DotEnv.Load();varmodel=Environment.GetEnvironmentVariable("MODEL")!;varapiKey=Environment.GetEnvironmentVariable("API_KEY")!;varopenAIUrl=Environment.GetEnvironmentVariable("OPENAI_URL")!;varagent=newOpenAIClient(credential:newApiKeyCredential(key:apiKey),options:newOpenAIClientOptions{Endpoint=newUri(openAIUrl)}).GetChatClient(model:model).AsIChatClient().AsAIAgent();varquery="My name is Jayden, I am 18 years old and I like hiking and painting.";query=$""" Extract informationfromthe following text.context:{query}""";varresponseFormat=ChatResponseFormat.ForJsonSchema<UserInfo>();varresponse=awaitagent.RunAsync(message:query,options:newChatClientAgentRunOptions{ResponseFormat=responseFormat});varuserInfo=JsonSerializer.Deserialize<UserInfo>(response.Text,AgentAbstractionsJsonUtilities.DefaultOptions)!;Debug.Assert(userInfo.Name=="Jayden");Debug.Assert(userInfo.Age==18);Debug.Assert(userInfo.Hobbies.SequenceEqual(["hiking","painting"]));

利用AgentRunOptionsResponseFormat属性指定的希望输出的JSON Schema体现在发送给LLM的请求中,如下面的HTTP请求所示:

POST https://jinna-mjct0aiy-swedencentral.openai.azure.com/openai/v1/chat/completions HTTP/1.1 Host: jinna-mjct0aiy-swedencentral.openai.azure.com Accept: application/json User-Agent: OpenAI/2.10.0 (.NET 10.0.7; Microsoft Windows 10.0.26200) MEAI/10.5.0 Authorization: Bearer 8Kvb0MoMlk3ie0o2G01KVqaqc2tqIwq4RpxvEVTtmHNR9OFUmpdnJQQJ99BLACfhMk5XJ3w3AAAAACOG1Sww Content-Type: application/json Content-Length: 845 {"messages":[{"role":"user","content":"Extract information from the following text.\r\ncontext: My name is Jayden, I am 18 years old and I like hiking and painting."}],"model":"gpt-5.2-chat","response_format":{"type":"json_schema","json_schema":{"name":"UserInfo","schema":{ "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "properties": { "name": { "description": "user's name", "type": [ "string", "null" ] }, "age": { "description": "user's age", "type": "integer" }, "hobbies": { "description": "user's hobbies", "type": "array", "items": { "type": "string" } } }, "additionalProperties": false, "required": [ "name", "age", "hobbies" ] }}}}
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/15 10:07:49

VSCode、Obsidian、Typora都适用!一键插入Emoji的Markdown插件和工具全攻略

跨平台Markdown写作&#xff1a;Emoji高效插入全方案指南 在数字写作时代&#xff0c;Emoji已经超越了简单的表情符号&#xff0c;成为提升内容表现力的重要元素。无论是技术文档、学习笔记还是创意写作&#xff0c;恰到好处的Emoji使用都能让文字更具吸引力。然而&#xff0c;…

作者头像 李华
网站建设 2026/6/15 10:05:52

信奥的数学题单(2026.06.15)

NOI / 小学奥数&#xff08;20题&#xff09; OpenJudge - OpenJudge - 题目 C编程与信息学竞赛数学思维&#xff08;2026.06&#xff09; 【数学思维】01-变量及输入输出 https://www.luogu.com.cn/training/675222 【数学思维】02-用单位正方形/体理解数学问题 https://www.l…

作者头像 李华
网站建设 2026/6/15 10:04:54

从清华到北航:拆解中科院自动化所偏爱的生源地图与导师联系“潜规则”

解码中科院自动化所的生源密码&#xff1a;如何借力院校背景与导师网络突围保研站在北京中关村南大街的十字路口&#xff0c;抬头就能望见中国科学院自动化研究所那座低调的灰色大楼。这里每年吸引着全国最优秀的理工科学生&#xff0c;但仔细观察录取名单会发现一个有趣现象&a…

作者头像 李华
网站建设 2026/6/15 10:01:50

遗传算法工程化实战:参数设计、算子选型与早熟应对

1. 项目概述&#xff1a;为什么“遗传算法第二讲”比第一讲更值得细读“遗传算法”这个词&#xff0c;刚听时容易让人联想到生物课上染色体配对、孟德尔豌豆实验&#xff0c;甚至误以为是生物信息学专属工具。但实际在工业界——从物流路径优化到芯片布线&#xff0c;从金融风控…

作者头像 李华
网站建设 2026/6/15 10:01:50

IF-08 AURIX时钟系统 - 从晶振到CCU分发

IF-08 AURIX时钟系统 - 从晶振到CCU分发 IF-08 AURIX时钟系统 - 从晶振到CCU分发一、引言在汽车电子控制单元&#xff08;ECU&#xff09;中&#xff0c;时钟系统是整个芯片的"心脏起搏器"。没有稳定、精确的时钟&#xff0c;高速CAN通信会乱码&#xff0c;ADC采样…

作者头像 李华