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?" }], }));
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.`;
现在,将智能体的所有组件组装起来并运行它。有两种不同的框架用于创建智能体:LangChain 智能体和 Deep Agents。LangChain 和 Deep Agents 都为您提供了对工具、记忆等的精细控制。两者的主要区别在于,Deep Agents 预置了一系列常用的实用功能,例如规划、文件系统工具和子智能体。当您需要以最少的设置获得最大的功能时,请使用 Deep Agents;当您需要精细控制时,请选择 LangChain 智能体。
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;});
显示 完整示例代码
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;});
6
查看结果
结果会根据模型和执行情况而有所不同。
LangChain 智能体
Deep 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.
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.