Skip to main content
本快速入门将带您在几分钟内从简单设置到功能齐全的 AI agent。
LangChain Docs MCP server如果您使用的是 AI 编码助手或 IDE(例如 Claude Code 或 Cursor),您应该安装 LangChain Docs MCP server 以充分利用它。这确保您的 agent 可以访问最新的 LangChain 文档和示例。

要求

对于这些示例,您需要:
  • 安装 LangChain 包
  • 设置一个 Claude (Anthropic) 帐户并获取 API 密钥
  • 在您的终端中设置 ANTHROPIC_API_KEY 环境变量
虽然这些示例使用 Claude,但您可以通过更改代码中的模型名称并设置适当的 API 密钥来使用 任何支持的模型

构建一个基本 agent

首先创建一个可以回答问题并调用工具的简单 agent。该 agent 将使用 Claude Sonnet 4.5 作为其语言模型,使用基本的 weather 函数作为工具,并使用简单的提示来指导其行为。
import { createAgent, tool } from "langchain";
import * as z from "zod";

const getWeather = tool(
  (input) => `It's always sunny in ${input.city}!`,
  {
    name: "get_weather",
    description: "Get the weather for a given city",
    schema: z.object({
      city: z.string().describe("The city to get the weather for"),
    }),
  }
);

const agent = createAgent({
  model: "claude-sonnet-4-6",
  tools: [getWeather],
});

console.log(
  await agent.invoke({
    messages: [{ role: "user", content: "What's the weather in Tokyo?" }],
  })
);
要了解如何使用 LangSmith 跟踪您的 agent,请参阅 LangSmith 文档

构建一个真实世界的 agent

接下来,构建一个实用的天气预报 agent,演示关键的生产概念:
  1. 详细的系统提示 (System Prompts) 以获得更好的 agent 行为
  2. 创建工具 以与外部数据集成
  3. 模型配置 以获得一致的响应
  4. 结构化输出 以获得可预测的结果
  5. 对话记忆 以进行类似聊天的交互
  6. 创建并运行 agent 以测试功能齐全的 agent
让我们逐步完成:
1

定义系统提示

系统提示定义了您的 agent 的角色和行为。保持其具体和可操作:
const systemPrompt = `You are an expert weather forecaster, who speaks in puns.

You have access to two tools:

- get_weather_for_location: use this to get the weather for a specific location
- get_user_location: use this to get the user's location

If a user asks you for the weather, make sure you know the location. If you can tell from the question that they mean wherever they are, use the get_user_location tool to find their location.`;
2

创建工具

工具 (Tools) 是您的 agent 可以调用的函数。通常,工具需要连接到外部系统,并依赖运行时配置来做到这一点。请注意 getUserLocation 工具是如何做到这一点的:
import { tool, type ToolRuntime } from "langchain";
import * as z from "zod";

const getWeather = tool(
  (input) => `It's always sunny in ${input.city}!`,
  {
    name: "get_weather_for_location",
    description: "Get the weather for a given city",
    schema: z.object({
      city: z.string().describe("The city to get the weather for"),
    }),
  }
);

type AgentRuntime = ToolRuntime<unknown, { user_id: string }>;

const getUserLocation = tool(
  (_, config: AgentRuntime) => {
    const { user_id } = config.context;
    return user_id === "1" ? "Florida" : "SF";
  },
  {
    name: "get_user_location",
    description: "Retrieve user information based on user ID",
  }
);
Zod 是一个用于验证和解析预定义模式的库。您可以使用它来定义工具的输入模式,以确保 agent 仅使用正确的参数调用工具。或者,您可以将 schema 属性定义为 JSON schema 对象。请记住,JSON schemas 不会 在运行时进行验证。
const getWeather = tool(
  ({ city }) => `It's always sunny in ${city}!`,
  {
    name: "get_weather_for_location",
    description: "Get the weather for a given city",
    schema: {
      type: "object",
      properties: {
        city: {
          type: "string",
          description: "The city to get the weather for"
        }
      },
      required: ["city"]
    },
  }
);
3

配置您的模型

为您的用例设置具有正确参数的 语言模型
import { initChatModel } from "langchain";

const model = await initChatModel(
  "claude-sonnet-4-6",
  { temperature: 0.5, timeout: 10, maxTokens: 1000 }
);
根据选择的模型和提供商,初始化参数可能会有所不同;有关详细信息,请参阅其参考页面。
4

定义响应格式

如果您需要 agent 响应匹配特定模式,可以选择定义结构化响应格式。
const responseFormat = z.object({
  punny_response: z.string(),
  weather_conditions: z.string().optional(),
});
5

添加记忆

向您的 agent 添加 记忆 以在交互之间保持状态。这允许 agent 记住之前的对话和上下文。
import { MemorySaver } from "@langchain/langgraph";

const checkpointer = new MemorySaver();
在生产环境中,使用将消息历史记录保存到数据库的持久化检查点保存器。 有关更多详细信息,请参阅 添加和管理记忆
6

创建并运行 agent

现在用所有组件组装您的 agent 并运行它!
import { createAgent } from "langchain";

const agent = createAgent({
  model: "claude-sonnet-4-6",
  systemPrompt: systemPrompt,
  tools: [getUserLocation, getWeather],
  responseFormat,
  checkpointer,
});

// `thread_id` is a unique identifier for a given conversation.
const config = {
  configurable: { thread_id: "1" },
  context: { user_id: "1" },
};

const response = await agent.invoke(
  { messages: [{ role: "user", content: "what is the weather outside?" }] },
  config
);
console.log(response.structuredResponse);
// {
//   punny_response: "Florida is still having a 'sun-derful' day ...",
//   weather_conditions: "It's always sunny in Florida!"
// }

// Note that we can continue the conversation using the same `thread_id`.
const thankYouResponse = await agent.invoke(
  { messages: [{ role: "user", content: "thank you!" }] },
  config
);
console.log(thankYouResponse.structuredResponse);
// {
//   punny_response: "You're 'thund-erfully' welcome! ...",
//   weather_conditions: undefined
// }
要了解如何使用 LangSmith 跟踪您的 agent,请参阅 LangSmith 文档
恭喜!您现在拥有一个 AI agent,它可以:
  • 理解上下文 并记住对话
  • 智能地 使用多个工具
  • 以一致的格式 提供结构化响应
  • 通过上下文 处理特定于用户的信息
  • 跨交互 保持对话状态