<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sourav Bhattacharjee on Medium]]></title>
        <description><![CDATA[Stories by Sourav Bhattacharjee on Medium]]></description>
        <link>https://medium.com/@souravb65?source=rss-6c0ab09ea1d9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*I-PAwFH_dbmYB1LvxayY4w.jpeg</url>
            <title>Stories by Sourav Bhattacharjee on Medium</title>
            <link>https://medium.com/@souravb65?source=rss-6c0ab09ea1d9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 12:16:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@souravb65/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Your LangChain Agent Shouldn’t Read Everything: Give It RAG]]></title>
            <link>https://medium.com/@souravb65/your-langchain-agent-shouldnt-read-everything-give-it-rag-3dc4165939d9?source=rss-6c0ab09ea1d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3dc4165939d9</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Sourav Bhattacharjee]]></dc:creator>
            <pubDate>Sat, 08 Aug 2026 07:26:38 GMT</pubDate>
            <atom:updated>2026-08-08T07:26:38.604Z</atom:updated>
            <content:encoded><![CDATA[<p>My briefing agent could tell me how many stories it fetched. It could not tell me the score.</p><p>By the end of the last part it had memory. I could ask “how many stories today?” and it answered. I could ask “what was in the TL;DR?” and it answered. Then I asked “what was the score in the England match?” and it either shrugged, or worse, made one up from stale training data. The digest it was holding only had headlines and one-line summaries. The actual number lived in the article body, and the agent had never been given the body.</p><p>I had two bad options. Paste all twelve full articles into the prompt so the agent can see everything, and pay to re-send tens of thousands of tokens on every single turn. Or keep the prompt cheap and let the agent guess. One is expensive, the other is fiction.</p><p>There is a third option, and it is the whole point of this post: don’t put the articles in the prompt at all. Put them in a search index, and give the agent a search box.</p><p>This builds on a morning-briefing agent from the earlier parts, but you can read this on its own. All you need to know: we have an agent that fetches a dozen news articles a day, writes a short digest, and can chat about it. The digest is cheap and small. The article bodies are big. We want the agent to answer specific questions without dragging everybody into the conversation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6xsZJsCFtpAHNuKGa6OaCg.png" /></figure><h3>Table of contents</h3><ul><li><a href="#the-question-the-digest-cant-answer">The question the digest can’t answer</a></li><li><a href="#dont-memorize-look-it-up">Don’t memorize. Look it up.</a></li><li><a href="#three-moving-parts-nothing-more">Three moving parts, nothing more</a></li><li><a href="#chunk-it-or-drown-in-noise">Chunk it, or drown in noise</a></li><li><a href="#does-it-actually-find-the-right-thing">Does it actually find the right thing?</a></li><li><a href="#distance-is-the-number-to-trust">Distance is the number to trust</a></li><li><a href="#giving-the-agent-the-search-box">Giving the agent the search box</a></li><li><a href="#the-prompt-that-forces-a-lookup">The prompt that forces a lookup</a></li><li><a href="#what-to-remember">What to remember</a></li><li><a href="#the-code">The code</a></li></ul><h3>The question the digest can’t answer</h3><p>The digest is a summary. That is its job. It has a headline, a source, and a one-line “why it matters” for each story. It is a few thousand characters, and it is cheap to keep in the conversation.</p><p>What it does not have is the score, the price, the quote, the exact number. Those live in the article body, which can run a few thousand words on its own. Twelve of those is a wall of text.</p><p>So when a reader asks the specific question, the digest genuinely cannot answer it. The information was never in there. You have to go back to the body.</p><p>The lazy fix is to seed all twelve bodies into the conversation up front, so the agent always has them. I tried it. On a chat thread that keeps growing, every one of those bodies gets re-sent to the model on every turn, because that is how conversational memory works: history is resent, and it only grows. The starting cost of a thread jumps from a few thousand tokens to twenty thousand before the reader has typed a single question. You pay that tax on every answer, including the ones that never needed a body at all.</p><blockquote>The context window is not a database. Stop treating it like one.</blockquote><h3>Don’t memorize. Look it up.</h3><p>Here is the reframe that fixes it. A person answering questions about today’s news does not memorize twelve articles. They keep the headlines in their head, and when you ask something specific, they go find the paragraph that has the answer.</p><p>That is retrieval. Keep the small thing (the digest) in the conversation. Keep the big thing (the bodies) outside it, in a searchable index. When a question actually needs a detail, the agent runs a search, pulls back only the handful of passages that match, and answers from those. When a question does not need a body, no body gets fetched and nothing extra gets paid for.</p><p>The trick that makes this work is searching by <em>meaning</em>, not by keyword. A reader might ask “who won the England match” when the article never uses the word “won” and calls it a “one-off Test.” Keyword search misses that. Semantic search does not, because it matches on what the text is about, not the exact words. That is what embeddings buy you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6KzJ8Qa5oJJ9ZoOa3X3o7A.png" /></figure><h3>Three moving parts, nothing more</h3><p>Retrieval sounds like a lot of machinery. It is three things.</p><ol><li>An <strong>embeddings model</strong> turns a piece of text into a vector, a list of numbers that captures its meaning. Similar meanings land close together in that number space.</li><li>A <strong>vector store</strong> holds those vectors along with the original text and its metadata, and knows how to find the nearest ones to a query vector.</li><li>A <strong>similarity search</strong> embeds your query, then asks the store for the closest stored vectors.</li></ol><p>For this project the embeddings come from Azure OpenAI and the store is Chroma, which runs in-process with no server to stand up. Two new dependencies:</p><pre># RAG: local vector store + Azure embeddings<br>langchain-chroma&gt;=0.1.4<br>langchain-text-splitters&gt;=0.3.0<br>chromadb&gt;=0.5.0</pre><p>Embeddings use a <em>separate</em> Azure deployment from your chat model. You deploy an embedding model such as text-embedding-3-small, then point one more environment variable at it:</p><pre>AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME=text-embedding-3-small</pre><p>The embedder itself is a few lines:</p><pre>from langchain_openai import AzureOpenAIEmbeddings<br>def build_embedder() -&gt; AzureOpenAIEmbeddings:<br>    load_dotenv()<br>    return AzureOpenAIEmbeddings(<br>        azure_deployment=os.environ[&quot;AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME&quot;],<br>        api_version=os.environ[&quot;AZURE_OPENAI_API_VERSION&quot;],<br>        azure_endpoint=os.environ[&quot;AZURE_OPENAI_ENDPOINT&quot;],<br>        api_key=os.environ[&quot;AZURE_OPENAI_API_KEY&quot;],<br>    )</pre><p>Call embed_query(&quot;...&quot;) on that and you get back a list of 1536 floats. That list is the whole idea. Text in, meaning as coordinates out.</p><h3>Chunk it, or drown in noise</h3><p>You could embed each article as one big vector. Don’t. A full article is about several things at once. Embed the whole thing and its vector becomes a blurry average of all of them, so a sharp query like “T20 series result” gets diluted by the same article’s paragraphs on Test cricket, injuries, and weather.</p><p>The fix is to split each body into small overlapping chunks and embed those. A query then lands on the specific paragraph that answers it, not the article-length blob it lives in.</p><pre>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>from langchain_core.documents import Document<br><br>splitter = RecursiveCharacterTextSplitter(<br>    chunk_size=800,<br>    chunk_overlap=100,<br>    separators=[&quot;\n\n&quot;, &quot;\n&quot;, &quot;. &quot;, &quot; &quot;, &quot;&quot;],<br>)<br>docs: list[Document] = []<br>for s in stories:<br>    parts = splitter.split_text(s[&quot;body&quot;])<br>    for i, part in enumerate(parts):<br>        docs.append(Document(<br>            page_content=part,<br>            metadata={<br>                &quot;title&quot;: s[&quot;title&quot;],<br>                &quot;source&quot;: s[&quot;source&quot;],<br>                &quot;category&quot;: s[&quot;category&quot;],<br>                &quot;url&quot;: s[&quot;url&quot;],<br>                &quot;chunk_index&quot;: i,<br>                &quot;chunk_count&quot;: len(parts),<br>            },<br>        ))</pre><p>Two numbers carry the weight here. chunk_size=800 keeps each piece focused on roughly one idea. chunk_overlap=100 copies the last hundred characters of one chunk onto the front of the next, so a sentence that straddles a boundary does not get sliced in half and lost. The separators list tells the splitter to break on paragraph gaps first, then line breaks, then sentence ends, and only chop mid-word as a last resort.</p><p>Notice the metadata copied onto every chunk. That is how a retrieved fragment still knows which article it came from, so the agent can attribute the answer and you can tell which part of the story you got.</p><h3>Does it actually find the right thing?</h3><p>This is the part I refuse to take on faith. Before wiring anything into the agent, I built a standalone script, rag_demo.py, that indexes one day&#39;s saved articles and runs a fixed set of queries, each written to aim at a different category. Then it checks whether the top hit actually lands in the category I expected.</p><pre>python rag_demo.py 2026-07-12</pre><pre>[rag_demo] Loading stories for 2026-07-12...<br>[rag_demo] Loaded 12 articles.<br>[rag_demo] Building embeddings + Chroma index...<br>[rag_demo] Index ready. Collection has 63 vectors.<br><br>======================================================================<br>Canned queries (expected category vs top-1 actual)<br>======================================================================<br>[OK] expected=&#39;Sports &amp; Entertainment&#39;<br>       got     =&#39;Sports &amp; Entertainment&#39; (dist=1.048)<br>       title   =Kranti Gaud makes history as India turn up heat on England in women&#39;s<br>[OK] expected=&#39;Business&#39;<br>       got     =&#39;Business&#39; (dist=0.543)<br>       title   =SBI Funds Management IPO size reduced to Rs 9,813 crore after pre-IPO<br>[OK] expected=&#39;Science&#39;<br>       got     =&#39;Science&#39; (dist=0.957)<br>       title   =U.S. regulator green-lights mission to launch giant mirror to orbit<br>[OK] expected=&#39;Technology &amp; Engineering&#39;<br>       got     =&#39;Technology &amp; Engineering&#39; (dist=0.909)<br>       title   =Motorola Edge 70 Max&#39;s battery details revealed - GSMArena.com news<br>======================================================================<br>Category-match rate: 4/4</pre><p>Twelve articles became 63 chunks, and all four queries landed in the right category. The one I care about most is the sports query, because I wrote it to be sneaky: &quot;cricket England T20 series result&quot; against an article that is actually about a one-off Test, never says &quot;T20,&quot; and never says &quot;result.&quot; Here is the top-3 for it:</p><pre>QUERY: &quot;cricket England T20 series result&quot;<br>----------------------------------------------------------------------<br>  1. [dist=1.040] [Sports &amp; Entertainment] Kranti Gaud makes history as India turn up heat on England in women&#39;s<br>     source: The Guardian<br>     preview: Test cricket is not easy when you play it once every 18 months; England&#39;s first innings veered from zealous attack to in...<br>  2. [dist=1.073] [Sports &amp; Entertainment] Kranti Gaud makes history as India turn up heat on England in women&#39;s<br>     source: The Guardian<br>     preview: India are in firm control of their one-off Test after bowling England out for 170 and reaching 154 for one at the close,...<br>  3. [dist=1.077] [Sports &amp; Entertainment] Kranti Gaud makes history as India turn up heat on England in women&#39;s<br>     source: The Guardian<br>     preview: England did at least avoid the indignity of the follow-on. But given the ominous levels of turn extracted by Rana, batti...</pre><p>The query and the document share almost no words, and it still found the right story. That is the whole reason to use embeddings instead of a keyword grep.</p><h3>Distance is the number to trust</h3><p>Every hit comes back with a score, and it is worth understanding because it is the honesty signal.</p><pre>hits = store.similarity_search_with_score(query, k=3)<br>for doc, score in hits:<br>    print(f&quot;[dist={score:.3f}] {doc.metadata[&#39;title&#39;]}&quot;)</pre><p>Chroma returns a <em>distance</em>, not a similarity, so lower is better. A score near 0 is a near-perfect match. A score near 2 means the two texts have basically nothing to do with each other. In the run above, the Business query scored 0.543 (a tight, confident match) while the sneaky sports query scored 1.040 (found it, but with more of a stretch, exactly as you’d expect from a query full of words the article never uses).</p><p>This number is what lets the agent be honest instead of confident. If the closest chunk is still far away, that is the signal to say “today’s briefing doesn’t cover that” rather than dressing up the nearest unrelated paragraph as an answer. An agent that retrieves without checking distance is just guessing with extra steps.</p><h3>Giving the agent the search box</h3><p>The demo proves retrieval works in isolation. Now it becomes a tool the agent can call. In LangChain that is a plain function with the @tool decorator and a very deliberate docstring, because the docstring is the only thing the model reads to decide when to call it.</p><pre>@tool<br>def search_todays_stories(query: str, k: int = 3) -&gt; str:<br>    &quot;&quot;&quot;Search today&#39;s briefing for stories relevant to `query`.<br><br>CALL THIS TOOL for any question that mentions a specific date, score,<br>    number, name, quote, event, place, or product detail - even if you<br>    think you already know the answer from prior training. The digest<br>    seeded into your first turn contains only headline-level summaries;<br>    the full article bodies live in this index and are the ONLY source of<br>    truth for specifics.<br>    &quot;&quot;&quot;<br>    k = max(1, min(int(k), 6))<br>    hits = _stories_index.similarity_search_with_score(query, k=k)<br>    results = []<br>    for doc, score in hits:<br>        results.append({<br>            &quot;title&quot;: doc.metadata.get(&quot;title&quot;, &quot;&quot;),<br>            &quot;source&quot;: doc.metadata.get(&quot;source&quot;, &quot;&quot;),<br>            &quot;category&quot;: doc.metadata.get(&quot;category&quot;, &quot;&quot;),<br>            &quot;chunk_index&quot;: doc.metadata.get(&quot;chunk_index&quot;, 0),<br>            &quot;chunk_count&quot;: doc.metadata.get(&quot;chunk_count&quot;, 1),<br>            &quot;distance&quot;: round(float(score), 3),<br>            &quot;content&quot;: doc.page_content,<br>        })<br>    return json.dumps(results)</pre><p>The tool returns JSON, not prose. The agent gets structured hits with the source, the distance, and the chunk position, so it can attribute the answer, judge confidence, and, if it got chunk 2 of 5 and needs more, search again for a neighbouring piece.</p><p>Inside the real chat flow, the index is built once when the session starts, and the tool is only attached if there were bodies to index:</p><pre>_stories_index = _build_stories_index(stories, embedder, today)<br><br>chat_agent = create_agent(<br>    model=llm,<br>    tools=[search_todays_stories] if _stories_index is not None else [],<br>    system_prompt=CHAT_PROMPT,<br>    checkpointer=checkpointer,<br>)</pre><p>The digest still gets seeded into the first turn, cheap and small. The bodies sit in Chroma, one tool call away. The agent decides, per question, whether it needs to reach for them.</p><h3>The prompt that forces a lookup</h3><p>Here is the failure I did not expect. Even with a working search tool bolted on, the model would sometimes skip it and answer a factual question straight from training data. It “knew” who a company was, so it did not bother to search, and confidently served an answer that had nothing to do with today’s article.</p><p>A tool the agent won’t call is worthless. The fix is not more code, it is a blunter prompt. I stopped politely offering the tool and started ordering its use:</p><pre>MANDATORY tool-call triggers - you MUST call search_todays_stories before<br>answering any question that mentions or requires:<br>  - a specific date, score, number, price, measurement, or statistic<br>  - a specific name (person, company, product, place)<br>  - a direct quote or paraphrase of what someone said<br>  - a specific event outcome (who won, what launched, what was announced)<br><br>Even if you &quot;know&quot; the answer from prior training, you MUST search first.<br>Your training data is stale; today&#39;s briefing is the authoritative source.</pre><p>That last line is the one that mattered. The model’s instinct is to trust what it already knows. You have to explicitly tell it that its knowledge is stale and the index is the truth. Retrieval is only half the job. The other half is convincing the agent to actually retrieve.</p><blockquote>If a constraint matters, don’t ask nicely. Make it mandatory and tell the model why.</blockquote><h3>The code</h3><p>Everything is at <a href="https://github.com/souravb65/morning-briefing-agent"><strong>github.com/souravb65/morning-briefing-agent</strong></a>.</p><p>It’s the same repo from the earlier parts, plus rag_demo.py:</p><pre>LangChainAgent/<br>├── briefing.py         # --chat now indexes bodies and exposes the search tool<br>├── rag_demo.py         # standalone: index a day&#39;s articles, run test queries<br>└── briefings/          # saved digests and the .stories.json bodies</pre><p>To run the retrieval demo against a saved day, then chat with the full agent:</p><pre>.\.venv\Scripts\Activate.ps1<br>pip install -r requirements.txt<br><br>python rag_demo.py 2026-07-12   # index 12 articles, run the 4 test queries<br>python briefing.py --chat-only  # chat about the last digest, tool-backed</pre><p>In chat mode, ask something specific (“what was the score in the England match?”) and watch the agent call the tool before it answers. That single tool call is the difference between an answer grounded in today’s article and a confident guess from last year’s training data.</p><p>Run rag_demo.py against your own briefing and tell me your category-match rate. Mine hit 4 out of 4. If a query fools yours into the wrong category, send me the query, because the ones that miss are where all the interesting retrieval problems hide.</p><p>Happy building.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3dc4165939d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Agent Forgets Everything: Watch What It Costs to Remember]]></title>
            <link>https://medium.com/@souravb65/your-agent-forgets-everything-watch-what-it-costs-to-remember-9df6a995c447?source=rss-6c0ab09ea1d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9df6a995c447</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Sourav Bhattacharjee]]></dc:creator>
            <pubDate>Mon, 27 Jul 2026 23:31:01 GMT</pubDate>
            <atom:updated>2026-08-08T06:05:16.717Z</atom:updated>
            <content:encoded><![CDATA[<p>My briefing agent had a beautiful digest and the memory of a goldfish.</p><p>I would ask it “tell me more about the second story,” and it would cheerfully reply, “Which story? I don’t have any stories.” We had literally just spoken. One question earlier it handed me twelve of them. By the next line it had forgotten the entire conversation.</p><p>This is not a bug. This is the default. And once you understand <em>why</em>, you understand the single most misunderstood thing about LLM agents: they don’t remember anything. Not one word. Every turn is the first turn unless you build the memory yourself.</p><p>This is Part 2 of building a morning-briefing agent in LangChain 1.x. In <a href="https://medium.com/@souravb65/build-observe-fix-a-langchain-agent-walkthrough-bc69e4c01342">Part 1</a> we built the thing that produces the digest and squashed three bugs that made it lie to us. Here we make it hold a conversation, and then we add the one piece of measurement every agent needs and almost none of them ship with: a way to see what each turn actually costs.</p><p>You can read this on its own. All you need to know from Part 1 is that we have a working agent, built with create_agent, that produces a daily news digest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hpTXmxPRhp2iVc0T_am3kw.png" /></figure><h3>Table of contents</h3><ul><li><a href="#the-goldfish-problem">The goldfish problem</a></li><li><a href="#memory-is-one-keyword-argument">Memory is one keyword argument</a></li><li><a href="#thread_id-is-the-whole-trick">thread_id is the whole trick</a></li><li><a href="#wiring-memory-into-the-briefing-agent">Wiring memory into the briefing agent</a></li><li><a href="#seed-it-with-the-summary-not-everything">Seed it with the summary, not everything</a></li><li><a href="#you-cant-manage-what-you-cant-see">You can’t manage what you can’t see</a></li><li><a href="#watching-the-bill-climb">Watching the bill climb</a></li><li><a href="#what-to-remember">What to remember</a></li><li><a href="#the-code">The code</a></li></ul><h3>The goldfish problem</h3><p>Let’s isolate the problem with the smallest possible experiment. Forget the news agent for a second. Two messages, one after the other:</p><pre>USER:  My favourite fruit is mango.<br>USER:  What is my favourite fruit?</pre><p>A human answers the second question without thinking. An agent, by default, cannot. Here is a tiny script, memory_demo.py, that runs exactly those two turns through a real create_agent:</p><pre>def turn(agent, user_msg: str, config: dict | None) -&gt; None:<br>    print(f&quot;\nUSER:  {user_msg}&quot;)<br>    result = agent.invoke(<br>        {&quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_msg}]},<br>        config=config or {},<br>    )<br>    print(f&quot;AGENT: {result[&#39;messages&#39;][-1].content}&quot;)</pre><pre># ...build a normal agent, no special arguments...<br>turn(agent, &quot;My favourite fruit is mango.&quot;, None)<br>turn(agent, &quot;What is my favourite fruit?&quot;, None)</pre><p>Run it with no special flags:</p><pre>python memory_demo.py</pre><pre>WITHOUT MEMORY (each invoke starts from an empty message list)<br>USER:  My favourite fruit is mango.<br>AGENT: That&#39;s great! Mango is delicious.<br>USER:  What is my favourite fruit?<br>AGENT: I don&#39;t know - you haven&#39;t told me that.</pre><p>Read that last line again. We told it. It even responded warmly. And it still has no idea, because the second agent.invoke(...) started from a blank message list. The first exchange never happened, as far as turn two is concerned.</p><p>Here’s the mental model that fixes this for good: <strong>an LLM call is a pure function.</strong> You give it a list of messages, it gives you back the next message. It keeps nothing. There is no hidden “conversation” living inside the model. If turn two is going to know about turn one, <em>you</em> have to hand turn one’s messages back to the model. Memory is not something the model has. It is something you carry.</p><h3>Memory is one keyword argument</h3><p>The good news, and the mildly dangerous news, is that LangGraph makes carrying that history absurdly easy. You add a checkpointer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TOnVgCpelTprj1zw" /></figure><p>A checkpointer is a place to save the conversation state after every step. Attach one and LangGraph will, on each invoke, load the saved messages, append the new ones, run the graph, and save the result back. The whole &quot;hand turn one&#39;s messages back to the model&quot; chore is done for you.</p><p>For local development the simplest one is InMemorySaver, which keeps everything in a Python dict:</p><pre>from langgraph.checkpoint.memory import InMemorySaver<br><br>checkpointer = InMemorySaver()<br>agent = create_agent(<br>    model=llm,<br>    tools=[echo],<br>    system_prompt=PROMPT,<br>    checkpointer=checkpointer,   # &lt;- the entire difference<br>)<br>config = {&quot;configurable&quot;: {&quot;thread_id&quot;: &quot;demo-user-1&quot;}}</pre><p>Same two turns, this time adding the --memory flag so the agent is built with the checkpointer:</p><pre>python memory_demo.py --memory</pre><pre>WITH MEMORY (InMemorySaver + thread_id=&#39;demo-user-1&#39;)<br>USER:  My favourite fruit is mango.<br>AGENT: Mango, nice choice!<br>USER:  What is my favourite fruit?<br>AGENT: Your favourite fruit is mango.</pre><p>One argument. That’s the whole gap between amnesia and recall.</p><p>And here’s my mildly dangerous opinion: because memory is <em>this</em> easy to switch on, most people switch it on everywhere and never think about it again. That’s a mistake, and the second half of this article is about why. Memory is not free. Every remembered turn is context you pay to re-send on the next turn. Easy to add is not the same as free to run.</p><h3>thread_id is the whole trick</h3><p>Look again at that config. The interesting part isn&#39;t InMemorySaver, it&#39;s thread_id.</p><pre>config = {&quot;configurable&quot;: {&quot;thread_id&quot;: &quot;demo-user-1&quot;}}</pre><p>The thread_id is the name of the conversation. The checkpointer stores history keyed by it. Use the same thread_id across invokes and you continue the same conversation. Use a different one and you get a clean, independent thread with zero shared memory.</p><p>That single string is how one process serves many separate conversations without them bleeding into each other. In a real app it’s your user ID, or a session ID, or chat-2026-07-12. Get it wrong in the fun way and user A starts seeing user B&#39;s history. Get it wrong in the boring way and every request spins up a fresh, amnesiac thread and you&#39;re back to the goldfish, wondering why memory &quot;isn&#39;t working&quot; when it&#39;s working perfectly on a thread you never reuse.</p><p>Two practical rules I now follow without exception:</p><ul><li><strong>The </strong><strong>thread_id is the conversation.</strong> Decide what a conversation <em>is</em> in your app, and derive the id from that. Don&#39;t let it be an afterthought.</li><li><strong>Different users must never share a </strong><strong>thread_id.</strong> It&#39;s a memory key, so it&#39;s also a privacy boundary.</li></ul><h3>Wiring memory into the briefing agent</h3><p>Back to the real agent. I wanted a --chat mode: produce the daily digest, then drop into a simple prompt loop where I can ask follow-up questions about today&#39;s news. Memory is the thing that makes &quot;the second story&quot; a sentence the agent can actually resolve.</p><p>The setup is exactly what the demo taught, with a thread_id scoped to the day:</p><pre>checkpointer = InMemorySaver()<br>chat_agent = create_agent(<br>    model=llm,<br>    tools=[search_todays_stories],<br>    system_prompt=CHAT_PROMPT,<br>    checkpointer=checkpointer,<br>)<br>thread_config = {&quot;configurable&quot;: {&quot;thread_id&quot;: f&quot;chat-{today}&quot;}}</pre><p>Then a plain input loop, reusing thread_config on every turn so the whole chat is one continuous thread:</p><pre>while True:<br>    user_input = input(&quot;YOU: &quot;).strip()<br>    if user_input.lower() in {&quot;quit&quot;, &quot;exit&quot;}:<br>        break<br>    result = chat_agent.invoke(<br>        {&quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_input}]},<br>        config=thread_config,<br>    )<br>    print(f&quot;AGENT: {result[&#39;messages&#39;][-1].content}&quot;)</pre><p>Now “tell me more about the second story” works, because turn two can see turn one. Ask a follow-up to the follow-up and it holds. The goldfish finally remembers.</p><p>I also added a --chat-only [DATE] fast path that loads a previously saved digest from disk and jumps straight into chat, skipping the whole fetch-and-write pipeline. When you&#39;re iterating on conversation behavior, you do not want to re-run the news gathering every single time. Save the expensive output once, replay it into chat as often as you like.</p><p>Try it against the digest you already built:</p><pre>python briefing.py --chat-only</pre><pre>============================================================<br>CHAT MODE - ask follow-up questions about today&#39;s briefing.<br>Type &#39;quit&#39;, &#39;exit&#39;, or press Ctrl+C to leave.<br>============================================================<br>[chat] Briefing loaded. Ask away.<br><br>YOU: tell me more about the second story<br>AGENT: ...</pre><p>Type quit or exit when you&#39;re done.</p><h3>Seed it with the summary, not everything</h3><p>Here’s the design decision I want you to notice, because it’s the hinge the whole chat design turns on.</p><p>When chat mode starts, I have twelve full article bodies sitting in memory. The obvious move is to stuff all twelve into the agent’s context so it can answer anything. I deliberately did not do that.</p><p>Instead, the very first message on the thread seeds the conversation with the digest <em>only</em>:</p><pre>seed_lines = [<br>    f&quot;Here is today&#39;s briefing for {today}. Use this - and only this - to&quot;,<br>    &quot;answer any follow-up questions I ask.&quot;,<br>    &quot;&quot;,<br>    &quot;=== FINAL DIGEST (Markdown) ===&quot;,<br>    digest,<br>]<br>chat_agent.invoke(<br>    {&quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;\n&quot;.join(seed_lines)}]},<br>    config=thread_config,<br>)</pre><p>The digest is a few thousand characters. The twelve full bodies are tens of thousands. If I seed the bodies, every single chat turn re-sends all of them to the model, forever, whether the question needs them or not. That is the memory cost I mentioned earlier, paid in full on every turn.</p><p>So the deal I struck: seed the cheap summary, and make the expensive bodies available <em>on demand</em> through a tool called search_todays_stories. When a question actually needs a specific detail, the agent goes and fetches only the relevant slice. When it doesn&#39;t, we never pay for the bodies. The principle is the part worth keeping: <strong>put the small thing in context, keep the big thing one tool call away.</strong></p><p>For this article, treat search_todays_stories as a black box: hand it a query, get back the most relevant chunks of today&#39;s articles. How it actually finds those chunks — embeddings, a vector index, similarity search — is a whole topic of its own, and it&#39;s the subject of the next part. Here, all that matters is <em>where</em> the bulk lives: behind a tool call, not in memory.</p><h3>You can’t manage what you can’t see</h3><p>I made a claim twice now: memory costs money, every turn re-sends the history. Claims are cheap. I wanted the number on my screen after every turn. So before adding anything clever, I added a way to measure it.</p><p>Here is the thing nobody hands you: the agent already records exactly what each call cost. Every AIMessage that comes back from create_agent carries a usage_metadata dict with input_tokens and output_tokens. And the checkpointer already holds the entire message history for the thread. Put those two facts together and you can compute the running bill without any external service.</p><p>The read is agent.get_state(config), which returns a snapshot whose .values[&quot;messages&quot;] is the full history:</p><pre>def get_chat_stats(agent, config: dict) -&gt; dict:<br>    snap = agent.get_state(config)<br>    msgs = snap.values.get(&quot;messages&quot;, [])<br>    ai_msgs = [m for m in msgs if type(m).__name__ == &quot;AIMessage&quot;]<br>    last = (getattr(ai_msgs[-1], &quot;usage_metadata&quot;, None) or {}) if ai_msgs else {}<br>    cum_in = sum((getattr(m, &quot;usage_metadata&quot;, None) or {}).get(&quot;input_tokens&quot;, 0)<br>                 for m in ai_msgs)<br>    cum_out = sum((getattr(m, &quot;usage_metadata&quot;, None) or {}).get(&quot;output_tokens&quot;, 0)<br>                  for m in ai_msgs)<br>    return {<br>        &quot;n_messages&quot;: len(msgs),<br>        &quot;last_input_tokens&quot;: last.get(&quot;input_tokens&quot;),<br>        &quot;last_output_tokens&quot;: last.get(&quot;output_tokens&quot;),<br>        &quot;cumulative_input_tokens&quot;: cum_in,<br>        &quot;cumulative_output_tokens&quot;: cum_out,<br>    }</pre><p>Then one line printed after every chat turn:</p><pre>[stats] history: 8 msgs, 25,241 chars | this turn: in=9103, out=592 | cumulative: in=26,574, out=647</pre><p>That single line changed how I think about the agent. Three things jump out of it:</p><ul><li><strong>history: N msgs</strong> tells you the conversation shape. It grows by 2 on a plain turn (your question, the answer) and by 4 when a tool fires (question, the tool-call message, the tool result, the final answer). You can <em>see</em> whether the agent reached for a tool without any tracing.</li><li><strong>this turn: in=</strong> is the number I care about most. That&#39;s the tokens the model was billed to read <em>this turn</em>, and it includes the entire history re-sent. Watch it, and the cost of memory stops being a claim and becomes a graph.</li><li><strong>cumulative: in=</strong> is what the thread has cost you so far. This is the real spend.</li></ul><p>Strong opinion, and I’ll die on this hill: <strong>token counting should be on from the first line of code, not bolted on after the bill scares you.</strong> It’s about fifteen lines. It reads data the framework already collected. There is no reason to fly blind, and every agent I’ve seen ship without it eventually surprises its owner with an invoice.</p><h3>Watching the bill climb</h3><p>Now the fun part. Start a session, then keep asking specific questions, each one triggering the search tool, and just watch this turn: in= climb:</p><pre>python briefing.py --chat-only</pre><pre>turn 1  -&gt;  in=3,101<br>turn 3  -&gt;  in=5,940<br>turn 5  -&gt;  in=8,700<br>turn 7  -&gt;  in=11,520</pre><p>Nobody changed the question difficulty. The questions are all roughly the same size. The input cost climbs anyway, turn after turn, because every turn re-sends everything that came before it. Memory only adds up. It never shrinks on its own.</p><p>This is the moment the whole design clicked for me. Memory is what makes an agent feel like it’s talking <em>with</em> you instead of <em>at</em> you. It’s also a slow, growing cost on every future turn. The more it remembers, the more each next answer costs. And if I had seeded those twelve full article bodies into the thread the way my first instinct wanted, that curve wouldn’t start at 3,000 tokens. It would start at 20,000 and climb from there.</p><p>So the seeding choice from earlier pays off right here. Because only the small digest lives in memory and the full bodies sit behind the search tool, the cost line starts low and stays manageable. The agent can still reach any detail it needs, but it only pays for what a given question actually touches. Memory is what gives you the conversation. Keeping the bulk out of memory is what keeps that conversation affordable.</p><h3>The code</h3><p>Everything is at <a href="https://github.com/souravb65/morning-briefing-agent">github.com/souravb65/morning-briefing-agent</a>.</p><p>It’s the same repo from Part 1, plus memory_demo.py:</p><pre>LangChainAgent/<br>├── briefing.py         # now with --chat / --chat-only and stats output<br>├── memory_demo.py      # the amnesia-vs-memory experiment<br>└── articles/           # these write-ups</pre><p>To feel the whole thing yourself:</p><pre>.\.venv\Scripts\Activate.ps1</pre><pre>python memory_demo.py            # forgets everything<br>python memory_demo.py --memory   # remembers</pre><pre>python briefing.py --chat        # build today&#39;s digest, then chat about it<br>python briefing.py --chat-only   # skip the build, chat about the last digest</pre><p>Ask a few follow-ups in chat mode and watch the [stats] line after each answer. Watching this turn: in= climb is the fastest way to feel, in your gut, what conversational memory actually costs.</p><p>Try the two memory_demo.py runs back to back and tell me your agent&#39;s answer to &quot;what is my favourite fruit?&quot; in each. If the no-memory run ever guesses &quot;mango&quot; correctly, I want to see it, because that would mean something genuinely weird is happening and I&#39;d love to dig into it.</p><p>And once your agent remembers, keep an eye on that this turn: in= number after every answer. The day it climbs faster than you expected is the day you&#39;ll really feel what memory costs.</p><p>Next up in Part 3: what’s actually inside search_todays_stories — turning those article bodies into a searchable index so the agent fetches only the slice a question needs. That&#39;s retrieval, and it&#39;s where this series goes next.</p><p>Happy building.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9df6a995c447" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build, Observe, Fix: A LangChain Agent Walkthrough]]></title>
            <link>https://medium.com/@souravb65/build-observe-fix-a-langchain-agent-walkthrough-bc69e4c01342?source=rss-6c0ab09ea1d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc69e4c01342</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Sourav Bhattacharjee]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 10:07:28 GMT</pubDate>
            <atom:updated>2026-08-08T06:04:27.679Z</atom:updated>
            <content:encoded><![CDATA[<p>Last week my morning news agent lied to me.</p><p>Every day it delivered a nice little briefing: headlines, sources, a “why it matters” bullet for each story, all wrapped in tidy Markdown. And every day it was completely fabricated.</p><p>Well, not completely. The headlines were real. But the summaries? The agent had never actually opened a single article. Not one. It grabbed the RSS titles, decided that was “enough context,” and quietly skipped the step I had explicitly asked it to perform.</p><p>It looked right. It sounded right. It was fiction.</p><p>I would never have caught it without a trace.</p><p>This post is the story of building that agent from scratch, plus the three bugs I hit and how I fixed them. If you’re new to LangChain agents, you’re going to hit these too. Better to see them here first.</p><p><strong>What you’re building:</strong> a “morning briefing” agent. Fetches top India news across four categories, actually reads the article bodies, and writes a structured daily digest. About 90 minutes to follow along if you already have an Azure OpenAI resource.</p><p>Full code is in the repo at the end. Read straight through, or jump to the bug that sounds like yours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u69umeYumkFco_yF6g2D3g.png" /></figure><h3>Table of contents</h3><ul><li><a href="#Before you start">Before you start</a></li><li><a href="#set-up-python-and-langchain-1x">Set up Python and LangChain 1.x</a></li><li><a href="#hello-agent">Hello, agent</a></li><li><a href="#the-briefing-agent-first-attempt">The briefing agent, first attempt</a></li><li><a href="#when-you-say-2-to-3-the-llm-hears-1">When you say “2 to 3,” the LLM hears “1”</a></li><li><a href="#adding-a-trace-to-see-what-the-agent-is-doing">Adding a trace to see what the agent is doing</a></li><li><a href="#the-bug-where-the-agent-lies-with-a-straight-face">The bug where the agent lies with a straight face</a></li><li><a href="#agents-should-decide-code-should-fetch">Agents should decide. Code should fetch.</a></li><li><a href="#google-news-urls-return-blank-pages">Google News URLs return blank pages</a></li><li><a href="#what-to-remember-when-you-build-your-own">What to remember when you build your own</a></li><li><a href="#the-code">The code</a></li></ul><h3>Before you start</h3><p>You’ll want:</p><ul><li>Windows 10 or 11 with PowerShell 7+ (pwsh). Everything below works with powershell.exe too.</li><li>VS Code (recommended, not required).</li><li>An Azure OpenAI resource with a deployed model like gpt-4o-mini. The <a href="https://learn.microsoft.com/azure/ai-services/openai/quickstart">Azure OpenAI quickstart</a> covers that.</li><li>Internet access. The agent calls Google News RSS and Azure OpenAI.</li></ul><p>You don’t need Python installed. We do that next.</p><h3>Set up Python and LangChain 1.x</h3><p>Windows ships with a stub that redirects python to the Microsoft Store. Skip that. Use winget for a real install.</p><pre>winget install --id Python.Python.3.12 -e --scope user `<br>    --accept-package-agreements --accept-source-agreements --silent</pre><p>Open a new terminal so PATH picks up the install, then verify:</p><pre>&amp; &quot;$env:LOCALAPPDATA\Programs\Python\Python312\python.exe&quot; --version<br># Python 3.12.10</pre><p>Create the project and a virtual environment:</p><pre>mkdir LangChainAgent<br>cd LangChainAgent<br>&amp; &quot;$env:LOCALAPPDATA\Programs\Python\Python312\python.exe&quot; -m venv .venv<br>.\.venv\Scripts\Activate.ps1<br>python -m pip install --upgrade pip setuptools wheel</pre><p>You should see (.venv) in your prompt.</p><p>Now the dependencies. Drop this in requirements.txt:</p><pre># Core LangChain 1.x stack<br>langchain&gt;=1.3<br>langchain-core&gt;=1.4<br>langchain-community&gt;=0.4<br>langchain-openai&gt;=1.3<br>langgraph&gt;=1.2<br>langsmith&gt;=0.9<br><br># Azure OpenAI SDK<br>openai&gt;=2.0<br><br># Utilities<br>python-dotenv&gt;=1.0<br>pydantic&gt;=2.7<br>tiktoken&gt;=0.13<br><br># HTTP + HTML<br>httpx&gt;=0.27<br>beautifulsoup4&gt;=4.12<br>lxml&gt;=5.2<br><br># News tools<br>feedparser&gt;=6.0.11<br>trafilatura&gt;=1.12<br>googlenewsdecoder&gt;=0.1.7</pre><p>Install:</p><pre>pip install -r requirements.txt</pre><p>Quick note on LangChain 1.x. The old AgentExecutor was moved to a separate langchain-classic package. The new agent facade is create_agent, which builds a LangGraph state machine under the hood. LangGraph is the actual engine now. LangChain gives you one convenient function on top and lets you drop down to raw graphs when you need more control.</p><p>Honestly, this reshuffle broke half the tutorials on the internet. If you’re reading old code that uses AgentExecutor or create_tool_calling_agent, it won&#39;t import cleanly on langchain&gt;=1.0. That&#39;s why I&#39;ve pinned versions above.</p><p>Now Azure OpenAI. Create .env.example (safe to commit):</p><pre>AZURE_OPENAI_API_KEY=your-api-key-here<br>AZURE_OPENAI_ENDPOINT=https://your-resource-name.openai.azure.com/<br>AZURE_OPENAI_API_VERSION=2024-10-21<br>AZURE_OPENAI_DEPLOYMENT_NAME=your-deployment-name</pre><p>Copy to .env (which stays local; add it to .gitignore immediately):</p><pre>Copy-Item .env.example .env</pre><p>Fill in real values from your Azure OpenAI resource:</p><ul><li><strong>Keys and Endpoint</strong> blade gives you AZURE_OPENAI_API_KEY and AZURE_OPENAI_ENDPOINT.</li><li><strong>Azure AI Foundry → Deployments</strong> gives you AZURE_OPENAI_DEPLOYMENT_NAME (the deployment name you chose, not the model name).</li></ul><p>Two gotchas here that will absolutely burn you.</p><p><strong>AZURE_OPENAI_ENDPOINT must be the base URL.</strong> Just https://&lt;name&gt;.openai.azure.com/. If your Foundry resource shows something like .../openai/v1, strip that suffix. AzureChatOpenAI appends its own path and you&#39;ll get a 404 if you leave the extra bit on.</p><p><strong>AZURE_OPENAI_API_VERSION is a REST API version, not a model version.</strong> Correct values look like 2024-10-21 or 2025-01-01-preview. If you paste 2024-07-18 (which is a gpt-4o-mini <em>model</em> version) you get a 404 &quot;Resource not found.&quot; I&#39;ve done this twice. It&#39;s confusing because the model version looks exactly like a date.</p><p>Finally, .gitignore:</p><pre>.venv/<br>.env<br>__pycache__/<br>*.pyc<br>.ipynb_checkpoints/<br>.langchain/<br>.langsmith/</pre><h3>Hello, agent</h3><p>Before we tackle the real briefing agent, let’s prove the wiring works.</p><p>An agent, stripped down, is a very simple loop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/0*Q6ZxbLvT_USxA6lg" /></figure><p>Three moving parts:</p><ul><li><strong>The model.</strong> The LLM (AzureChatOpenAI in our case) that decides what to do next.</li><li><strong>The tools.</strong> Plain Python functions decorated with @tool. LangChain reads the docstring and type hints and turns them into a JSON schema for the model.</li><li><strong>The system prompt.</strong> The agent’s standing instructions.</li></ul><p>That’s it. create_agent(...) wires those three into the loop and returns a LangGraph you .invoke(). You don&#39;t write the loop yourself. That&#39;s the whole point.</p><p>Here’s a minimal agent.py:</p><pre>&quot;&quot;&quot;Minimal tool-calling agent using Azure OpenAI + LangChain 1.x.&quot;&quot;&quot;<br>from __future__ import annotations<br>import os<br>from datetime import datetime<br>from dotenv import load_dotenv<br>from langchain.agents import create_agent<br>from langchain_core.tools import tool<br>from langchain_openai import AzureChatOpenAI<br><br>@tool<br>def get_current_time() -&gt; str:<br>    &quot;&quot;&quot;Return the current local date and time as an ISO 8601 string.&quot;&quot;&quot;<br>    return datetime.now().isoformat(timespec=&quot;seconds&quot;)<br><br>def build_agent():<br>    load_dotenv()<br>    llm = AzureChatOpenAI(<br>        azure_deployment=os.environ[&quot;AZURE_OPENAI_DEPLOYMENT_NAME&quot;],<br>        api_version=os.environ[&quot;AZURE_OPENAI_API_VERSION&quot;],<br>        azure_endpoint=os.environ[&quot;AZURE_OPENAI_ENDPOINT&quot;],<br>        api_key=os.environ[&quot;AZURE_OPENAI_API_KEY&quot;],<br>        temperature=0,<br>    )<br>    return create_agent(<br>        model=llm,<br>        tools=[get_current_time],<br>        system_prompt=&quot;You are a helpful assistant. Use tools when they help.&quot;,<br>    )<br><br>def main() -&gt; None:<br>    agent = build_agent()<br>    result = agent.invoke(<br>        {&quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;What time is it right now?&quot;}]}<br>    )<br>    print(&quot;\nFinal answer:&quot;, result[&quot;messages&quot;][-1].content)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Run it:</p><pre>python agent.py</pre><p>Something like Final answer: The current time is 08:00:00 on 2026-07-08.</p><p>Here’s what happened. AzureChatOpenAI was built from your .env values. create_agent produced a CompiledStateGraph with two nodes: model and tools. agent.invoke(...) fed the user message in. The model saw get_current_time in its tool schema, decided to call it, LangGraph ran the Python function, fed the result back to the model, and the model produced the final answer.</p><p>Simple. Now the interesting part.</p><h3>The briefing agent, first attempt</h3><p>Goal: fetch top India headlines across four categories, and produce a structured Markdown digest.</p><p>My first design was the obvious one:</p><ul><li>Tool A: fetch_headlines(category) returns top N headlines from a Google News RSS feed.</li><li>Tool B: fetch_article(url) fetches a URL and extracts clean article text.</li><li>One system prompt that tells the LLM to iterate the categories, pick the best stories, read them, and write the digest.</li></ul><p>Create briefing.py. The full file is in the repo. Here&#39;s the shape.</p><p><strong>Data source:</strong> Google News category RSS feeds, India / English.</p><pre>_REGION = &quot;hl=en-IN&amp;gl=IN&amp;ceid=IN:en&quot;<br>_FEEDS = {<br>    &quot;Technology &amp; Engineering&quot;: [f&quot;.../topic/TECHNOLOGY?{_REGION}&quot;],<br>    &quot;Science&quot;:                  [f&quot;.../topic/SCIENCE?{_REGION}&quot;],<br>    &quot;Business&quot;:                 [f&quot;.../topic/BUSINESS?{_REGION}&quot;],<br>    &quot;Sports &amp; Entertainment&quot;:   [f&quot;.../topic/SPORTS?{_REGION}&quot;,<br>                                 f&quot;.../topic/ENTERTAINMENT?{_REGION}&quot;],<br>}</pre><p>hl is UI language, gl is geolocation, ceid is edition. Free, no API key.</p><p>The two tools:</p><pre>@tool<br>def fetch_headlines(category: str, limit: int = 8) -&gt; str:<br>    &quot;&quot;&quot;Fetch top news headlines for a category from Google News (India).<br>    Returns JSON array of {title, source, url, published}.<br>    &quot;&quot;&quot;<br>    ...<br><br>@tool<br>def fetch_article(url: str) -&gt; str:<br>    &quot;&quot;&quot;Fetch a news article URL and return its cleaned main-body text.<br>    Handles Google News redirects. Returns extracted text (up to ~4000<br>    chars) or an error string starting with &#39;ERROR&#39;.<br>    &quot;&quot;&quot;<br>    ...</pre><p>Two patterns worth internalizing from these tools.</p><p><strong>Tools always return strings.</strong> LLMs consume text. If you have structured data, json.dumps it. The LLM will parse it back in its head.</p><p><strong>Return errors, don’t raise them.</strong> If fetch_article fails, we return &quot;ERROR ...&quot;. If we raise, the whole graph crashes. Returning an error string lets the LLM see it and decide what to do. This one pattern will save you more headaches than any other.</p><p>The system prompt described the four-step workflow (fetch, pick 2 to 3, read, digest) plus a Markdown template.</p><pre>python briefing.py</pre><p>It worked. The digest had the right shape.</p><p>But something was off.</p><h3>When you say “2 to 3,” the LLM hears “1”</h3><p>First run of the agent, I got a digest with four categories and exactly four stories. One per category. My prompt clearly said “pick 2–3 substantive stories per category.”</p><p>The model just… didn’t feel like it.</p><p>Here’s the thing nobody tells you: cost-aware LLMs read ranges the way a lazy contractor reads them. “2 to 3” means “1 will do.” “Up to 5” means “you’re getting 2.” Ranges anchor at the minimum, and everything below the range is fair game if the model thinks the effort isn’t worth it.</p><p>If you want three, ask for three. Not “2 to 3.” Not “at least 2.” Three.</p><p>Five things I changed in the prompt to fix it:</p><p><strong>1. Replace the range with an exact number.</strong> &quot;2-3 stories per category&quot; became &quot;EXACTLY 3 stories per category&quot;. Blunt. Boring. Works.</p><p><strong>2. Add explicit negatives.</strong> &quot;Not 1, not 2, not 4. Exactly 3.&quot; This feels insulting to write. It is. But you&#39;re not writing for a human. You&#39;re closing off the wiggle room the model would otherwise use.</p><p><strong>3. Close the “well, there weren’t enough good stories” escape hatch.</strong> &quot;If a category has fewer than 3 substantive stories, still pick 3. Use the next-best.&quot; Otherwise, the model will helpfully tell you, &quot;there wasn&#39;t much science news today&quot; and give you one story. Its judgment is not what you wanted.</p><p><strong>4. Add a self-check step.</strong> &quot;Before responding, count them. If fewer than 3 in any section, add more before you finish.&quot; This is the single biggest lever. Making the model count its own output catches more of these bugs than any wording change.</p><p><strong>5. Show the template with three explicit slots.</strong> If your Markdown template has one story block and then says (repeat for other stories), don&#39;t be surprised when you get one story. Write out three empty story blocks. The model pattern-matches what it sees.</p><p>Try #1 and #4 first. That’s usually enough. If it still misbehaves, add the rest.</p><blockquote>If a constraint matters, don’t ask nicely. State it exactly, list what’s forbidden, and make the model verify itself before it commits.</blockquote><p>After these edits, every run produced 12 stories: 4 categories times 3. Great.</p><p>But the digest content was still shallow. Every “Summary” bullet was a paraphrase of the headline, not a real summary of the article body. Was fetch_article even being called? I couldn&#39;t tell from the output alone.</p><p>Time to add observability.</p><h3>Adding a trace to see what the agent is doing</h3><p>You cannot debug an agent from its output. You need to watch it think.</p><p>There are three tiers of observability for LangChain agents, in order of investment:</p><p>TierWhat you seeSetupStream events locallyModel turns, tool calls, tool results, printed live~30 lines, no depsVerbose callbacksSame, plus full payloads2 linesLangSmith / Langfuse / PhoenixWeb UI with tokens, latency, cost, replays3 env vars for LangSmith</p><p>If you’re learning, start with the first one. It’s the mental-model builder.</p><p>Here’s the trick. Convert agent.invoke(...) to agent.stream(..., stream_mode=&quot;updates&quot;). Each yield is a dict keyed by the node that just ran (model or tools), value is the state changes that node produced.</p><p>I put this behind a --trace CLI flag so normal runs stay quiet:</p><pre>def _run_streaming(agent, user_msg: str) -&gt; str:<br>    turn = 0<br>    for update in agent.stream(<br>        {&quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_msg}]},<br>        config={&quot;recursion_limit&quot;: 80},<br>        stream_mode=&quot;updates&quot;,<br>    ):<br>        for node, node_update in update.items():<br>            if node == &quot;model&quot;:<br>                turn += 1<br>                for msg in node_update.get(&quot;messages&quot;, []):<br>                    tool_calls = getattr(msg, &quot;tool_calls&quot;, None) or []<br>                    if tool_calls:<br>                        print(f&quot;─── Model turn {turn}: {len(tool_calls)} tool call(s) ───&quot;)<br>                        for tc in tool_calls:<br>                            print(f&quot;  → {tc[&#39;name&#39;]}({tc[&#39;args&#39;]})&quot;)<br>                    else:<br>                        print(f&quot;─── Model turn {turn}: FINAL ANSWER ───&quot;)<br>            elif node == &quot;tools&quot;:<br>                for msg in node_update.get(&quot;messages&quot;, []):<br>                    content = (msg.content or &quot;&quot;)[:300]<br>                    print(f&quot;      ← {msg.name}: {content}&quot;)</pre><p>Truncate tool results at 300 chars or so. JSON headline payloads are several KB and will drown the terminal.</p><p>Three things a trace teaches you quickly.</p><p><strong>Parallel tool calls are a thing.</strong> Modern LLMs batch independent tool calls into a single AI message. LangGraph runs them in parallel. When you see Model turn 1: 4 tool call(s), that&#39;s one turn issuing four calls simultaneously. Cheap and fast, and completely invisible from the output alone.</p><p><strong>Turn count is a metric.</strong> A four-step workflow that finishes in 2 turns has collapsed steps. That’s a signal, not usually a feature.</p><p><strong>Tool-call count per tool name is a metric.</strong> If your prompt says “call X for each item” and the trace shows X was called zero times, no amount of prompt tightening will fix it. That’s a structural bug, not a wording bug.</p><p>Speaking of which.</p><p>Opinion time: tracing should be the default, not the opt-in. Every agent framework I’ve used treats it as an add-on. Everyone I know who’s shipped an agent to production ended up building their own trace tool anyway. The framework should ship one out of the box.</p><h3>The bug where the agent lies with a straight face</h3><p>Ran python briefing.py --trace. Here&#39;s what I saw:</p><pre>─── Model turn 1: 4 tool call(s) ───<br>  → fetch_headlines(Technology &amp; Engineering)<br>  → fetch_headlines(Science)<br>  → fetch_headlines(Business)<br>  → fetch_headlines(Sports &amp; Entertainment)<br>      ← fetch_headlines returned (5365 chars): ...<br>      ← fetch_headlines returned (4353 chars): ...<br>      ← fetch_headlines returned (3741 chars): ...<br>      ← fetch_headlines returned (10915 chars): ...<br><br>─── Model turn 2: FINAL ANSWER (11644 chars) ───</pre><p>The model called fetch_article zero times.</p><p>Two turns and done. The prompt clearly said “For each picked story, call fetch_article(url=...).&quot; The model ignored it.</p><p>This is a class of bug: <strong>silent step omission</strong>. Cost-aware LLMs decide a step isn’t worth the effort when they think they already have enough context. From the output alone, you’d never know. The digest looked exactly like it would have if the model had read every article. It just hadn’t.</p><p>Prompt tightening rarely fixes this reliably. The model is optimizing for its own perceived reward and treats prose constraints as soft. You can escalate (“MUST call this tool, no exceptions”) and buy yourself another few runs before it starts skipping again.</p><p>Three routes to fix, in order of increasing strength:</p><ol><li><strong>Prompt harder.</strong> Fragile. Breaks on model swaps. Not recommended.</li><li><strong>Deterministic pipeline.</strong> Move the step out of the agent loop into code.</li><li><strong>Middleware or hard gate.</strong> Reject any final answer without N tool calls of the required name. Powerful but complex.</li></ol><p>For a mandatory step whose omission produces plausible-but-wrong output, option 2 wins every time.</p><h3>Agents should decide. Code should fetch.</h3><p>That’s the rule that fell out of this bug. Any step that is (a) deterministic and (b) would be silently skipped if invisible, belongs in code. Not the agent.</p><p>Here’s the refactored architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/0*5lFNI_hkYO6PPbpf" /></figure><p>Five real changes to briefing.py:</p><p><strong>1. Remove </strong><strong>fetch_article as a tool.</strong> Keep its guts as _extract_article_text, an internal Python function. The LLM no longer sees it, so it can&#39;t skip it.</p><p><strong>2. Add a new tool: </strong><strong>pick_stories(selections).</strong> This is the selector&#39;s &quot;commit&quot; step. Takes a dict {category: [3 URLs]}, validates it, stores it in module state, returns &quot;OK: ...&quot; or &quot;ERROR: ...&quot;. If validation fails (missing category, wrong count, invented URL) the LLM will retry. The return-errors-don&#39;t-raise pattern is really carrying its weight here.</p><p><strong>3. Cache headline metadata.</strong> fetch_headlines populates _headline_cache: {url → {title, source, category}}. Two consumers: pick_stories uses it to reject invented URLs; the post-selection Python loop uses it to attach metadata to each fetched body.</p><p><strong>4. Two prompts.</strong> SELECTOR_PROMPT (workflow: fetch headlines, pick 12, call pick_stories, say DONE) and WRITER_PROMPT (template plus rules; no mention of tools). Each is much shorter and does one thing well.</p><p><strong>5. The writer stage uses </strong><strong>llm.invoke() directly. No </strong><strong>create_agent.</strong> Teaching point: not every LLM call needs to be an agent. Agents are for when the LLM must <em>decide</em> between tools. When there are no tools, llm.invoke([system, user]) is simpler, cheaper, and easier to debug.</p><p>Run it with the trace flag on. Turn 1: fetch_headlines × 4. Turn 2: pick_stories. Turn 3: LLM says DONE. Then 12 Python-driven article fetches. Then one big writer call. Done.</p><p>If the selector calls pick_stories with only 1 category, our validator returns ERROR: missing categories [...] and the model self-corrects on the next turn. I actually saw this happen live in the trace. That&#39;s exactly why we return errors instead of raising.</p><h3>Google News URLs return blank pages</h3><p>First run of the two-phase pipeline printed:</p><pre>[briefing] Fetched 0/12 article bodies successfully.</pre><p>Zero out of twelve.</p><p>Every article body came back as ERROR. The writer legitimately produced &quot;Full article not available.&quot; for all 12 stories, which is exactly what the prompt told it to do on failure.</p><p>Notice something great here: the failure is now visible. Before the refactor, the same failed fetches were hidden behind fake summaries. Now they’re loud. That’s the deterministic pipeline earning its keep.</p><p>But it’s still a failure. Let me diagnose it in one line.</p><pre>python -c @&quot;<br>import httpx, trafilatura<br>url = &#39;https://news.google.com/rss/articles/CBMi...?oc=5&#39;<br>with httpx.Client(timeout=10, follow_redirects=True) as c:<br>    r = c.get(url)<br>print(&#39;final URL   :&#39;, str(r.url))<br>print(&#39;status      :&#39;, r.status_code)<br>print(&#39;body len    :&#39;, len(r.text))<br>&quot;@</pre><p>Output:</p><ul><li>Status 200</li><li>Body 576 KB</li><li><strong>Final URL is the same as the input URL.</strong> No redirect happened.</li></ul><p>Google News is a JavaScript trampoline, not an HTTP redirect chain. It returns a JS shell page that navigates client-side only. follow_redirects=True was the wrong tool. trafilatura correctly finds no article content in a Google News wrapper page.</p><p>The fix is to decode the wrapper URL to the real publisher URL before fetching. The <a href="https://pypi.org/project/googlenewsdecoder/">googlenewsdecoder</a> package does exactly that.</p><pre>pip install &quot;googlenewsdecoder&gt;=0.1.7&quot;</pre><p>Add a helper at the top of the fetch:</p><pre>from googlenewsdecoder import gnewsdecoder<br><br>def _resolve_google_news_url(/service/url: str) -&gt; str:<br>    if &quot;news.google.com/rss/articles/&quot; not in url:<br>        return url<br>    try:<br>        result = gnewsdecoder(url, interval=1)<br>    except Exception:<br>        return url<br>    if isinstance(result, dict) and result.get(&quot;status&quot;) and result.get(&quot;decoded_url&quot;):<br>        return result[&quot;decoded_url&quot;]<br>    return url<br><br>def _extract_article_text(url: str) -&gt; str:<br>    real_url = _resolve_google_news_https://medium.com/url(url)<br>    ...</pre><p>Run again:</p><pre>[briefing] Fetched 10/12 article bodies successfully.</pre><p>Ten out of twelve. The two remaining failures are publisher-side (403, JS-rendered, geoblocked) and are an acceptable long tail. The digest summaries now cite real numbers, real names, real details from the actual article bodies.</p><p>Here’s the general lesson, and it’s the one that stung the most: <strong>prove every tool works on one real input before you wire it into an agent.</strong> A single manual call to _extract_article_text(&#39;&lt;one real URL&gt;&#39;) from a REPL would have caught this on day one. When you suspect silent step omission, first run the skipped tool by hand <em>outside</em> the agent loop. Very often the answer is &quot;the tool doesn&#39;t work at all,&quot; not &quot;the agent skipped it.&quot; Silent omission is sometimes the model correctly refusing to call a broken tool.</p><h3>The code</h3><p>Everything is at <a href="http://github.com/souravb65/morning-briefing-agent">github.com/souravb65<strong>/</strong>morning-briefing-agent</a>.</p><pre>LangChainAgent/<br>├── .env.example                # Azure OpenAI credential template<br>├── .gitignore<br>├── .vscode/settings.json       # points Python interpreter at .venv<br>├── .github/<br>│   └── skills/<br>│       └── langchain-agent-debugging/<br>│           └── SKILL.md        # extendable symptom → cause → fix catalog<br>├── requirements.txt<br>├── agent.py                    # hello-world tool-calling agent<br>├── briefing.py                 # the morning briefing agent<br>└── briefings/                  # (git-ignored) daily digest outputs<br>    └── YYYY-MM-DD.md</pre><p>To run it end to end:</p><pre>.\.venv\Scripts\Activate.ps1<br>pip install -r requirements.txt<br>Copy-Item .env.example .env    # then edit .env</pre><pre>python agent.py                 # sanity check<br>python briefing.py              # produces briefings/YYYY-MM-DD.md<br>python briefing.py --trace      # same, with per-step visibility</pre><p>If you build one, I want to hear which bug bit you first. Reply here or DM me. The three I hit above are the common ones for a first agent; if you find a fourth, please tell me so I can add it to the debugging catalog.</p><p>Happy building.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc69e4c01342" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Everything you should know about NoSQL database — System Design]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/swlh/everything-you-should-know-about-nosql-database-system-design-b3716a3663cf?source=rss-6c0ab09ea1d9------2"><img src="https://cdn-images-1.medium.com/max/2234/1*fxtG9Vo7H_aQM2v-PxboCg.png" width="2234"></a></p><p class="medium-feed-snippet">It is hard to choose between relation (RDBS) or non-relational database (NoSQL) while designing a system. A fair understanding of the&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/swlh/everything-you-should-know-about-nosql-database-system-design-b3716a3663cf?source=rss-6c0ab09ea1d9------2">Continue reading on The Startup »</a></p></div>]]></description>
            <link>https://medium.com/swlh/everything-you-should-know-about-nosql-database-system-design-b3716a3663cf?source=rss-6c0ab09ea1d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3716a3663cf</guid>
            <category><![CDATA[relational-databases]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Sourav Bhattacharjee]]></dc:creator>
            <pubDate>Wed, 13 May 2020 17:53:59 GMT</pubDate>
            <atom:updated>2020-05-17T17:34:02.807Z</atom:updated>
        </item>
    </channel>
</rss>