快速入门
在数分钟内构建你的首个 Agent
本快速入门将向你展示如何在短短数分钟内创建一个功能完备的 AI Agent。
构建 LangChain 快速入门 Agent
按照 LangChain 快速入门,在此工作目录中构建一个基础的 LangChain Agent。
步骤 1:阅读指南
检测此项目使用的是 Python 还是 TypeScript/JavaScript。获取并遵循匹配的页面;将其作为包名、模型字符串和代码的权威来源:
- Python: https://docs.langchain.com/oss/python/langchain/quickstart.md
- TypeScript: https://docs.langchain.com/oss/javascript/langchain/quickstart.md
步骤 2:安装依赖
使用本项目中已使用的包管理器(uv、pip、npm、pnpm、yarn 或 bun)安装指南中的软件包。如果项目已经固定了版本,建议固定当前的稳定版本,而不是使用浮动的 latest 标签。
步骤 3:配置模型凭证
检查是否已设置受支持提供商的 API 密钥(例如 OPENAI_API_KEY、GOOGLE_API_KEY 或 ANTHROPIC_API_KEY)。如果均未设置,请询问用户要使用哪家提供商,然后暂停并等待他们在 Shell 或 .env 文件中创建并设置密钥。切勿捏造、硬编码或提交 API 密钥。
步骤 4:实现基础 Agent
根据指南创建“构建基础 Agent”示例:create_agent、一个简单的工具(如 get_weather)、简短的系统提示词以及 invoke 调用。使用用户所选提供商的模型字符串。打印最终的消息内容(Python: .content_blocks),以便用户验证运行结果。
步骤 5:可选的 LangSmith 追踪
询问用户是否需要追踪。如果需要,请让他们自行设置 LANGSMITH_TRACING=true 和 LANGSMITH_API_KEY,然后重新运行。切勿捏造 LangSmith 密钥。
规则
- 仅限于本快速入门的范围。切勿添加无关的框架、评测或生产部署。
- 优先使用指南中所示来自
langchain.agents/langchain的create_agent。 - 当凭证、提供商选择或项目规范不明确时,请主动询问而不是自行猜测。
TIP
正在使用 AI 编程助手?
安装 LangChain 文档 MCP 服务器,让你的 Agent 能够访问最新的 LangChain 文档和示例。
连接 LangChain 文档 MCP 服务器
将两个 LangChain 文档 MCP 服务器连接到我的编程 Agent,使其可以查阅最新的 LangChain、LangGraph 和 LangSmith 文档及 API 参考。
要添加的服务器:
docs-langchain: https://docs.langchain.com/mcpreference-langchain: https://reference.langchain.com/mcp
检测我正在使用的 Agent 或编辑器(Claude Code、Cursor、Codex CLI、Claude Desktop、Deep Agents Code、VS Code、Antigravity 或其他兼容 MCP 的客户端)。使用 https://docs.langchain.com/use-these-docs.md 中对应的配置:
- Claude Code:为每个服务器运行
claude mcp add --transport http(默认项目范围;仅在要求全局访问时使用--scope user)。 - Codex CLI:使用每个服务器的 URL 运行
codex mcp add。 - Cursor、Deep Agents Code、VS Code 或 Antigravity:使用该页面中为你客户端展示的字段名,将这两个条目合并到 MCP 设置 JSON 中。
- Claude Desktop:在 Settings > Connectors 下添加这两个 URL。
切勿自行捏造替代的 MCP URL。配置完成后,确认两个服务器均已列出且可访问。
安装 LangChain Skills 以提升你的 Agent 在 LangChain 生态系统任务中的表现。
安装 LangChain Skills
为我的编程 Agent 安装 LangChain Skills,使其在 LangChain、LangGraph 和 Deep Agents 任务中表现更佳。
使用来自 https://github.com/langchain-ai/langchain-skills 的 Agent Skills 安装程序:
bashnpx skills add langchain-ai/langchain-skills --skill '*' --yes如果我要求全局安装,请改用:
bashnpx skills add langchain-ai/langchain-skills --skill '*' --yes --global检测我正在使用的 Agent 或编辑器。如果我使用 Claude Code 且更倾向于插件途径,请按照该仓库 README 中的市场安装步骤进行操作(依次运行
/plugin marketplace add和/plugin install)。切勿自行捏造替代的技能包名称或安装 URL。安装完成后,确认这些技能对 Agent 可用。
安装依赖
安装以下软件包以跟随本指南进行操作:
npm install langchain @langchain/core
# 需要 Node.js 22+pnpm add langchain @langchain/core
# 需要 Node.js 22+yarn add langchain @langchain/core
# 需要 Node.js 22+bun add langchain @langchain/core
# 需要 Bun v1.0.0+设置 API 密钥
从任何受支持的模型提供商(例如 Google Gemini 或 OpenAI)获取 API 密钥。
在你的 Shell 或 .env 文件中设置 API 密钥,例如:
OpenAI
export OPENAI_API_KEY="your-api-key"OPENAI_API_KEY=your-api-keyGoogle Gemini
export GOOGLE_API_KEY="your-api-key"GOOGLE_API_KEY=your-api-keyClaude (Anthropic)
export ANTHROPIC_API_KEY="your-api-key"ANTHROPIC_API_KEY=your-api-keyOpenRouter
export OPENROUTER_API_KEY="your-api-key"OPENROUTER_API_KEY=your-api-keyFireworks
export FIREWORKS_API_KEY="your-api-key"FIREWORKS_API_KEY=your-api-keyBaseten
export BASETEN_API_KEY="your-api-key"BASETEN_API_KEY=your-api-keyOllama
# 本地:Ollama 必须处于运行状态 (https://ollama.com)
# 云端:为托管推理设置你的 Ollama API 密钥
export OLLAMA_API_KEY="your-api-key"# 本地:Ollama 必须处于运行状态 (https://ollama.com)
# 云端:为托管推理设置你的 Ollama API 密钥
OLLAMA_API_KEY=your-api-keyAzure
export AZURE_OPENAI_API_KEY="your-api-key"
export AZURE_OPENAI_ENDPOINT="https://your-resource.openai.azure.com"
export AZURE_OPENAI_DEPLOYMENT_NAME="your-deployment"AZURE_OPENAI_API_KEY=your-api-key
AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com
AZURE_OPENAI_DEPLOYMENT_NAME=your-deploymentAWS Bedrock
export AWS_ACCESS_KEY_ID="your-access-key"
export AWS_SECRET_ACCESS_KEY="your-secret-key"
export AWS_REGION="us-east-1"AWS_ACCESS_KEY_ID=your-access-key
AWS_SECRET_ACCESS_KEY=your-secret-key
AWS_REGION=us-east-1HuggingFace
export HUGGINGFACEHUB_API_TOKEN="hf_..."HUGGINGFACEHUB_API_TOKEN=hf_...其他
查看受支持的聊天模型集成完整列表。
要加载 .env 文件,请使用 dotenv(import "dotenv/config")。
TIP
使用 LangSmith Gateway
LangSmith Gateway 将大多数主流提供商路由至 LangSmith。你可以自带提供商密钥,或使用 Gateway 积分在没有提供商密钥的情况下访问模型。
构建基础 Agent
首先创建一个能够回答问题并调用工具的简单 Agent。本示例中的 Agent 使用所选的语言模型、一个作为工具的基础天气函数,以及一个用于指导其行为的简单提示词:
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.5",
tools: [getWeather],
});
console.log(
await agent.invoke({
messages: [{ role: "user", content: "What's the weather in San Francisco?" }],
})
);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: "google:gemini-2.5-flash-lite",
tools: [getWeather],
});
console.log(
await agent.invoke({
messages: [{ role: "user", content: "What's the weather in San Francisco?" }],
})
);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 San Francisco?" }],
})
);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: "openrouter:anthropic/claude-sonnet-4-6",
tools: [getWeather],
});
console.log(
await agent.invoke({
messages: [{ role: "user", content: "What's the weather in San Francisco?" }],
})
);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: "fireworks:accounts/fireworks/models/qwen3p5-397b-a17b",
tools: [getWeather],
});
console.log(
await agent.invoke({
messages: [{ role: "user", content: "What's the weather in San Francisco?" }],
})
);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: "baseten:zai-org/GLM-5.2",
tools: [getWeather],
});
console.log(
await agent.invoke({
messages: [{ role: "user", content: "What's the weather in San Francisco?" }],
})
);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: "ollama:devstral-2",
tools: [getWeather],
});
console.log(
await agent.invoke({
messages: [{ role: "user", content: "What's the weather in San Francisco?" }],
})
);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: "azure_openai:gpt-5.5",
tools: [getWeather],
});
console.log(
await agent.invoke({
messages: [{ role: "user", content: "What's the weather in San Francisco?" }],
})
);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: "bedrock:gpt-5.5",
tools: [getWeather],
});
console.log(
await agent.invoke({
messages: [{ role: "user", content: "What's the weather in San Francisco?" }],
})
);当你运行代码并提示 Agent 告诉你旧金山(San Francisco)的天气时,Agent 会利用该输入及其可用上下文。 Agent 理解你正在询问旧金山市的天气,因此会使用所提供的城市名称调用天气工具。
TIP
你可以通过更改模型名称并设置相应的 API 密钥来使用任何受支持的模型。使用 LangSmith 追踪 Agent 内部发生的情况。遵循追踪快速入门进行设置。
我们建议你同时设置 LangSmith Engine,它可以监控你的追踪记录、检测问题并提出修复建议。
构建真实世界的 Agent
在以下示例中,你将构建一个能够回答有关文本文件问题的研究型 Agent。 在此过程中,你将探索以下概念:
- 详细的系统提示词,以改善 Agent 行为
- 创建工具,与外部数据进行集成
- 模型配置,以获得一致的响应
- 对话记忆,用于类聊天式的交互
- Deep Agents,用于内置功能
- 测试你的 Agent
1. 定义系统提示词
系统提示词定义了 Agent 的角色与行为。请保持具体且具备可操作性:
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. 创建工具
工具允许模型通过调用你定义的函数来与外部系统交互。 工具可以依赖运行时上下文,也可以与 Agent 记忆进行交互。
本示例使用一个从指定 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() }),
},
);NOTE
Zod 是一个用于验证和解析预定义模式(schema)的库。你可以用它来定义工具的输入模式,以确保 Agent 仅使用正确的参数调用工具。
或者,你也可以将 schema 属性定义为 JSON schema 对象。请注意,JSON schema 不会在运行时进行验证。
示例:将 JSON schema 用于工具输入
tsimport { 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. 配置你的模型
使用适合你使用场景的正确参数设置你的语言模型。例如:
import { initChatModel } from "langchain";
const model = await initChatModel("gpt-5.5", {
temperature: 0.5,
timeout: 300,
maxTokens: 25000,
});import { initChatModel } from "langchain";
const model = await initChatModel("gemini-3.1-pro-preview", {
modelProvider: "google",
temperature: 0.5,
timeout: 600_000,
maxTokens: 25000,
});import { initChatModel } from "langchain";
const model = await initChatModel("claude-sonnet-4-6", {
temperature: 0.5,
timeout: 300,
maxTokens: 25000,
});import { initChatModel } from "langchain";
const model = await initChatModel("openrouter:anthropic/claude-sonnet-4-6", {
temperature: 0.5,
timeout: 300,
maxTokens: 25000,
});import { initChatModel } from "langchain";
const model = await initChatModel(
"fireworks:accounts/fireworks/models/qwen3p5-397b-a17b",
{ temperature: 0.5, timeout: 300, maxTokens: 25000 }
);import { initChatModel } from "langchain";
const model = await initChatModel("baseten:zai-org/GLM-5.2", {
temperature: 0.5,
timeout: 300,
maxTokens: 25000,
});import { initChatModel } from "langchain";
const model = await initChatModel("ollama:devstral-2", {
temperature: 0.5,
timeout: 300,
maxTokens: 25000,
});import { initChatModel } from "langchain";
const model = await initChatModel("azure_openai:gpt-5.5", {
temperature: 0.5,
timeout: 300,
maxTokens: 25000,
});import { initChatModel } from "langchain";
const model = await initChatModel("bedrock:gpt-5.5", {
temperature: 0.5,
timeout: 300,
maxTokens: 25000,
});根据所选的模型和提供商,初始化参数可能会有所不同;有关详细信息,请参阅它们的参考页面。
4. 添加记忆
为你的 Agent 添加记忆以跨交互维护状态。这允许 Agent 记住先前的对话和上下文。
import { MemorySaver } from "@langchain/langgraph";
const checkpointer = new MemorySaver();NOTE
在生产环境中,请使用将消息历史保存到数据库的持久化检查点(checkpointer)。 有关更多详细信息,请参阅添加与管理记忆。
5. 创建并运行 Agent
现在将所有组件组装到你的 Agent 中并运行它。
创建 Agent 有两种不同的框架:LangChain agents 和 deep agents。 LangChain 和 deep agents 都能让你对工具、记忆等进行细粒度控制。 两者之间的主要区别在于,deep agents 已经内置了一系列常用的实用功能,例如规划、文件系统工具和子 Agent。
当你希望以最少的配置获得最强大的能力时,请使用 deep agents;当你需要细粒度控制时,请选择 LangChain agents。
为了在此步骤中对比两者,请安装 deepagents 软件包:
npm install deepagentspnpm add deepagentsyarn add deepagentsbun add deepagentsWARNING
此示例将《了不起的盖茨比》(The Great Gatsby)的全文发送给模型,可能需要一到两分钟才能得到响应。你可以在下一步中查看示例输出。
让我们尝试这两种方式:
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.`;
console.log("Running createAgent...");
const agentResult = await agent.invoke(
{ messages: [{ role: "user", content }] },
{ configurable: { thread_id: "great-gatsby-lc" } },
);
console.log("Running createDeepAgent...");
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("\ncreateAgent:");
console.log(agentMessages[agentMessages.length - 1]!.contentBlocks);
console.log("\ncreateDeepAgent:");
console.log(deepMessages[deepMessages.length - 1]!.contentBlocks);
}
main().catch((err) => {
console.error(err);
process.exitCode = 1;
});下面的展开折叠块包含了一个完整可运行脚本的所有内容:
完整示例代码
import { MemorySaver } from "@langchain/langgraph";
import { createDeepAgent } from "deepagents";
import { tool } from "@langchain/core/tools";
import { createAgent, initChatModel } from "langchain";
import { z } from "zod";
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.`;
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() }),
},
);
const model = await initChatModel("gemini-3.1-pro-preview", {
modelProvider: "google",
temperature: 0.5,
timeout: 600_000,
maxTokens: 25000,
streaming: true,
});
const checkpointer = new MemorySaver();
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.`;
console.log("Running createAgent...");
const agentResult = await agent.invoke(
{ messages: [{ role: "user", content }] },
{ configurable: { thread_id: "great-gatsby-lc" } },
);
console.log("Running createDeepAgent...");
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("\ncreateAgent:");
console.log(agentMessages[agentMessages.length - 1]!.contentBlocks);
console.log("\ncreateDeepAgent:");
console.log(deepMessages[deepMessages.length - 1]!.contentBlocks);
}
main().catch((err) => {
console.error(err);
process.exitCode = 1;
});6. 查看结果
结果会因模型和执行过程的不同而有所差异。
LangChain agents
**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.Deep agents
Based on the text fetched directly from the Gutenberg URL and analyzed using filesystem search tools, here are the answers to your questions:
**1) Lines containing the substring `Gatsby`**
**258** lines contain the exact substring `Gatsby`.
**2) First line containing `Daisy`**
Line **181** is the first line in the file that contains the exact substring `Daisy`.
*(For context, the line reads: "Buchanans. Daisy was my second cousin once removed, and I’d known Tom")*
**3) Two-sentence neutral synopsis**
*The Great Gatsby* follows the mysterious millionaire Jay Gatsby and his obsessive pursuit to reunite with his former lover, Daisy Buchanan, in 1920s Long Island. The story is narrated by Nick Carraway, who observes the tragic consequences of Gatsby's relentless ambition and the shallow materialism of the era's wealthy elite.
***
**How counts were computed:**
When fetching the document from the URL, the file was too large for the standard output and was automatically saved to the local filesystem by the system (`/large_tool_results/x246ax2x`). I then used the `grep` tool to search the saved file for the exact literal substrings `Gatsby` and `Daisy`. The `grep` tool returned every matching line along with its 1-based line number. I manually counted the exact number of lines returned for `Gatsby` (which totaled 258) and identified the first line number returned for `Daisy` (which was 181). I also verified there were no uppercase variations (`GATSBY` or `DAISY`) that would have been missed. No errors were encountered during this process.如果你查看这两个标签页上的输出,会发现 LangChain agent 给出了答案,但它们属于估算。Agent 缺少回答该问题所需的工具。你还可能会收到提示词过长的错误。
另一方面,deep agent 能够:
- 规划其方法:使用内置的
write_todos工具拆解研究任务。 - 加载文件:通过调用
fetch_text_from_url工具来收集信息。 - 管理上下文:使用文件系统工具(
grep和read_file)。 - 派生子 Agent:根据需要将复杂的子任务委托给专门的子 Agent。
对于 LangChain agents,你必须自行实现更多功能才能获得类似水准的服务,并可根据需要随时进行定制。
追踪 Agent 调用
使用 LangChain 构建的大多数有趣应用都会对 LLM 进行多次调用。随着这些应用变得更加复杂,能够检查 Agent 内部具体发生了什么是至关重要的。实现这一目标的最佳方式是使用 LangSmith。
注册 LangSmith 账号并设置以下环境变量以开始记录追踪:
export LANGSMITH_TRACING="true"
export LANGSMITH_API_KEY="..."设置完成后,再次运行你的脚本,然后在 LangSmith 上检查 Agent 调用期间发生了什么。
TIP
要了解有关使用 LangSmith 追踪 Agent 的更多信息,请参阅 LangSmith 文档。
我们建议你同时设置 LangSmith Engine,它可以监控你的追踪记录、检测问题并提出修复建议。
后续步骤
你现在拥有的 Agent 能够:
- 理解上下文并记住对话
- 智能地使用工具
- 以一致的格式提供结构化响应
- 通过上下文处理用户特定信息
- 跨交互维护对话状态
- 规划、研究与综合分析(仅限 deep agents)
继续探索:
