<?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 Sanyam Sharma on Medium]]></title>
        <description><![CDATA[Stories by Sanyam Sharma on Medium]]></description>
        <link>https://medium.com/@sanyam.ss99?source=rss-4304b9beb58b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*A2g1KZELdDtrgCnsCWH7qw.jpeg</url>
            <title>Stories by Sanyam Sharma on Medium</title>
            <link>https://medium.com/@sanyam.ss99?source=rss-4304b9beb58b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 11:56:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sanyam.ss99/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[Building an LLM Debugger with Claude Code. Here’s What I Learned.]]></title>
            <link>https://medium.com/@sanyam.ss99/building-an-llm-debugger-with-claude-code-heres-what-i-learned-6fab2efc7ab0?source=rss-4304b9beb58b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fab2efc7ab0</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Sanyam Sharma]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 09:56:50 GMT</pubDate>
            <atom:updated>2026-03-15T09:56:50.431Z</atom:updated>
            <content:encoded><![CDATA[<p>I work on Jira Platform at Atlassian — scale and performance, mostly. The kind of work where you stare at p99 latency charts and argue about connection pool sizes. One question bugged me, how do retrieval systems measure if their search results are actually influencing or being utilised in RAG pipelines, or is the model hallucinating ?</p><p>Teams spend weeks tuning retrieval. Embeddings, reranking, chunking strategies, hybrid search. Then you stuff five retrieved chunks into a prompt and… hope. The LLM spits out an answer. Did it use chunk #3? Did it ignore your carefully retrieved docs entirely and hallucinate from its training data? You have no idea. Without this measure, how do you improve relevancy of your retrieval system ? So I spent some time down this rabbit hole with Claude code and built <a href="http://use-trace.com/">Trace</a> last week. <a href="https://github.com/sanyamss99/trace">github</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RFYDv1G2_nCFkLSsXyXdGw.png" /></figure><p>Existing tools like Langfuse and LangSmith will show you the prompt and the output. That’s great for knowing <em>what</em> happened. But you still don’t know <em>why</em>. Which part of your prompt actually mattered?</p><p>Tools existed, sure. But nothing that answered the question I actually cared about: “Which chunk drove the answer?” I wanted to point at a sentence in the LLM’s response and trace it back to the retrieval passage that caused it. Like git blame, but for prompts.</p><h3>The idea: attribution maps</h3><p>Here’s the insight that got me off the couch. LLM APIs can return logprobs which are basically token-level confidence scores that tell you how certain the model was about each word it generated. Most people ignore them. But if you combine logprobs with the structure of your prompt, you can score which segments of the prompt actually influenced the output.</p><p>Think of it as a heat camera for your prompt. Bright red means “this chunk drove the response.” Yellow/blank means “the model didn’t care about this part.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zK9WAruo2Genic4AwQIfnw.png" /><figcaption>Prompt Heat map</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*InTifclMLrFirw30fF8bKQ.png" /><figcaption>Completion Heat map</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SHu_NOvVcdjuKOvYWj5p7A.png" /><figcaption>Attribution of chunks in prompt (Voila !)</figcaption></figure><h3>The stack: one week, three packages</h3><p>I built the whole thing in about a week, working 2-4 hours a day after work. Thank you Claude code.</p><ul><li><strong>Python SDK</strong> (pip install usetrace): 2 runtime dependencies, one decorator to instrument your code</li><li><strong>FastAPI backend: </strong>trace ingestion, attribution engine, cost tracking</li><li><strong>React dashboard: </strong>span trees, heatmap visualizations, analytics</li></ul><p>One week means every decision got optimized for “what’s the simplest thing that works?” No clever abstractions, no future-proofing. Just make it run. And surprisingly, when you don’t have time to over-engineer, you end up with something surprisingly clean.</p><h3>The attribution algorithm</h3><p>Lets get to the core problem and its math.</p><p>The first step is figuring out the logical pieces of a prompt aka segment detection. This is rule-based, not ML. Prompts have structure and people follow conventions:</p><ol><li><strong>Chat format</strong>: Parse [system], [user], [assistant] role markers</li><li><strong>XML chunks</strong>: Match &lt;doc&gt;, &lt;context&gt;, &lt;chunk&gt; tags — common in RAG prompts</li><li><strong>Numbered lists</strong>: Detect 1. ... 2. ... patterns (need at least two to be confident)</li><li><strong>Separator-delimited</strong>: --- or === between sections</li><li><strong>Fallback</strong>: Treat the whole prompt as a single segment</li></ol><p>Once you’ve got segments, you score them across 2 core metrics: <strong>influence </strong>&amp; <strong>utilization.</strong></p><p><strong>Utilization</strong> measures lexical recall — what fraction of the output’s words appeared in this segment:</p><pre>utilization(segment) = |words(segment) ∩ words(completion)| / |words(completion)|</pre><p>Simple, but it tells you: “Did the model parrot back content from this chunk?”</p><p><strong>Influence</strong> is the interesting one. It blends two signals:</p><pre>uncertain_tokens = {t ∈ completion : logprob(t) &lt; -0.3}<br>presence = |words(segment) ∩ words(completion)| / |words(completion)|<br>overlap = |words(segment) ∩ uncertain_tokens| / |uncertain_tokens|<br>influence(segment) = 0.4 × presence + 0.6 × overlap</pre><p>The intuition: when the model was confident about a token (logprob close to 0), that token was probably coming from the model’s training data regardless of your prompt. But when it was <em>uncertain</em> (logprob below -0.3), something in the prompt was steering it. If words from your retrieval chunk show up in those uncertain tokens, that chunk actually helped.</p><p>The -0.3 threshold captures moderately uncertain tokens, not just the wild guesses. The 60/40 blend weighs the logprob signal heavier because presence alone can’t distinguish “used this chunk” from “coincidental word overlap.”</p><p>Here’s the actual function:</p><pre>def compute_influence(<br>    chunk_text: str,<br>    completion_text: str,<br>    completion_logprobs: list[dict] | list[float] | None = None,<br>) -&gt; float:<br>    chunk_tokens = _tokenize(chunk_text)<br>    completion_tokens = _tokenize(completion_text)<br>    if not completion_tokens:<br>        return 0.0<br><br>    presence = len(chunk_tokens &amp; completion_tokens) / len(completion_tokens)<br>    if not completion_logprobs:<br>        return presence<br><br>    uncertain = [<br>        (_clean_token(str(e.get(&quot;token&quot;, &quot;&quot;))), abs(float(e[&quot;logprob&quot;])))<br>        for e in completion_logprobs<br>        if float(e[&quot;logprob&quot;]) &lt; _UNCERTAIN_LOGPROB_THRESHOLD<br>    ]<br>    if not uncertain:<br>        return presence<br><br>    total_weight = sum(w for _, w in uncertain)<br>    overlap_weight = sum(w for tok, w in uncertain if tok in chunk_tokens)<br>    logprob_score = overlap_weight / total_weight<br><br>    return 0.4 * presence + 0.6 * logprob_score</pre><p>Rule-based beats ML here. Deterministic, fast, debuggable, no training set. Prompts follow patterns, therefore we don’t need embeddings to find XML tags.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pm4w3uq0nm8iEFR9_WfqPQ.png" /><figcaption><em>The attribution pipeline. Segment detection is rule-based regex. Scoring blends lexical overlap with logprob-weighted uncertainty.</em></figcaption></figure><h3>Invisible tracing and the joy of keeping it light</h3><p>The SDK was the part I had the most fun with. The constraint: adding tracing to your LLM app should feel like adding a decorator, not adopting a framework.</p><p>pip install usetrace pulls in exactly two dependencies: pydantic (data validation) and httpx (HTTP client). Everything else is stdlib. contextvars for async-safe span nesting. queue.SimpleQueue for lock-free buffering. threading for the flush worker. Installs in under two seconds. Works in any Python environment.</p><p>I’m personally allergic to SDKs that bring the kitchen sink. Every dependency is a potential version conflict, a security surface, a thing that breaks on some edge-case Python version. Two deps felt right.</p><p><strong>Duck-typing for vendor support</strong> was the trick that made the SDK work across providers. The SDK supports OpenAI, Anthropic, Gemini, Ollama, Together, and xAI — without importing any of them. Pure getattr() probing.</p><p>Held together with getattr and vibes? Kind of. But it means zero vendor lock-in for users, zero import errors, and adding a new provider is just figuring out where they put .content on their response object. Most importantly <strong><em>minimal dependencies.</em></strong></p><p><strong>The transport layer is fire-and-forget.</strong> A memory-bounded SimpleQueue (10MB cap) feeds a daemon thread that batches spans and POSTs them to the backend. If the queue fills up, spans get silently dropped. If the network is down, it retries once and moves on. All errors are logged at DEBUG level — your production app never knows tracing exists.</p><p>I chose a daemon thread over asyncio for the flush worker. The SDK instruments both sync and async code . If the flush mechanism itself were async, you’d need an event loop running, which isn’t guaranteed in sync apps. Sometimes boring technology is the right technology.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vDk5nwsJde_pKbYf25yJDA.png" /></figure><h3>The full picture, rapid-fire</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-uRCfC5NiaVZBtl3u5L3vg.png" /></figure><h3>Building with Claude Code</h3><p>There’s a meta angle here I can’t ignore. I used an LLM tool to build an LLM debugging tool.</p><p>Claude Code changed how I worked on this project. My role shifted from writing code to directing and reviewing. I’d describe what I wanted — “build the ingestion endpoint, here are the schemas” — and CC would generate the route, the service layer, the DAL queries, the tests. I could focus my energy on the hard problems: designing the attribution algorithm, getting the transport layer right, making architectural decisions. The boilerplate — routes, CRUD, Pydantic schemas, test scaffolding — that all moved way faster than I could’ve typed it.</p><p>But here’s the thing nobody talks about in the “AI tools are amazing” posts. CC compounds mistakes. If I didn’t catch a wrong design decision early — say, a bad data model or a flawed abstraction — CC would build on top of it with complete confidence. By the time I noticed something was off, there’d be three layers of code built on a flawed foundation. Restructuring back was painful for both of us: high effort for CC to rewrite, high effort for me to re-review every change.</p><p>Early course correction is everything. You have to stay sharp on architecture even when the code is writing itself. Especially when the code is writing itself. The skill isn’t prompting — it’s catching bad decisions before they spread.</p><p><strong>Duck-typing is underrated.</strong> Those getattr() chains are ugly. I know. But they let you support an entire ecosystem of LLM providers without coupling to any of them. Not a single vendor import in the SDK.</p><p><strong>Rule-based beats ML when you can enumerate patterns.</strong> Prompts have structure — role markers, XML tags, numbered lists. You don’t need a classifier to detect them. Regex is fast, deterministic, and debuggable. Save the ML for problems where you genuinely can’t enumerate the cases.</p><p><strong>The best observability is invisible.</strong> If your tracing SDK blocks the hot path, has 10 dependencies, or requires wrapping every function in a context manager — nobody will use it. One decorator. Two dependencies. Fire-and-forget transport. That’s the bar.</p><p><strong>Observability tools must choose a side: your app or the data.</strong> The SDK buffers spans in a 10 MB capped queue. If spans arrive faster than the network can ship them, new ones get silently dropped — no backpressure, no exceptions in your code. When the burst passes, the buffer drains and self-corrects. You lose some traces during pressure. That’s the right tradeoff — an observability tool that degrades your production app has its priorities backwards.</p><h3>Try it</h3><p>Trace is open source.</p><p>pip install usetrace. <a href="https://github.com/sanyamsharma/trace">GitHub</a>.</p><p><em>A single trace. Nested spans, timing, cost, the full picture of one LLM call.</em></p><p>If you’re building RAG and you want to know whether your retrieval actually matters — whether those carefully ranked chunks are being used or just taking up context window — give it a shot.</p><p>I’m Sanyam. I build things when I’m curious about the answer. Find me on <a href="https://www.linkedin.com/in/sanyamss99">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fab2efc7ab0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>