跳到内容

如何从预构建的 ReAct 代理返回结构化输出

先决条件

本指南假定您熟悉以下内容

要从预构建的 ReAct 代理返回结构化输出,您可以为 create_react_agent 提供带有期望输出模式的 response_format 参数

class ResponseFormat(BaseModel):
    """Respond to the user in this format."""
    my_special_output: str


graph = create_react_agent(
    model,
    tools=tools,
    # specify the schema for the structured output using `response_format` parameter
    response_format=ResponseFormat
)

预构建的 ReAct 在 ReAct 循环结束时进行额外的 LLM 调用,以生成结构化输出响应。请参阅本指南,了解从工具调用代理返回结构化输出的其他策略。

设置

首先,让我们安装所需的软件包并设置我们的 API 密钥

%%capture --no-stderr
%pip install -U langgraph langchain-openai
import getpass
import os


def _set_env(var: str):
    if not os.environ.get(var):
        os.environ[var] = getpass.getpass(f"{var}: ")


_set_env("OPENAI_API_KEY")

设置 LangSmith 以进行 LangGraph 开发

注册 LangSmith 以快速发现问题并提高 LangGraph 项目的性能。LangSmith 让您可以使用跟踪数据来调试、测试和监控使用 LangGraph 构建的 LLM 应用程序——阅读更多关于如何开始使用 此处 的信息。

代码

# First we initialize the model we want to use.
from langchain_openai import ChatOpenAI

model = ChatOpenAI(model="gpt-4o", temperature=0)

# For this tutorial we will use custom tool that returns pre-defined values for weather in two cities (NYC & SF)

from typing import Literal
from langchain_core.tools import tool


@tool
def get_weather(city: Literal["nyc", "sf"]):
    """Use this to get weather information."""
    if city == "nyc":
        return "It might be cloudy in nyc"
    elif city == "sf":
        return "It's always sunny in sf"
    else:
        raise AssertionError("Unknown city")


tools = [get_weather]

# Define the structured output schema

from pydantic import BaseModel, Field


class WeatherResponse(BaseModel):
    """Respond to the user in this format."""

    conditions: str = Field(description="Weather conditions")


# Define the graph

from langgraph.prebuilt import create_react_agent

graph = create_react_agent(
    model,
    tools=tools,
    # specify the schema for the structured output using `response_format` parameter
    response_format=WeatherResponse,
)

API 参考:ChatOpenAI | tool | create_react_agent

用法

现在让我们测试我们的代理

inputs = {"messages": [("user", "What's the weather in NYC?")]}
response = graph.invoke(inputs)

您可以看到代理输出包含一个 structured_response 键,其中包含符合指定的 WeatherResponse 模式的结构化输出,以及 messages 键下的消息历史记录。

response["structured_response"]
WeatherResponse(conditions='cloudy')

自定义提示

您可能需要进一步自定义第二个 LLM 调用以生成结构化输出,并提供系统提示。为此,您可以传递一个元组 (prompt, schema)

graph = create_react_agent(
    model,
    tools=tools,
    # specify both the system prompt and the schema for the structured output
    response_format=("Always return capitalized weather conditions", WeatherResponse),
)

inputs = {"messages": [("user", "What's the weather in NYC?")]}
response = graph.invoke(inputs)

您可以验证结构化响应现在包含一个大写值

response["structured_response"]
WeatherResponse(conditions='Cloudy')

评论