如何从预构建的 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 密钥。
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 构建的大语言模型应用程序 — 点击 此处 了解更多关于如何开始使用的信息。
代码¶
# 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: tool
使用方法¶
现在让我们测试一下我们的智能体:
你可以看到,代理输出包含一个 structured_response
键,其结构化输出符合指定的 WeatherResponse
架构,此外,messages
键下还有消息历史记录。
自定义提示语¶
你可能需要进一步自定义第二次大语言模型(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)
你可以验证现在结构化响应中包含一个首字母大写的值: