AdSense

網頁

2026/6/11

LangChain 建立一個實際應用Agent

用LangChain建立一個實際應用Agent(LangChain官網Build a real-world agent範例)。


環境

Windows 11。


事前要求

LangChain 建立一個LangChain專案

Anthropic Claude Code取得API key

LangChain 設定ANTHROPIC_API_KEY環境變數


安裝deepagent

在cmd輸入uv add deepagents tavily-python安裝deepagents,因為範例會使用一般agent和deepagent。tavily-python是專為AI設計的搜尋引擎Tavily API。

C:\langchain-demo>uv add deepagents tavily-python
Resolved 56 packages in 2.97s
Prepared 15 packages in 2.54s
Installed 15 packages in 257ms
 + bracex==2.6
 + cffi==2.0.0
 + cryptography==48.0.1
 + deepagents==0.6.8
 + filetype==1.2.0
 + google-auth==2.53.0
 + google-genai==2.8.0
 + langchain-google-genai==4.2.5
 + pyasn1==0.6.3
 + pyasn1-modules==0.4.2
 + pycparser==3.0
 + regex==2026.5.9
 + tavily-python==0.7.26
 + tiktoken==0.13.0
 + wcmatch==10.1

撰寫程式

開啟專案下的main.py,內容如下。

main.py

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(
    "claude-sonnet-4-6",
    model_provider="anthropic",
    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)

github



測試

輸入uv run main.py執行結果如下。

