外观
本快速入门将向您展示如何在短短几分钟内创建一个功能齐全的 AI 智能体。
TIP
正在使用 AI 编程助手?
- 安装 LangChain 文档 MCP 服务器,让你的智能体能够访问最新的 LangChain 文档和示例。
- 安装 LangChain Skills,以提高你的智能体在 LangChain 生态任务上的表现。
安装依赖
安装以下包以继续操作:
bash
uv init
uv add langchain deepagents
uv syncbash
pip install -U langchain deepagentsbash
python3 -m venv .venv
source .venv/bin/activate
# Windows 下:.venv\Scripts\activate
pip install -U langchain deepagentsbash
npm install deepagents langchain @langchain/core
# 需要 Node.js 22+bash
pnpm add deepagents langchain @langchain/core
# 需要 Node.js 22+bash
yarn add deepagents langchain @langchain/core
# 需要 Node.js 22+bash
bun add deepagents langchain @langchain/core
# 需要 Bun v1.0.0+设置 API 密钥
从任一支持的模型提供商获取 API 密钥(例如 Google Gemini 或 OpenAI)。
设置 API 密钥,例如:
OpenAI
bash
export OPENAI_API_KEY="your-api-key"Google Gemini
bash
export GOOGLE_API_KEY="your-api-key"Claude (Anthropic)
bash
export ANTHROPIC_API_KEY="your-api-key"OpenRouter
bash
export OPENROUTER_API_KEY="your-api-key"Fireworks
bash
export FIREWORKS_API_KEY="your-api-key"Baseten
bash
export BASETEN_API_KEY="your-api-key"Ollama
bash
# 本地:Ollama 必须正在运行(https://ollama.com)
# 云端:为托管推理设置你的 Ollama API 密钥
export OLLAMA_API_KEY="your-api-key"Azure
bash
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"AWS Bedrock
bash
export AWS_ACCESS_KEY_ID="your-access-key"
export AWS_SECRET_ACCESS_KEY="your-secret-key"
export AWS_REGION="us-east-1"HuggingFace
bash
export HUGGINGFACEHUB_API_TOKEN="hf_..."其他
查看受支持的[对话模型集成](/oss/integrations/chat)的完整列表。
TIP
使用 LangSmith Gateway
LangSmith Gateway 可通过 LangSmith 路由大多数主流提供商。你可以自带提供商密钥,或使用 Gateway 积分在无需提供商密钥的情况下访问模型。
构建基础智能体
首先创建一个简单的智能体,它可以回答问题并调用工具。本示例中的智能体使用所选的语言模型、一个基础天气函数作为工具,以及一个简单的提示词来引导其行为:
python
from langchain.agents import create_agent
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
agent = create_agent(
model="openai:gpt-5.5",
tools=[get_weather],
system_prompt="You are a helpful assistant",
)
result = agent.invoke(
{"messages": [{"role": "user", "content": "What's the weather in San Francisco?"}]}
)
print(result["messages"][-1].content_blocks)python
from langchain.agents import create_agent
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
agent = create_agent(
model="google_genai:gemini-2.5-flash-lite",
tools=[get_weather],
system_prompt="You are a helpful assistant",
)
result = agent.invoke(
{"messages": [{"role": "user", "content": "What's the weather in San Francisco?"}]}
)
print(result["messages"][-1].content_blocks)python
from langchain.agents import create_agent
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
agent = create_agent(
model="claude-sonnet-4-6",
tools=[get_weather],
system_prompt="You are a helpful assistant",
)
result = agent.invoke(
{"messages": [{"role": "user", "content": "What's the weather in San Francisco?"}]}
)
print(result["messages"][-1].content_blocks)python
from langchain.agents import create_agent
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
agent = create_agent(
model="openrouter:anthropic/claude-sonnet-4-6",
tools=[get_weather],
system_prompt="You are a helpful assistant",
)
result = agent.invoke(
{"messages": [{"role": "user", "content": "What's the weather in San Francisco?"}]}
)
print(result["messages"][-1].content_blocks)python
from langchain.agents import create_agent
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
agent = create_agent(
model="fireworks:accounts/fireworks/models/qwen3p5-397b-a17b",
tools=[get_weather],
system_prompt="You are a helpful assistant",
)
result = agent.invoke(
{"messages": [{"role": "user", "content": "What's the weather in San Francisco?"}]}
)
print(result["messages"][-1].content_blocks)python
from langchain.agents import create_agent
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
agent = create_agent(
model="baseten:zai-org/GLM-5.2",
tools=[get_weather],
system_prompt="You are a helpful assistant",
)
result = agent.invoke(
{"messages": [{"role": "user", "content": "What's the weather in San Francisco?"}]}
)
print(result["messages"][-1].content_blocks)python
from langchain.agents import create_agent
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
agent = create_agent(
model="ollama:devstral-2",
tools=[get_weather],
system_prompt="You are a helpful assistant",
)
result = agent.invoke(
{"messages": [{"role": "user", "content": "What's the weather in San Francisco?"}]}
)
print(result["messages"][-1].content_blocks)python
import os
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
model = init_chat_model(
"azure_openai:gpt-5.5",
azure_deployment=os.environ["AZURE_OPENAI_DEPLOYMENT_NAME"],
)
agent = create_agent(
model=model,
tools=[get_weather],
system_prompt="You are a helpful assistant",
)
result = agent.invoke(
{"messages": [{"role": "user", "content": "What's the weather in San Francisco?"}]}
)
print(result["messages"][-1].content_blocks)python
from langchain.agents import create_agent
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
agent = create_agent(
model="bedrock_converse:us.anthropic.claude-sonnet-4-6",
tools=[get_weather],
system_prompt="You are a helpful assistant",
)
result = agent.invoke(
{"messages": [{"role": "user", "content": "What's the weather in San Francisco?"}]}
)
print(result["messages"][-1].content_blocks)python
from langchain.agents import create_agent
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
agent = create_agent(
model="huggingface:microsoft/Phi-3-mini-4k-instruct",
tools=[get_weather],
system_prompt="You are a helpful assistant",
)
result = agent.invoke(
{"messages": [{"role": "user", "content": "What's the weather in San Francisco?"}]}
)
print(result["messages"][-1].content_blocks)ts
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?" }],
})
);ts
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-genai:gemini-2.5-flash-lite",
tools: [getWeather],
});
console.log(
await agent.invoke({
messages: [{ role: "user", content: "What's the weather in San Francisco?" }],
})
);ts
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?" }],
})
);ts
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?" }],
})
);ts
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?" }],
})
);ts
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?" }],
})
);ts
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?" }],
})
);ts
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?" }],
})
);ts
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?" }],
})
);当你运行代码并提示智能体告诉你旧金山的天气时,智能体会利用该输入及其可用的上下文。 智能体理解你是在询问旧金山这座城市的天气,因此会使用提供的城市名调用天气工具。
TIP
你可以通过更改模型名称并设置相应的 API 密钥来使用任何受支持的模型。使用 LangSmith 追踪智能体内部发生的情况。按照追踪快速入门进行设置。
我们还建议你设置 LangSmith Engine,它可以监控你的追踪、检测问题并提出修复方案。
构建真实世界的智能体
在下面的示例中,你将构建一个能够回答关于文本文件问题的研究型智能体。 在此过程中你将探索以下概念:
- 详细的系统提示词,以获得更好的智能体行为
- 创建工具,与外部数据集成
- 模型配置,以获得一致的响应
- 对话记忆,实现类聊天式交互
- Deep Agents,获取内置功能
- 测试你的智能体
定义系统提示词
系统提示词定义了智能体的角色和行为。让它保持具体且可执行:
python
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."""ts
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.`;创建工具
[工具](/oss/langchain/tools) 让模型可以通过调用你定义的函数与外部系统交互。
工具可以依赖[运行时上下文](/oss/langchain/runtime),也可以与[智能体记忆](/oss/langchain/short-term-memory)交互。
本示例使用一个工具从给定 URL 加载文档:
python
import urllib.error
import urllib.request
from langchain.tools import tool
@tool
def fetch_text_from_url(url: str) -> str:
"""Fetch the document from a URL.
"""
req = urllib.request.Request(
url,
headers={"User-Agent": "Mozilla/5.0 (compatible; quickstart-research/1.0)"},
)
try:
with urllib.request.urlopen(req, timeout=120) as resp:
raw = resp.read()
except urllib.error.URLError as e:
return f"Fetch failed: {e}"
text = raw.decode("utf-8", errors="replace")
return textTIP
工具应该有完善的文档说明:它们的名称、描述和参数名会成为模型提示词的一部分。 LangChain 的 @tool 装饰器 会添加元数据,并通过 ToolRuntime 参数启用运行时注入。 在工具指南中了解更多。
ts
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() }),
},
);INFO
Zod 是一个用于验证和解析预定义 schema 的库。你可以用它来定义工具输入 schema,确保智能体只以正确的参数调用工具。
或者,你也可以将 schema 属性定义为一个 JSON schema 对象。请注意,JSON schema 不会在运行时被验证。
示例:为工具输入使用 JSON schema
ts
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"],
},
},
);配置你的模型
使用适合你的用例的参数设置你的[语言模型](/oss/langchain/models)。例如:
python
from langchain.chat_models import init_chat_model
model = init_chat_model(
"openai:gpt-5.5",
temperature=0.5,
timeout=300,
max_tokens=25000,
)python
from langchain.chat_models import init_chat_model
model = init_chat_model(
"gemini-3.1-pro-preview",
model_provider="google-genai",
temperature=0.5,
timeout=600,
max_tokens=25000,
streaming=True,
)python
from langchain.chat_models import init_chat_model
model = init_chat_model(
"claude-sonnet-4-6",
temperature=0.5,
timeout=600,
max_tokens=25000,
streaming=True,
)python
from langchain.chat_models import init_chat_model
model = init_chat_model(
"openrouter:anthropic/claude-sonnet-4-6",
temperature=0.5,
timeout=300,
max_tokens=25000,
)python
from langchain.chat_models import init_chat_model
model = init_chat_model(
"fireworks:accounts/fireworks/models/qwen3p5-397b-a17b",
temperature=0.5,
timeout=300,
max_tokens=25000,
)python
from langchain.chat_models import init_chat_model
model = init_chat_model(
"baseten:zai-org/GLM-5.2",
temperature=0.5,
timeout=300,
max_tokens=25000,
)python
from langchain.chat_models import init_chat_model
model = init_chat_model(
"ollama:devstral-2",
temperature=0.5,
timeout=300,
max_tokens=25000,
)python
import os
from langchain.chat_models import init_chat_model
model = init_chat_model(
"azure_openai:gpt-5.5",
temperature=0.5,
timeout=300,
max_tokens=25000,
azure_deployment=os.environ["AZURE_OPENAI_DEPLOYMENT_NAME"],
)python
from langchain.chat_models import init_chat_model
model = init_chat_model(
"us.anthropic.claude-sonnet-4-6",
model_provider="bedrock_converse",
temperature=0.5,
timeout=300,
max_tokens=25000,
)python
from langchain.chat_models import init_chat_model
model = init_chat_model(
"microsoft/Phi-3-mini-4k-instruct",
model_provider="huggingface",
temperature=0.5,
timeout=300,
max_tokens=25000,
)ts
import { initChatModel } from "langchain";
const model = await initChatModel("gpt-5.5", {
temperature: 0.5,
timeout: 300,
maxTokens: 25000,
});ts
import { initChatModel } from "langchain";
const model = await initChatModel("gemini-3.1-pro-preview", {
modelProvider: "google-genai",
temperature: 0.5,
timeout: 600_000,
maxTokens: 25000,
});ts
import { initChatModel } from "langchain";
const model = await initChatModel("claude-sonnet-4-6", {
temperature: 0.5,
timeout: 300,
maxTokens: 25000,
});ts
import { initChatModel } from "langchain";
const model = await initChatModel("openrouter:anthropic/claude-sonnet-4-6", {
temperature: 0.5,
timeout: 300,
maxTokens: 25000,
});ts
import { initChatModel } from "langchain";
const model = await initChatModel(
"fireworks:accounts/fireworks/models/qwen3p5-397b-a17b",
{ temperature: 0.5, timeout: 300, maxTokens: 25000 }
);ts
import { initChatModel } from "langchain";
const model = await initChatModel("baseten:zai-org/GLM-5.2", {
temperature: 0.5,
timeout: 300,
maxTokens: 25000,
});ts
import { initChatModel } from "langchain";
const model = await initChatModel("ollama:devstral-2", {
temperature: 0.5,
timeout: 300,
maxTokens: 25000,
});ts
import { initChatModel } from "langchain";
const model = await initChatModel("azure_openai:gpt-5.5", {
temperature: 0.5,
timeout: 300,
maxTokens: 25000,
});ts
import { initChatModel } from "langchain";
const model = await initChatModel("bedrock:gpt-5.5", {
temperature: 0.5,
timeout: 300,
maxTokens: 25000,
}); 根据所选模型和提供商的不同,初始化参数可能有所差异;详情请参阅它们的参考页面。
添加记忆
为你的智能体添加[记忆](/oss/langchain/short-term-memory),以在多次交互之间保持状态。这可以让
智能体记住之前的对话和上下文。
python
from langgraph.checkpoint.memory import InMemorySaver
checkpointer = InMemorySaver()ts
import { MemorySaver } from "@langchain/langgraph";
const checkpointer = new MemorySaver();INFO
在生产环境中,请使用一个将消息历史保存到数据库的持久化检查点。 更多详情请参阅添加和管理记忆。
创建并运行智能体
现在将所有组件组合起来创建你的智能体并运行它。
创建智能体有两种不同的框架:LangChain 智能体和深度智能体。
两者都为你提供对工具、记忆等内容的细粒度控制。
二者之间的主要区别在于,深度智能体自带一系列常用的现成能力,例如规划、文件系统工具和子智能体。
当你希望以最少的设置获得最大的能力时,请使用深度智能体;当你需要细粒度控制时,请选择 LangChain 智能体。
WARNING
由于代码会将《了不起的盖茨比》的全文传给模型,因此会消耗大量 token。
你可以在下一步查看示例输出。
让我们两种都试一试:
python
from langchain.agents import create_agent
from deepagents import create_deep_agent
agent = create_agent(
model=model,
tools=[fetch_text_from_url],
system_prompt=SYSTEM_PROMPT,
checkpointer=checkpointer,
)
deep_agent = create_deep_agent(
model=model,
tools=[fetch_text_from_url],
system_prompt=SYSTEM_PROMPT,
checkpointer=checkpointer,
)
content = f"""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."""
agent_result = agent.invoke(
{"messages": [{"role": "user", "content": content}]},
config={"configurable": {"thread_id": "great-gatsby-lc"}},
)
deep_agent_result = deep_agent.invoke(
{"messages": [{"role": "user", "content": content}]},
config={"configurable": {"thread_id": "great-gatsby-da"}},
)
print(agent_result["messages"][-1].content_blocks)
print("\n")
print(deep_agent_result["messages"][-1].content_blocks)ts
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;
});python
import urllib.error
import urllib.request
from langchain.agents import create_agent
from deepagents import create_deep_agent
from langchain.chat_models import init_chat_model
from langchain.tools import tool
from langgraph.checkpoint.memory import InMemorySaver
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."""
@tool
def fetch_text_from_url(url: str) -> str:
"""Fetch the document from a URL.
"""
req = urllib.request.Request(
url,
headers={"User-Agent": "Mozilla/5.0 (compatible; quickstart-research/1.0)"},
)
try:
with urllib.request.urlopen(req, timeout=120) as resp:
raw = resp.read()
except urllib.error.URLError as e:
return f"Fetch failed: {e}"
text = raw.decode("utf-8", errors="replace")
return text
model = init_chat_model(
"gemini-3.1-pro-preview",
model_provider="google-genai",
temperature=0.5,
timeout=600,
max_tokens=25000,
streaming=True,
)
checkpointer = InMemorySaver()
agent = create_agent(
model=model,
tools=[fetch_text_from_url],
system_prompt=SYSTEM_PROMPT,
checkpointer=checkpointer,
)
deep_agent = create_deep_agent(
model=model,
tools=[fetch_text_from_url],
system_prompt=SYSTEM_PROMPT,
checkpointer=checkpointer,
)
content = f"""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."""
agent_result = agent.invoke(
{"messages": [{"role": "user", "content": content}]},
config={"configurable": {"thread_id": "great-gatsby-lc"}},
)
deep_agent_result = deep_agent.invoke(
{"messages": [{"role": "user", "content": content}]},
config={"configurable": {"thread_id": "great-gatsby-da"}},
)
print(agent_result["messages"][-1].content_blocks)
print("\n")
print(deep_agent_result["messages"][-1].content_blocks)ts
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-genai",
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.`;
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;
});查看结果
结果会因模型和执行情况而异。
LangChain 智能体
txt
**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.深度智能体
txt
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 智能体提供了答案,但都是估算值。该智能体缺乏回答此问题所需的工具。你还可能会遇到提示词过长的错误。
另一方面,深度智能体可以:
1. **规划其方法**,使用内置的 [`write_todos`](/oss/deepagents/harness#task-planning) 工具分解研究任务。
1. **加载文件**,通过调用 `fetch_text_from_url` 工具收集信息。
1. **管理上下文**,通过使用文件系统工具([`grep`](/oss/deepagents/harness#virtual-filesystem-access) 和 [`read_file`](/oss/deepagents/harness#virtual-filesystem-access))。
1. **按需生成子智能体**,将复杂的子任务委派给专门的子智能体。
对于 LangChain 智能体,你必须实现更多能力才能获得类似水平的服务,并可以根据需要在过程中进行自定义。
追踪智能体调用
你用 LangChain 构建的大多数有趣的应用程序都会对 LLM 进行大量调用。随着这些应用程序变得越来越复杂,能够检查智能体内部到底发生了什么就显得非常重要。做到这一点的最佳方式是使用 LangSmith。
注册一个 LangSmith 账户,并设置以下内容以开始记录追踪:
bash
export LANGSMITH_TRACING="true"
export LANGSMITH_API_KEY="..."设置完成后,再次运行你的脚本,然后在 LangSmith 上检查智能体调用期间发生了什么。
下一步
你现在拥有的智能体可以:
- 理解上下文并记住对话
- 智能地使用工具
- 提供结构化响应,格式保持一致
- 通过上下文处理特定于用户的信息
- 在多次交互之间保持对话状态
- 规划、研究和综合(仅限深度智能体)
继续学习: