本快速开始展示如何在几分钟内创建一个功能完整的 AI 代理。
正在使用 AI 编程助手?

安装依赖

安装以下包以跟随操作:
npm install deepagents langchain @langchain/core
# Requires Node.js 20+

设置 API keys

任意支持的模型 provider 获取 API key(例如 Google Gemini 或 OpenAI)。 设置 API keys,例如:
export OPENAI_API_KEY="your-api-key"

构建基础代理

首先创建一个可以回答问题并调用工具的简单代理。此示例中的代理使用所选语言模型、作为工具的基础天气函数,以及用于引导其行为的简单 prompt:
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: "gpt-5.4",
  tools: [getWeather],
});

console.log(
  await agent.invoke({
    messages: [{ role: "user", content: "What's the weather in San Francisco?" }],
  })
);
运行代码并提示代理告诉你 San Francisco 的天气时,代理会使用该输入和它可用的上下文。 代理会理解你在询问 San Francisco 这座城市的天气,因此会使用提供的城市名称调用天气工具。
可以通过更改模型名称并设置相应 API key 来使用任意支持的模型。使用 LangSmith 跟踪代理内部发生的事情。按照 tracing quickstart 完成设置。还建议设置 LangSmith Engine,它会监控 traces、检测问题并提出修复建议。

构建真实世界代理

在下面的示例中,你将构建一个可以回答文本文件相关问题的研究代理。 在此过程中,你将探索以下概念:
  1. 用于改善代理行为的详细 system prompts
  2. 创建工具以集成外部数据
  3. 用于一致响应的模型配置
  4. 用于聊天式交互的对话记忆
  5. 提供内置功能的 Deep Agents
  6. 测试你的代理
1

定义 system prompt

System prompt 定义代理的角色和行为。保持具体且可执行:
const SYSTEM_PROMPT = `You are a literary data assistant.

## Capabilities

- \`fetch_text_from_url\`: loads document text from a URL into the conversation.
Do not guess line counts or positions—ground them in tool results from the saved file.`;
2

创建工具

Tools 让模型通过调用你定义的函数与外部系统交互。 Tools 可以依赖 runtime context,也可以与 agent memory 交互。此示例使用一个工具从给定 URL 加载文档:
import { tool } from "@langchain/core/tools";
import { createAgent, initChatModel } from "langchain";
import { z } from "zod";

const fetchTextFromUrl = tool(
    async ({ url }: { url: string }): Promise<string> => {
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), 120_000);
        try {
            const resp = await fetch(url, {
                headers: {
                "User-Agent": "Mozilla/5.0 (compatible; quickstart-research/1.0)",
                },
                signal: controller.signal,
            });
            if (!resp.ok) {
                return `Fetch failed: HTTP ${resp.status} ${resp.statusText}`;
            }
            return await resp.text();
        } catch (e) {
            const msg = e instanceof Error ? e.message : String(e);
            return `Fetch failed: ${msg}`;
        } finally {
            clearTimeout(timeoutId);
        }
    },
    {
        name: "fetch_text_from_url",
        description: "Fetch the document from a URL.",
        schema: z.object({ url: z.string().url() }),
    },
);
Zod 是一个用于验证和解析预定义 schemas 的库。可以使用它定义工具输入 schema,确保代理只使用正确参数调用工具。也可以将 schema 属性定义为 JSON schema 对象。请注意,JSON schemas 不会在运行时验证。
import { tool } from "@langchain/core/tools";

const fetchTextFromUrl = tool(
async ({ url }: { url: string }): Promise<string> => {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 120_000);
    try {
    const resp = await fetch(url, {
        headers: {
        "User-Agent": "Mozilla/5.0 (compatible; quickstart-research/1.0)",
        },
        signal: controller.signal,
    });
    if (!resp.ok) {
        return `Fetch failed: HTTP ${resp.status} ${resp.statusText}`;
    }
    return await resp.text();
    } catch (e) {
    const msg = e instanceof Error ? e.message : String(e);
    return `Fetch failed: ${msg}`;
    } finally {
    clearTimeout(timeoutId);
    }
},
{
    name: "fetch_text_from_url",
    description: "Fetch the document from a URL.",
    schema: {
    type: "object",
    properties: {
        url: {
        type: "string",
        description: "The URL of the document to fetch.",
        format: "uri",
        },
    },
    required: ["url"],
    },
},
);
3

配置模型

使用适合用例的参数设置你的 language model。例如:
import { initChatModel } from "langchain";

const model = await initChatModel("gpt-5.4", {
  temperature: 0.5,
  timeout: 300,
  maxTokens: 25000,
});
根据所选模型和 provider,初始化参数可能有所不同;详情请参阅各自的参考页面。
4

添加 memory

为代理添加 memory,以在交互之间维护状态。这让代理能够记住先前对话和上下文。
import { MemorySaver } from "@langchain/langgraph";

const checkpointer = new MemorySaver();
在生产环境中,请使用将消息历史保存到数据库的持久 checkpointer。 更多详情请参阅 Add and manage memory
5

