跳到内容

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

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

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

兼容性

stateModifier 参数是在 @langchain/langgraph>=0.2.27 中添加的。
如果您使用的是旧版本,则需要使用已弃用的 messageModifier 参数。
如需升级方面的帮助,请参阅本指南

设置

首先,我们需要安装所需的软件包。

yarn add @langchain/langgraph @langchain/openai @langchain/core

本指南将使用 OpenAI 的 GPT-4o 模型。我们将可选地为 LangSmith 跟踪设置我们的 API 密钥,这将为我们提供一流的可观察性。

// process.env.OPENAI_API_KEY = "sk_...";

// Optional, add tracing in LangSmith
// process.env.LANGCHAIN_API_KEY = "ls__..."
// process.env.LANGCHAIN_CALLBACKS_BACKGROUND = "true";
process.env.LANGCHAIN_CALLBACKS_BACKGROUND = "true";
process.env.LANGCHAIN_TRACING_V2 = "true";
process.env.LANGCHAIN_PROJECT = "ReAct Agent with system prompt: LangGraphJS";
ReAct Agent with system prompt: LangGraphJS

代码

现在我们可以使用预构建的 createReactAgent 函数来设置带有系统提示的代理

import { ChatOpenAI } from "@langchain/openai";
import { tool } from '@langchain/core/tools';
import { z } from 'zod';
import { createReactAgent } from "@langchain/langgraph/prebuilt";

const model = new ChatOpenAI({
    model: "gpt-4o",
  });

const getWeather = tool((input) => {
    if (input.location === 'sf') {
        return 'It\'s always sunny in sf';
    } else {
        return 'It might be cloudy in nyc';
    }
}, {
    name: 'get_weather',
    description: 'Call to get the current weather.',
    schema: z.object({
        location: z.enum(['sf','nyc']).describe("Location to get the weather for."),
    })
})

// We can add our system prompt here
const prompt = "Respond in Italian"

const agent = createReactAgent({ llm: model, tools: [getWeather], stateModifier: prompt });

用法

让我们验证代理是否确实用意大利语回复!

let inputs = { messages: [{ role: "user", content: "what is the weather in NYC?" }] };
let stream = await agent.stream(inputs, {
  streamMode: "values",
});

for await (
  const { messages } of stream
) {
  let msg = messages[messages?.length - 1];
  if (msg?.content) {
    console.log(msg.content);
  } else if (msg?.tool_calls?.length > 0) {
    console.log(msg.tool_calls);
  } else {
    console.log(msg);
  }
  console.log("-----\n");
}
what is the weather in NYC?
-----

[
  {
    name: 'get_weather',
    args: { location: 'nyc' },
    type: 'tool_call',
    id: 'call_PqmKDQrefHQLmGsZSSr4C7Fc'
  }
]
-----

It might be cloudy in nyc
-----

A New York potrebbe essere nuvoloso. Hai altre domande o posso aiutarti in qualcos'altro?
-----