Skip to content

如何使用预构建的ReAct代理

前提条件

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

在本教程中,我们将创建一个简单的 ReAct 代理应用程序,该应用程序可以检查天气。该应用程序由代理(LLM)和工具组成。当我们与应用程序互动时,我们将首先调用代理(LLM)来决定是否使用工具。然后我们将运行一个循环:

  1. 如果代理要求采取行动(即调用工具),我们将运行工具并将结果传递回代理
  2. 如果代理没有要求运行工具,我们将完成操作(回应用户)

预构建代理

请注意,这里我们将使用 一个预构建的代理。LangGraph 的一个主要优点是您可以轻松创建自己的代理架构。因此,虽然从这里开始快速构建代理是可以的,但我们强烈建议您学习如何构建自己的代理,以便能够充分利用 LangGraph。

设置

首先,我们安装所需的包并设置我们的 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 应用程序——有关如何开始的更多信息,请在 这里 阅读。

代码

# 首先,我们初始化我们想要使用的模型。
from langchain_openai import ChatOpenAI

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


# 在本教程中,我们将使用一个自定义工具,该工具返回两个城市(纽约市和旧金山)的预定义天气值。

from typing import Literal

from langchain_core.tools import tool


@tool
def get_weather(city: Literal["nyc", "sf"]):
    """用这个来获取天气信息。"""
    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]


# 定义图形

from langgraph.prebuilt import create_react_agent

graph = create_react_agent(model, tools=tools)
API Reference: ChatOpenAI | tool | create_react_agent

用法

首先,让我们可视化我们刚刚创建的图形

from IPython.display import Image, display

display(Image(graph.get_graph().draw_mermaid_png()))

def print_stream(stream):
    for s in stream:
        message = s["messages"][-1]
        if isinstance(message, tuple):
            print(message)
        else:
            message.pretty_print()

让我们运行一个需要工具调用的输入的应用程序。

inputs = {"messages": [("user", "what is the weather in sf")]}
print_stream(graph.stream(inputs, stream_mode="values"))
================================ Human Message =================================

what is the weather in sf
================================== Ai Message ==================================
Tool Calls:
  get_weather (call_zVvnU9DKr6jsNnluFIl59mHb)
 Call ID: call_zVvnU9DKr6jsNnluFIl59mHb
  Args:
    city: sf
================================= Tool Message =================================
Name: get_weather

It's always sunny in sf
================================== Ai Message ==================================

The weather in San Francisco is currently sunny.
现在让我们尝试一个不需要工具的问题。

inputs = {"messages": [("user", "who built you?")]}
print_stream(graph.stream(inputs, stream_mode="values"))
================================ Human Message =================================

who built you?
================================== Ai Message ==================================

I was created by OpenAI, a research organization focused on developing and advancing artificial intelligence technology.

优云智算