结构化输出
概览
对于许多应用程序,例如聊天机器人,模型需要直接以自然语言响应用户。 但是,在某些情况下,我们需要模型以结构化格式进行输出。 例如,我们可能希望将模型输出存储在数据库中,并确保输出符合数据库的模式。 这种需求促成了结构化输出的概念,即可以指示模型以特定的输出结构进行响应。

关键概念
- 模式定义: 输出结构由模式表示,该模式可以通过多种方式定义。
- 返回结构化输出: 模型会接收此模式,并被指示返回符合该模式的输出。
推荐用法
此伪代码说明了使用结构化输出时推荐的工作流程。
LangChain 提供了一个方法,with_structured_output(),该方法自动化了将模式绑定到模型和解析输这个过程。
此辅助函数适用于所有支持结构化输出的模型提供商。
# Define schema
schema = {"foo": "bar"}
# Bind schema to model
model_with_structure = model.with_structured_output(schema)
# Invoke the model to produce structured output that matches the schema
structured_output = model_with_structure.invoke(user_input)
模式定义
核心概念是需要以某种方式表示模型响应的输出结构。 虽然您可以使用的对象类型取决于您正在使用的模型,但通常允许或推荐用于 Python 中结构化输出的常用对象类型。
结构化输出最简单也是最常见的格式是类似 JSON 的结构,在 Python 中可以表示为字典 (dict) 或列表 (list)。 当工具需要原始、灵活且开销最小的结构化数据时,通常直接使用 JSON 对象(或 Python 中的 dict)。
{
"answer": "The answer to the user's question",
"followup_question": "A followup question the user could ask"
}
作为第二个示例,Pydantic 因其提供类型提示和验证而特别适用于定义结构化输出模式。 这是一个 Pydantic 模式的示例:
from pydantic import BaseModel, Field
class ResponseFormatter(BaseModel):
"""Always use this tool to structure your response to the user."""
answer: str = Field(description="The answer to the user's question")
followup_question: str = Field(description="A followup question the user could ask")
返回结构化输出
定义了模式后,我们需要一种方法来指示模型使用它。 虽然一种方法是将此模式包含在提示中并礼貌地要求模型使用它,但不推荐这样做。 有几种更强大的方法利用模型提供商 API 中的原生功能。
使用工具调用
许多模型提供商支持工具调用,其概念将在我们的工具调用指南中更详细地讨论。
简而言之,工具调用涉及将工具绑定到模型,并在适当的时候,模型可以决定调用该工具并确保其响应符合该工具的模式。
考虑到这一点,核心概念很简单:只需将我们的模式作为工具绑定到模型!
这是一个使用上面定义的 ResponseFormatter 模式的示例:
from langchain_openai import ChatOpenAI
model = ChatOpenAI(model="gpt-4o", temperature=0)
# Bind responseformatter schema as a tool to the model
model_with_tools = model.bind_tools([ResponseFormatter])
# Invoke the model
ai_msg = model_with_tools.invoke("What is the powerhouse of the cell?")
工具调用的参数已经提取为一个字典。
这个字典可以根据需要选择性地解析为 Pydantic 对象,以匹配我们原始的 ResponseFormatter 模式。
# Get the tool call arguments
ai_msg.tool_calls[0]["args"]
{'answer': "The powerhouse of the cell is the mitochondrion. Mitochondria are organelles that generate most of the cell's supply of adenosine triphosphate (ATP), which is used as a source of chemical energy.",
'followup_question': 'What is the function of ATP in the cell?'}
# Parse the dictionary into a pydantic object
pydantic_object = ResponseFormatter.model_validate(ai_msg.tool_calls[0]["args"])
JSON 模式
除了工具调用,一些模型提供商还支持称为 JSON mode 的功能。
它支持将 JSON 模式定义作为输入,并强制模型生成符合要求的 JSON 输出。
您可以在此处找到支持 JSON 模式的模型提供商的表格。
以下是如何在 OpenAI 中使用 JSON 模式的示例:
from langchain_openai import ChatOpenAI
model = ChatOpenAI(model="gpt-4o").with_structured_output(method="json_mode")
ai_msg = model.invoke("Return a JSON object with key 'random_ints' and a value of 10 random ints in [0-99]")
ai_msg
{'random_ints': [45, 67, 12, 34, 89, 23, 78, 56, 90, 11]}
结构化输出方法
使用上述方法生成结构化输出时存在一些挑战:
-
当使用工具调用时,需要将工具调用参数从字典解析回原始模式。
-
此外,当我们要强制执行结构化输出时,需要指示模型始终使用该工具,这是一个特定于提供商的设置。
-
当使用 JSON 模式时,需要将输出解析为 JSON 对象。
考虑到这些挑战,LangChain 提供了一个辅助函数(with_structured_output())来简化此过程。

它将模式作为工具绑定到模型,并将输出解析为指定的输出模式。
# Bind the schema to the model
model_with_structure = model.with_structured_output(ResponseFormatter)
# Invoke the model
structured_output = model_with_structure.invoke("What is the powerhouse of the cell?")
# Get back the pydantic object
structured_output
ResponseFormatter(answer="The powerhouse of the cell is the mitochondrion. Mitochondria are organelles that generate most of the cell's supply of adenosine triphosphate (ATP), which is used as a source of chemical energy.", followup_question='What is the function of ATP in the cell?')
有关更多用法详细信息,请参阅我们的操作指南。