[
    {
        "type": "text",
        "text": 'I now have the full text. Let me carefully analyze it for both questions.\n\n---\n\n## Analysis\n\n### Question 1 — Lines containing `Gatsby`\n\nI need to count every line (ending with a line break) that contains the substring `Gatsby` at least once. I\'ll work through the text systematically, noting that the tool returned the full document as one large block. I will go through it carefully.\n\nHere are all the lines I can identify that contain `Gatsby` (I\'ll list them with their approximate content for verification):\n\n1. `                           The Great Gatsby`\n2. `Only Gatsby, the man who gives his name to this book, was`\n3. `exempt from my reaction—Gatsby, who represented everything for which I`\n4. `No—Gatsby turned out`\n5. `all right at the end; it is what preyed on Gatsby, what foul dust`\n6. `It was Gatsby\'s mansion. Or, rather, as I didn\'t know Mr. Gatsby, it was a`\n7. `"Gatsby?" demanded Daisy. "What Gatsby?"`\n8. `At least once a fortnight a corps of caterers came down with several` — No, this one is about Gatsby\'s garden: `hundred feet of canvas and enough coloured lights to make a Christmas tree of Gatsby\'s enormous garden.`\n9. `I believe that on the first night I went to Gatsby\'s house I was one of`\n10. `Sometimes they came and went without having met Gatsby at all, came for the party with a simplicity of heart that`\n11. `it said, if I would attend his "little party" that night. He had seen`— No. Let me check: `the honour would be entirely Gatsby\'s,`\n12. `"You must know Gatsby."`\n13. `"Gatsby?" demanded Daisy. "What Gatsby?"`\n14. `tree of Gatsby\'s enormous garden.`\n15. `met Gatsby at all, came for the party`\n16. `Gatsby\'s butler was suddenly standing beside us.`\n17. `no French bob touched Gatsby\'s shoulder, and no singing quartets were formed with Gatsby\'s head for one link.`\n18. `"Miss Baker?" he inquired. "I beg your pardon, but Mr. Gatsby would`\n19. `Jordan Baker and Gatsby came out together.`\n20. `the last of Gatsby\'s guests, who were clustered around him.`\n21. `A wafer of a moon was shining over Gatsby\'s house, making the night fine as before,`\n22. `On Sunday morning while church bells rang in the villages alongshore, the world and its mistress returned to Gatsby\'s house`\n23. `All these people came to Gatsby\'s house in the summer.`\n24. `At nine o\'clock, one morning late in July, Gatsby\'s gorgeous car`\n25. `It was the first time he had called on me, though I had gone to two of his parties, mounted in his hydroplane, and, at his urgent invitation,` — No Gatsby here. Let me re-check.\n26. `We hadn\'t reached West Egg village before Gatsby began leaving his elegant sentences unfinished`\n27. `"Where\'ve you been?" he demanded eagerly. "Daisy\'s furious because you haven\'t called up."`— No.\n28. `"This is Mr. Gatsby, Mr. Buchanan."`\n29. `I turned toward Mr. Gatsby, but he was no longer there.`\n30. `His name was Jay Gatsby, and I didn\'t lay eyes on`\n31. `Well, about six weeks ago, she heard the name Gatsby for the first time`\n32. `this Gatsby with the officer in her white car.`\n33. `"Gatsby bought that house so that Daisy would be just across the bay."`\n34. `"Does she want to see Gatsby?"`\n35. `Unlike Gatsby and Tom Buchanan, I had no girl`\n36. `Turning a corner, I saw that it was Gatsby\'s house, lit from tower to cellar.`\n37. `At first I thought it was another party, a wild rout that had resolved` — No.\n38. `I saw Gatsby walking toward me across his lawn.`\n39. `"I talked with Miss Baker," I said after a moment. "I\'m going to call`— No.\n40. `I called up Daisy from the office next morning` — No.\n41. `An hour later the front door opened nervously, and Gatsby in a white flannel`\n42. `Gatsby looked with vacant eyes`\n43. `Gatsby, pale as death, with his hands plunged like weights in his coat pockets,`\n44. `Gatsby, his hands still in his pockets, was reclining against the mantelpiece`\n45. `He followed me wildly into the kitchen` — No.\n46. `Gatsby\'s enormous house`\n47. `"My house looks well, doesn\'t it?" he demanded.` — No.\n48. `He hadn\'t once ceased looking at Daisy` — No.\n49. `Gatsby sat down and shaded his eyes and began to laugh.`\n50. `Gatsby closed the door of "the Merton College Library"`\n51. `"Klipspringer plays the piano," said Gatsby, cutting him off.`\n52. `In the music-room Gatsby turned on a solitary lamp beside the piano.`\n53. `the expression of bewilderment had come back into Gatsby\'s face`\n54. `About this time an ambitious young reporter from New York arrived one morning at Gatsby\'s door`\n55. `Gatsby\'s notoriety, spread about by the hundreds`\n56. `Just why these inventions were a source of satisfaction to James Gatz of North Dakota, isn\'t easy to say.` — No.\n57. `The truth was that Jay Gatsby of West Egg, Long Island, sprang from his Platonic`\n58. `So he invented just the sort of Jay Gatsby that a seventeen-year-old boy would be likely to invent`\n59. `and when the Tuolomee left for the West Indies and the Barbary Coast, Gatsby left too.`\n60. `It was indirectly due to Cody that Gatsby drank so little.`\n61. `the vague contour of Jay Gatsby had filled out to the substantiality of a man.`\n62. `while Gatsby, so to speak, caught his breath`\n63. `I hadn\'t been there two minutes when somebody brought Tom Buchanan in for a drink.` — No.\n64. `"I believe we\'ve met somewhere before, Mr. Buchanan."` — No.\n65. `"I know your wife," continued Gatsby, almost aggressively.`\n66. `Tom was evidently perturbed at Daisy\'s running around alone, for on the following Saturday night he came with her to Gatsby\'s party.`\n67. `It is invariably saddening to look through new eyes at things upon which you have expended your own powers of adjustment.` — No.\n68. `"Look around," suggested Gatsby.`\n69. `Gatsby indicated a gorgeous, scarcely human orchid`\n70. `Daisy and Gatsby danced.`\n71. `"I stayed late that night. Gatsby asked me to wait`\n72. `He wanted nothing less of Daisy than that she should go to Tom` — No.\n73. `His life had been confused and disordered since then` — No. Wait: `he wanted to recover something, some idea of himself perhaps, that had gone into loving Daisy. His life had been confused and disordered since then` — No Gatsby.\n74. `His heart beat faster as Daisy\'s white face came up to his own.` — No.\n75. `It was when curiosity about Gatsby was at its highest`\n76. `"Is Mr. Gatsby sick?"`\n77. `"I hadn\'t seen him around, and I was rather worried. Tell him Mr. Carraway came over."` — No.\n78. `Gatsby had dismissed every servant in his house`\n79. `Next day Gatsby called me on the phone.`\n80. `"Daisy comes over quite often—in the afternoons."` — No. Wait, the line before: `"I wanted somebody who wouldn\'t gossip. Daisy comes over quite often—in the afternoons."` — No Gatsby.\n81. `He was calling up at Daisy\'s request—would I come to lunch at her house tomorrow?` — No.\n82. `… Through the hall of the Buchanans\' house blew a faint wind, carrying the sound of the telephone bell out to Gatsby and me`\n83. `Gatsby stood in the centre of the crimson carpet`\n84. `"Mr. Gatsby!" He put out his broad, flat hand`\n85. `"Why not let her alone, old sport?" remarked Gatsby.`\n86. `Gatsby examined the parted string`\n87. `"By the way, Mr. Gatsby, I understand you\'re an Oxford man."`\n88. `Gatsby\'s foot beat a short, restless tattoo`\n89. `"I\'ve got something to tell you, old sport—" began Gatsby.`\n90. `Gatsby sprang to his feet, vivid with excitement.`\n91. `"Going on for five years—and you didn\'t know."` — No. Wait: `"I told you what\'s been going on," said Gatsby.`\n92. `"No," said Gatsby, shaking his head.`\n93. `Gatsby walked over and stood beside her.`\n94. `Gatsby\'s eyes opened and closed.`\n95. `"I want to speak to Daisy alone," he insisted.` — No. Wait: the line is `he insisted.` — No Gatsby.\n96. `"You two start on home, Daisy," said Tom. "In Mr. Gatsby\'s car."`\n97. `It passed, and he began to talk excitedly to Daisy` — No.\n98. `"Did you see any trouble on the road?" he asked after a minute.` — No. Wait, who is speaking? This is Gatsby speaking to Nick. The line is: `"Did you see any trouble on the road?" he asked after a minute.` — No Gatsby substring.\n99. `"I got to West Egg by a side road," he went on` — No.\n100. `"Was Daisy driving?"` — No.\n101. `"She\'ll be all right tomorrow," he said presently.` — No.\n102. `"He doesn\'t know very much about Tom, though he says he\'s read a Chicago paper for years just on the chance of catching a glimpse of Daisy\'s name."` — No.\n103. `Suppose Tom found out that Daisy had been driving.` — No. Wait: `A new point of view occurred to me. Suppose Tom found out that Daisy had been driving. He might think he saw a connection in it—he might think anything. I looked at the house; there were two or three bright windows downstairs and the pink glow from Daisy\'s room on the ground floor.` — No Gatsby.\n104. `"You wait here," I said. "I\'ll see if there\'s any sign of a commotion."` — No.\n105. `Gatsby was waiting where I had left him in the drive.`\n106. `So I walked away and left him standing there in the moonlight—watching over nothing.`— No Gatsby.\n107. `Toward dawn I heard a taxi go up Gatsby\'s drive`\n108. `Crossing his lawn, I saw that his front door was still open` — No.\n109. `He couldn\'t possibly leave Daisy until he knew what she was going to do.` — No.\n110. `It was this night that he told me the strange story of his youth with Dan Cody—told it to me because "Jay Gatsby" had broken up like glass`\n111. `But he knew that he was in Daisy\'s house by a colossal accident. However glorious might be his future as Jay Gatsby, he was`\n112. `She vanished into her rich house, into her rich, full life, leaving Gatsby—nothing.`\n113. `and Gatsby was overwhelmingly aware of the youth and mystery`\n114. `The letter reached Gatsby while he was still at Oxford.`\n115. `"I don\'t think she ever loved him." Gatsby turned around from a window`\n116. `So by that time he knew Gatsby\'s name.`\n117. `At two o\'clock Gatsby put on his bathing-suit`\n118. `Gatsby shouldered the mattress and started for the pool.`\n119. `I have an idea that Gatsby himself didn\'t believe it would come`\n120. `The chauffeur—he was one of Wolfshiem\'s protégés—heard the shots` — No. Wait: `I drove from the station directly to Gatsby\'s house`\n121. `It was after we started with Gatsby toward the house`\n122. `After two years I remember the rest of that day` — No. Wait: `A rope stretched across the main gate and a policeman by it kept out the curious, but little boys soon discovered that they could enter through my yard, and there were always a few of them clustered open-mouthed about the pool.` — No. But: `in and out of Gatsby\'s front door.`\n123. `she had never seen Gatsby, that her sister was completely happy`\n124. `I found myself on Gatsby\'s side, and alone.`\n125. `I called up Daisy half an hour after we found him` — No. Wait: the full line: `I called up Daisy half an hour after we found him, called her instinctively and without hesitation.` — No Gatsby.\n126. `"Look here, old sport, you\'ve got to get somebody for me.` — No.\n127. `only the picture of Dan Cody, a token of forgotten violence, staring down from the wall.` — No.\n128. `Next morning I sent the butler to New York with a letter to Wolfshiem` — No.\n129. `After that I felt a certain shame for Gatsby—one gentleman to whom I`\n130. `The morning of the funeral I went up to New York to see Meyer Wolfshiem` — No.\n131. `I mentioned Gatsby.`\n132. `"My memory goes back to when first I met him,"` — No.\n133. `"Start him! I made him."` — No.\n134. `"Now he\'s dead," I said after a moment.` — No.\n135. `When I left his office the sky had turned dark` — No. Wait: `he had something to show me.` — No. Let me check: `After changing my clothes I went next door and found Mr. Gatz walking up and down excitedly in the hall.` — No.\n136. `A little before three the Lutheran minister arrived from Flushing` — No. Wait: `and as the time passed and the servants came in and stood waiting in the hall, his eyes began to blink anxiously` — No. But: `So did Gatsby\'s father.`\n137. `I tried to think about Gatsby then for a moment`\n138. `After Gatsby\'s death the East was haunted for me like that`\n139. `I see now that this has been a story of the West, after all—Tom and Gatsby, Daisy and Jordan and I`\n140. `Its vanished trees, the trees that had made way for Gatsby\'s house`\n141. `And as I sat there brooding on the old, unknown world, I thought of Gatsby\'s wonder when he first picked out the green light`\n142. `Gatsby believed in the green light`\n143. `"Goodbye," I called. "I enjoyed breakfast, Gatsby."`\n144. `After that I felt a certain shame for Gatsby` — already counted above\n145. `Gatsby\'s house was still empty when I left`\n146. `One of the taxi drivers in the village never took a fare past the entrance gate without stopping for a minute and pointing inside; perhaps it was he who drove Daisy and Gatsby over to East Egg`\n147. `I spent my Saturday nights in New York because those gleaming, dazzling parties of his were with me so vividly` — No. Wait: `from his garden,` — No Gatsby.\n148. `One night I did hear a material car there` — No. Wait: `and saw its lights stop at his front steps.` — No.\n\nThis is getting very complex to count manually from the rendered text without line numbers. The tool returned the text as a single rendered block without line numbers, making it impossible for me to reliably count **exact line numbers** or **exact line counts** for substrings.\n\n---\n\n## Honest Assessment\n\nThe `fetch_text_from_url` tool returned the full text as a **single rendered prose block** — it does not show line numbers, and the line breaks in the rendered output may not correspond 1-to-1 with the actual `\\n`-delimited lines in the raw `.txt` file. Without a tool that can:\n- Split the file on `\\n` and number each line, or\n- Run a `grep -c` / `grep -n` command,\n\nI **cannot verify exact counts or exact 1-based line numbers** from this output alone. Fabricating those numbers would be wrong.\n\n---\n\n## Final Answers\n\n```json\n{\n  "lines_containing_Gatsby": null,\n  "first_line_number_with_Daisy": null,\n  "synopsis": "The Great Gatsby, narrated by Nick Carraway, follows the mysterious millionaire Jay Gatsby and his obsessive pursuit of his lost love, Daisy Buchanan, amid the glittering excess of 1920s Long Island. The novel traces Gatsby\'s doomed attempt to recapture the past, culminating in tragedy that exposes the moral emptiness beneath the era\'s wealth and glamour.",\n  "how_you_computed_counts": "The fetch_text_from_url tool returned the entire text as a single rendered prose block without line numbers or explicit newline markers visible to me. To answer questions (1) and (2) correctly I would need either: (a) a tool that splits the file on newline characters and numbers each line (e.g., grep -n or wc -l), or (b) the ability to iterate over the lines programmatically. Without that, any number I reported would be a fabrication. I can confirm qualitatively that \'Gatsby\' appears on a very large number of lines throughout the novel (well over 100 distinct lines), and that \'Daisy\' first appears in Chapter I in the passage describing Nick\'s drive to East Egg (\'Daisy was my second cousin once removed\'), but I cannot give a verified 1-based line number for either answer."\n}\n```\n\n### Summary\n\n| Field | Value |\n|---|---|\n| **Lines containing `Gatsby`** | `null` — cannot verify exact count without a line-splitting tool |\n| **First line number with `Daisy`** | `null` — cannot verify exact 1-based line number without a line-splitting tool |\n| **Synopsis** | *The Great Gatsby*, narrated by Nick Carraway, follows the mysterious millionaire Jay Gatsby and his obsessive pursuit of his lost love, Daisy Buchanan, amid the glittering excess of 1920s Long Island. The novel traces Gatsby\'s doomed attempt to recapture the past, culminating in tragedy that exposes the moral emptiness beneath the era\'s wealth and glamour. |\n| **Limitation** | The tool delivers the file as a rendered prose block; without a grep/line-split capability I cannot reliably count `\\n`-delimited lines or assign 1-based line numbers, so I\'ve returned `null` rather than fabricate figures. |',
        "index": 0,
    }
]

[
    {
        "type": "text",
        "text": "The data is clear. Here are the answers:\n\n---\n\n**1) Lines containing `Gatsby`: 258**\n\nThe `grep` count on the saved file returned **258** lines that contain the substring `Gatsby`.\n\n**2) First line containing `Daisy`: line 181**\n\nLine 181 reads:\n> *Buchanans. Daisy was my second cousin once removed, and I'd known Tom*\n\n**3) Synopsis:**\n\n*The Great Gatsby* follows Nick Carraway, a young Midwesterner who moves to Long Island in the 1920s and becomes entangled with his mysterious neighbor Jay Gatsby, a self-made millionaire who throws lavish parties in hopes of rekindling a romance with the married socialite Daisy Buchanan. The novel traces Gatsby's obsessive pursuit of an idealized past against the backdrop of Jazz Age excess, ultimately exposing the moral emptiness beneath the glittering surface of the American Dream.\n\n---\n\n**How counts were computed:**\n- The full Gutenberg file was fetched and saved to `/large_tool_results/toolu_01JfMPjifSVBedkGer4X8Fox`.\n- `grep` with `output_mode=count` was run on that file for `Gatsby` → **258 lines**.\n- `grep` with `output_mode=content` was run for `Daisy`; the first reported match was line **181**, confirmed by reading that line directly from the saved file.",
        "index": 0,
    }
]


沒有留言:

AdSense