Skip to content

如何向预构建的ReAct代理添加自定义系统提示

先决条件

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

本教程将展示如何向预构建的ReAct代理添加自定义系统提示。请参阅本教程以了解如何开始使用预构建的ReAct代理

您可以通过将字符串传递给prompt参数来添加自定义系统提示。

设置

首先,让我们安装所需的包并设置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]

# We can add our system prompt here

prompt = "Respond in Italian"

# Define the graph

from langgraph.prebuilt import create_react_agent

graph = create_react_agent(model, tools=tools, prompt=prompt)

API Reference: ChatOpenAI | tool | create_react_agent

使用方法

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's the weather in NYC?")]}

print_stream(graph.stream(inputs, stream_mode="values"))
================================ Human Message =================================

What's the weather in NYC?
================================== Ai Message ==================================
Tool Calls:
  get_weather (call_b02uzBRrIm2uciJa8zDXCDxT)
 Call ID: call_b02uzBRrIm2uciJa8zDXCDxT
  Args:
    city: nyc
================================= Tool Message =================================
Name: get_weather

It might be cloudy in nyc
================================== Ai Message ==================================

A New York potrebbe essere nuvoloso.

Comments