from langchain.agents import create_agentdef 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.4", 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)
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 智能体。
from langchain.agents import create_agentfrom deepagents import create_deep_agentagent = 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.txtAnswer 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 withyour available tools and reasoning, do not fabricate numbers: use `null` for that field and spell outthe 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)
显示 完整代码示例
import urllib.errorimport urllib.requestfrom langchain.agents import create_agentfrom deepagents import create_deep_agentfrom langchain.chat_models import init_chat_modelfrom langchain.tools import toolfrom langgraph.checkpoint.memory import InMemorySaverSYSTEM_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."""@tooldef 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 textmodel = 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.txtAnswer 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 withyour available tools and reasoning, do not fabricate numbers: use `null` for that field and spell outthe 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)
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.
如果您查看两个标签页上的输出,会注意到 LangChain 智能体提供了答案,但它们只是估算值。该智能体缺乏回答此问题的工具。您还可能会收到提示词太长的错误。而 Deep Agents 则可以: