Skip to content

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

前提条件

本指南假设您熟悉以下内容:

要从预构建的ReAct代理返回结构化输出,您可以在create_react_agent中提供一个带有所需输出模式的response_format参数:

class ResponseFormat(BaseModel):
    """以这种格式回复用户。"""
    my_special_output: str


graph = create_react_agent(
    model,
    tools=tools,
    # 使用`response_format`参数指定结构化输出的模式
    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")

为LangGraph开发设置LangSmith

注册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 Reference: 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调用以生成结构化的输出,并提供一个系统提示。为此,您可以传递一个元组 (提示, 架构):

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')

Comments