Skip to main content
本快速入门将引导你在几分钟内从简单设置到构建一个功能完整的 AI 智能体。
正在使用 AI 编程助手?

要求

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

构建一个基础智能体

首先创建一个能够回答问题并调用工具的简单智能体。该智能体将使用 Claude Sonnet 4.6 作为其语言模型,一个基础的天气函数作为工具,以及一个简单的提示词来指导其行为。
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: "获取指定城市的天气",
    schema: z.object({
      city: z.string().describe("要获取天气的城市"),
    }),
  }
);

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 追踪你的智能体,请参阅 LangSmith 文档

构建一个真实场景的智能体

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

定义系统提示词

系统提示词定义了你的智能体的角色和行为。请保持其具体且可操作:
const systemPrompt = `你是一位擅长说双关语的天气预报专家。

你可以使用两种工具:

- get_weather_for_location:用于获取特定地点的天气
- get_user_location:用于获取用户的位置

如果用户询问天气,请确保你知道地点。如果你能从问题中判断他们指的是他们所在的位置,请使用 get_user_location 工具来查找他们的位置。`;
2

创建工具

工具 是你的智能体可以调用的函数。通常,工具会希望连接到外部系统,并依赖运行时配置来实现。请注意这里的 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: "获取指定城市的天气",
    schema: z.object({
      city: z.string().describe("要获取天气的城市"),
    }),
  }
);

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: "根据用户 ID 检索用户信息",
  }
);
Zod 是一个用于验证和解析预定义模式的库。你可以用它来定义工具的输入模式,以确保智能体只使用正确的参数调用工具。或者,你可以将 schema 属性定义为一个 JSON 模式 对象。请注意,JSON 模式不会在运行时进行验证。
const getWeather = tool(
  ({ city }) => `It's always sunny in ${city}!`,
  {
    name: "get_weather_for_location",
    description: "获取指定城市的天气",
    schema: {
      type: "object",
      properties: {
        city: {
          type: "string",
          description: "要获取天气的城市"
        }
      },
      required: ["city"]
    },
  }
);
3

配置你的模型

根据你的用例设置合适的参数来配置你的语言模型
import { initChatModel } from "langchain";

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

定义响应格式

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

添加记忆

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

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

创建并运行智能体

现在,用所有组件组装你的智能体并运行它!
import { createAgent } from "langchain";

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

// `thread_id` 是给定对话的唯一标识符。
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!"
// }

// 注意,我们可以使用相同的 `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 追踪你的智能体,请参阅 LangSmith 文档
恭喜!你现在拥有一个能够:
  • 理解上下文并记住对话
  • 智能地使用多种工具
  • 以一致的格式提供结构化响应
  • 通过上下文处理用户特定信息
  • 在交互之间维护对话状态
的 AI 智能体。