创建并运行代理

现在用所有组件组装你的代理并运行它。创建代理有两个不同框架:LangChain agents 和 deep agents。 LangChain 和 deep agents 都为工具、memory 等提供细粒度控制。 二者主要区别是 deep agents 已内置一系列常用能力,例如规划、文件系统工具和 subagents。当你想用最少设置获得最大能力时使用 deep agents;当你需要细粒度控制时选择 LangChain agents。
由于代码会使用 The Great Gatsby 全文调用模型,因此会消耗大量 tokens。可以在下一步查看示例输出。
两者都试一下:
async function main() {
    const agent = createAgent({
        model,
        tools: [fetchTextFromUrl],
        systemPrompt: SYSTEM_PROMPT,
        checkpointer,
    });

    const deepAgent = createDeepAgent({
        model,
        tools: [fetchTextFromUrl],
        systemPrompt: SYSTEM_PROMPT,
        checkpointer,
    });

    const content = `Project Gutenberg hosts a full plain-text copy of F. Scott Fitzgerald's The Great Gatsby.
    URL: https://www.gutenberg.org/files/64317/64317-0.txt

    Answer as much as you can:

    1) How many lines in the complete Gutenberg file contain the substring \`Gatsby\` (count lines, not occurrences within a line, each line ends with a line break).
    2) The 1-based line number of the first line in the file that contains \`Daisy\`.
    3) A two-sentence neutral synopsis.

    Do your best on (1) and (2). If at any point you realize you cannot **verify** an exact answer with
    your available tools and reasoning, do not fabricate numbers: use \`null\` for that field and spell out
    the limitation in \`how_you_computed_counts\`. If you encounter any errors please report what the error was and what the error message was.`;

    const agentResult = await agent.invoke(
        { messages: [{ role: "user", content }] },
        { configurable: { thread_id: "great-gatsby-lc" } },
    );
    const deepAgentResult = await deepAgent.invoke(
        { messages: [{ role: "user", content }] },
        { configurable: { thread_id: "great-gatsby-da" } },
    );

    const agentMessages = agentResult.messages;
    const deepMessages = deepAgentResult.messages;
    console.log(agentMessages[agentMessages.length - 1]!.content_blocks);
    console.log("\n");
    console.log(deepMessages[deepMessages.length - 1]!.content_blocks);
}

main().catch((err) => {
    console.error(err);
    process.exitCode = 1;
});
6

查看结果

结果会根据模型和执行情况而有所不同。
**1) Number of lines containing `Gatsby`:** `null`

**2) First line containing `Daisy`:** `null`

**3) Synopsis:**
The Great Gatsby follows the mysterious millionaire Jay Gatsby and his obsession with reuniting with his former lover, Daisy Buchanan, as narrated by his neighbor Nick Carraway. Set against the backdrop of the Roaring Twenties on Long Island, the novel explores themes of wealth, class, and the elusive nature of the American Dream.

**how_you_computed_counts:**
I successfully fetched the full text of the eBook using the `fetch_text_from_url` tool. However, because I do not have access to a code execution environment (like Python) or text-processing tools (like `grep`), I cannot deterministically split the text by line breaks, iterate through the thousands of lines, and verify the exact line numbers or match counts. LLMs cannot reliably perform exact line-counting or indexing over massive texts within their context window without external computational tools. As instructed, rather than fabricating or guessing a number, I have output `null` for the exact counts and positions.
如果查看两个标签页中的输出,会发现 LangChain agent 提供了答案,但这些答案是估计值。该代理缺少回答此问题所需的工具。你也可能遇到 prompt 过长的错误。另一方面,deep agent 可以:
  1. 使用内置 write_todos 工具规划方法,分解研究任务。
  2. 调用 fetch_text_from_url 工具加载文件以收集信息。
  3. 使用文件系统工具(grepread_file管理上下文
  4. 按需生成 subagents,将复杂子任务委派给专门的 subagents。
对于 LangChain agents,你必须实现更多能力才能获得类似服务水平,并且可以在过程中按需自定义。

跟踪代理调用

你使用 LangChain 构建的大多数有趣应用都会多次调用 LLM。随着这些应用变得更复杂,能够检查代理内部究竟发生了什么会变得很重要。最好的方式是使用 LangSmith 注册 LangSmith 账户,并设置这些环境变量以开始记录 traces:
export LANGSMITH_TRACING="true"
export LANGSMITH_API_KEY="..."
设置完成后,再次运行脚本,然后在 LangSmith 上检查代理调用期间发生的事情。
要进一步了解如何使用 LangSmith 跟踪代理,请参阅 LangSmith documentation还建议设置 LangSmith Engine,它会监控 traces、检测问题并提出修复建议。

下一步

现在你的代理可以:
  • 理解上下文并记住对话
  • 智能使用工具
  • 以一致格式提供结构化响应
  • 通过 context 处理用户特定信息
  • 跨交互维护对话状态
  • 规划、研究并综合信息(仅 deep agents)
继续阅读: