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之外,还有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]|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会自动地在
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: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执行时由AgentRunOptions的ResponseFormat属性来控制结构化输出的格式。上面四个泛型的RunAsync<T>方法最终会根据泛型参数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();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"]));利用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": "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" ] }}}}