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应用程序——更多关于如何开始的信息,请参阅这里

代码

# 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 graph

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.

Comments