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

[对比学习LangChain和MAF-09]利用结构化输出生成指定结构的内容 AI Agent的结构化输出是指Agent在执行任务时不再返回自然语言文本而是严格按照预定义的格式如JSON、XML、YAML 或特定数据对象输出数据。这是将AI从能聊天的Agent演变为能精确执行工业级业务流的系统的核心技术。下来我们来看看LangChain和MAF是如何支持Agent的结构化输出的。1. LangChainLangChain针对结构化输出提供了两种编程模式一种是采用采用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:strField(descriptionusers name)age:intField(descriptionusers age)hobbies:list[str]Field(descriptionusers hobbies)parserJsonOutputParser(pydantic_objectUserInfo)template\ Extract information from the following text. {format_instructions} context: {query}prompt(PromptTemplate.from_template(template).partial(format_instructionsparser.get_format_instructions()))llmChatOpenAI(modelgpt-5.2-chat)chainprompt|llm|parser queryMy name is Jayden, I am 18 years old and I like hiking and painting.use_infochain.invoke({query:query})assertisinstance(use_info,UserInfo)assertuse_info.nameJaydenassertuse_info.age18assertuse_info.hobbies[hiking,painting]LangChain提供了很多预定义的输出解析器除了JsonOutputParser之外还有XMLOutputParser、PydanticOutputParser、ListOutputParser等满足不同的结构化输出需求。针对它们的详细介绍可以参考我如下两篇文章针对模型输出的解析上篇针对模型输出的解析下篇1.2 设置Agent的response_format数据只有具有希望的结构才可能被有效地处理我们在调用create_agent函数创建Agent的时候可以利用response_format控制输出的格式。我们可以定义一个Pydantic模型类表表示期望输出的结构如果将此类型表示成ResponseT我们可以直接将此类型作为response_format参数的值也可以将此参数赋值为ResponseFormat[ResponseT]。除此之外我们也可以创建一个表示JSON Schema的字典作为response_format参数的值。ResponseFormat实际上针对ToolStrategy、ProviderStrategy和AutoStrategy三个类型的联合。ToolStrategy和ProviderStrategy代表了两种实现结构化输出的不同技术路径。defcreate_agent(...response_format:ResponseFormat[ResponseT]|type[ResponseT]|dict[str,Any]|NoneNone,...)ResponseFormatToolStrategy[SchemaT]|ProviderStrategy[SchemaT]|AutoStrategy[SchemaT]组成ResponseFormat的三个类型代表了结构化输出的三种策略ToolStrategy利用工具调用来实现结构化输出Agent在调用LLM的时候会将工具的定义包括输入输出的格式作为提示词的一部分传入LLMLLM在生成输出的时候按照工具的定义来生成工具调用的意图Agent在解析到这个工具调用意图之后就会调用对应的工具来获取结构化的数据结果ProviderStrategy利用Provider来实现结构化输出Agent在调用LLM的时候会将Provider的定义包括输入输出的格式作为提示词的一部分传入LLMLLM在生成输出的时候按照Provider的定义来生成调用Provider的意图Agent在解析到这个调用Provider的意图之后就会调用对应的Provider来获取结构化的数据结果AutoStrategyAgent会自动地在ToolStrategy和ProviderStrategy之间进行选择如果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:strField(descriptionusers name)age:intField(descriptionusers age)hobbies:list[str]Field(descriptionusers hobbies)agentcreate_agent(modelChatOpenAI(modelgpt-5.2-chat),response_formatAutoStrategy(schemaUserInfo),)queryMy name is Jayden, I am 18 years old and I like hiking and painting.queryf\ Extract information from the following text. context:{query}resultagent.invoke(input{messages:[{role:user,content:query}]})use_inforesult[structured_response]assertisinstance(use_info,UserInfo)assertuse_info.nameJaydenassertuse_info.age18assertuse_info.hobbies[hiking,painting]关于三种策略的实现原理可以参考我之前写的这篇文章结构化输出的两种实现方式。2. MAF在MAF中AIAgent定义了如下四个重载的RunAsyncT方法它们的返回值都是AgentResponseT类型其中泛型参数T表示结构化输出的类型。在得到作为返回值的AgentResponseT对象之后我们可以通过它的Result属性来获取结构化输出的结果。AgentResponseT类型继承自AgentResponse并新增了一个IsWrappedInObject属性用来指示结构化输出的结果是否被包装在一个对象中。publicabstractclassAIAgent{publicTaskAgentResponseTRunAsyncT(AgentSession?sessionnull,JsonSerializerOptions?serializerOptionsnull,AgentRunOptions?optionsnull,CancellationTokencancellationTokendefault);publicTaskAgentResponseTRunAsyncT(stringmessage,AgentSession?sessionnull,JsonSerializerOptions?serializerOptionsnull,AgentRunOptions?optionsnull,CancellationTokencancellationTokendefault);publicTaskAgentResponseTRunAsyncT(ChatMessagemessage,AgentSession?sessionnull,JsonSerializerOptions?serializerOptionsnull,AgentRunOptions?optionsnull,CancellationTokencancellationTokendefault);publicasyncTaskAgentResponseTRunAsyncT(IEnumerableChatMessagemessages,AgentSession?sessionnull,JsonSerializerOptions?serializerOptionsnull,AgentRunOptions?optionsnull,CancellationTokencancellationTokendefault);}publicclassAgentResponseT:AgentResponse{publicboolIsWrappedInObject{get;init;}publicvirtualTResult{get;}}所以上面采用LangChain演示的实例在MAF中可以改写成如下的形式usingdotenv.net;usingMicrosoft.Extensions.AI;usingOpenAI;usingSystem.ClientModel;usingSystem.ComponentModel;usingSystem.Diagnostics;DotEnv.Load();varmodelEnvironment.GetEnvironmentVariable(MODEL)!;varapiKeyEnvironment.GetEnvironmentVariable(API_KEY)!;varopenAIUrlEnvironment.GetEnvironmentVariable(OPENAI_URL)!;varagentnewOpenAIClient(credential:newApiKeyCredential(key:apiKey),options:newOpenAIClientOptions{EndpointnewUri(openAIUrl)}).GetChatClient(model:model).AsIChatClient().AsAIAgent();varqueryMy name is Jayden, I am 18 years old and I like hiking and painting.;query$ Extract informationfromthe following text.context:{query};varresponseawaitagent.RunAsyncUserInfo(message:query);varuserInforesponse.Result;Debug.Assert(userInfo.NameJayden);Debug.Assert(userInfo.Age18);Debug.Assert(userInfo.Hobbies.SequenceEqual(new[]{hiking,painting}));publicclassUserInfo{[Description(users name)]publicstring?Name{get;set;}[Description(users age)]publicintAge{get;set;}[Description(users hobbies)]publicstring[]Hobbies{get;set;}[];}AIAgent执行时由AgentRunOptions的ResponseFormat属性来控制结构化输出的格式。上面四个泛型的RunAsyncT方法最终会根据泛型参数T创建一个代表其JSON Schema的ChatResponseFormat对象并将这个对象赋值给传入方法的AgentRunOptions的ResponseFormat属性。待接收到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();varmodelEnvironment.GetEnvironmentVariable(MODEL)!;varapiKeyEnvironment.GetEnvironmentVariable(API_KEY)!;varopenAIUrlEnvironment.GetEnvironmentVariable(OPENAI_URL)!;varagentnewOpenAIClient(credential:newApiKeyCredential(key:apiKey),options:newOpenAIClientOptions{EndpointnewUri(openAIUrl)}).GetChatClient(model:model).AsIChatClient().AsAIAgent();varqueryMy name is Jayden, I am 18 years old and I like hiking and painting.;query$ Extract informationfromthe following text.context:{query};varresponseFormatChatResponseFormat.ForJsonSchemaUserInfo();varresponseawaitagent.RunAsync(message:query,options:newChatClientAgentRunOptions{ResponseFormatresponseFormat});varuserInfoJsonSerializer.DeserializeUserInfo(response.Text,AgentAbstractionsJsonUtilities.DefaultOptions)!;Debug.Assert(userInfo.NameJayden);Debug.Assert(userInfo.Age18);Debug.Assert(userInfo.Hobbies.SequenceEqual([hiking,painting]));利用AgentRunOptions的ResponseFormat属性指定的希望输出的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: users name, type: [ string, null ] }, age: { description: users age, type: integer }, hobbies: { description: users hobbies, type: array, items: { type: string } } }, additionalProperties: false, required: [ name, age, hobbies ] }}}}