<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://dlrudqls99.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://dlrudqls99.github.io/" rel="alternate" type="text/html" /><updated>2026-11-28T13:59:57+00:00</updated><id>https://dlrudqls99.github.io/feed.xml</id><title type="html">Kyungbin’s Notes</title><subtitle>A personal knowledge base on software engineering, AI agents, and the practical details of shipping things.</subtitle><author><name>Kyungbin Lee</name></author><entry><title type="html">Start With the Customer: Solution Design From a Brief</title><link href="https://dlrudqls99.github.io/ai-agents/start-with-the-customer-solution-design-from-a-brief/" rel="alternate" type="text/html" title="Start With the Customer: Solution Design From a Brief" /><published>2026-11-28T00:00:00+00:00</published><updated>2026-11-28T00:00:00+00:00</updated><id>https://dlrudqls99.github.io/ai-agents/start-with-the-customer-solution-design-from-a-brief</id><content type="html" xml:base="https://dlrudqls99.github.io/ai-agents/start-with-the-customer-solution-design-from-a-brief/"><![CDATA[<p>I used to start every design problem the same way: someone gives me a brief, and I start drawing boxes. Database here, API there, maybe a vector store if it sounds like a RAG problem.</p>

<p>It felt productive. It was backwards. The short version: a brief is not a spec, so ask who it is for, what success is in a number, what constraint could kill the design, and who owns it after you leave — before any architecture.</p>

<p>A brief is a sentence someone wrote in a hurry, about a problem they feel more than they can describe. If I jump straight to architecture, I solve the sentence, not the problem. The sentence is usually wrong in at least one important way.</p>

<p>I learned this the slow way. A customer “wants an AI system that reads their documents and answers questions,” and I answered with an architecture before asking a single question.</p>

<p>The architecture was fine. The answer was still wrong, because I had no idea what “works” meant to them.</p>

<p>I keep a short list now. I write it down before a design discussion, so I do not skip it under pressure.</p>

<h2 id="forty-answers-a-day-is-not-one-exact-answer-a-month">Forty answers a day is not one exact answer a month</h2>

<p>First: who is this for, and what do they actually do today? Not “the use case” in the abstract — what a person does on a Tuesday afternoon, and where it hurts.</p>

<p>A support agent answering the same question forty times a day has a different problem from a compliance officer who needs one answer a month to be exactly right. Same brief. Completely different system.</p>

<h2 id="faster-is-not-a-success-metric">“Faster” is not a success metric</h2>

<p>Second: what does success look like, in a number? “Faster” is not a number.</p>

<p>“Answer in under five seconds, correct 95% of the time, and cut escalations by a third” is a number. It changes the design.</p>

<p>If the customer cannot give a number yet, that is fine. Then the first deliverable is finding the number, not building the system.</p>

<p>I once built something technically good, and nobody could tell whether it helped. We had never agreed on what “helped” meant.</p>

<h2 id="one-constraint-can-rule-out-half-the-architectures">One constraint can rule out half the architectures</h2>

<p>Third: what are the constraints that will actually decide the design? I used to treat this as an afterthought.</p>

<p>Where does the data live, and can it leave that place? Who is allowed to see the answers? How much can it cost per request?</p>

<p>And what happens when the system is wrong? Is a wrong answer annoying, or is it a compliance incident?</p>

<p>The answer to “can the data leave the building” can rule out half the architectures before you start. I would rather find that out in minute ten than in week six.</p>

<h2 id="a-system-nobody-owns-after-handover-is-not-finished">A system nobody owns after handover is not finished</h2>

<p>Fourth: who decides, and what happens after I leave? A system that only works while I am in the room is not a delivered system.</p>

<p>Who owns it? Who maintains the eval set? Who gets paged when it breaks?</p>

<p>If those questions have no answer, the design is not finished. It does not matter how clean the diagram looks.</p>

<h2 id="the-discovery-answers-do-most-of-the-designing">The discovery answers do most of the designing</h2>

<p>Only after those questions do I draw boxes. The drawing gets easier, because the answers do most of the deciding.</p>

<p>If the data cannot leave the customer’s network, you are looking at on-prem or VPC deployment. That rules out a whole class of managed services.</p>

<p>If the answers need citations, retrieval is not optional. You need to think about chunking and evaluation from day one.</p>

<p>If the pain is volume — hundreds of near-identical questions — caching and a small model might beat a big model with a fancy pipeline. If the pain is accuracy on rare, high-stakes questions, you spend the effort on evaluation and human review instead.</p>

<p>My rule: no architecture before I can write down the user, the success metric, and the one constraint that would kill the design. If I cannot write those three things down, I am not ready to design. I am still guessing.</p>

<p>One smaller habit helps: write the brief back to the customer in my own words before proposing anything. “Here is what I heard you need, here is what success looks like, here is what I am assuming.”</p>

<p>It takes five minutes, and it catches misunderstandings while they are still cheap. People correct you generously at this stage — much less generously after you have built the wrong thing.</p>

<h2 id="the-checklist-took-fifteen-minutes">The checklist took fifteen minutes</h2>

<p>What I tried this week: take a one-line brief — “build an AI assistant that answers questions about our product docs” — and turn it into a structured checklist with a tiny script. The point is not the code. The point is refusing to design from one sentence.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># brief_checklist.py — turn a vague brief into discovery questions
# before any architecture. Fill in what you know; the gaps are the work.
</span>
<span class="n">BRIEF</span> <span class="o">=</span> <span class="s">"Build an AI assistant that answers questions about our product docs."</span>

<span class="c1"># Four groups. Each question gets an answer, or the string "unknown".
</span><span class="n">DISCOVERY</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s">"user_and_workflow"</span><span class="p">:</span> <span class="p">[</span>
        <span class="s">"Who asks the questions, and how often?"</span><span class="p">,</span>
        <span class="s">"What do they do today when they cannot find the answer?"</span><span class="p">,</span>
        <span class="s">"Where does the pain actually show up — time, errors, escalations?"</span><span class="p">,</span>
    <span class="p">],</span>
    <span class="s">"success_metric"</span><span class="p">:</span> <span class="p">[</span>
        <span class="s">"What number would make this project a success?"</span><span class="p">,</span>
        <span class="s">"How will we measure it — and how often?"</span><span class="p">,</span>
        <span class="s">"What is good enough for version one?"</span><span class="p">,</span>
    <span class="p">],</span>
    <span class="s">"constraints"</span><span class="p">:</span> <span class="p">[</span>
        <span class="s">"Where does the data live? Can it leave that network?"</span><span class="p">,</span>
        <span class="s">"Who may see the answers? Any PII or regulated content?"</span><span class="p">,</span>
        <span class="s">"What is the cost budget per question? Latency budget?"</span><span class="p">,</span>
        <span class="s">"What happens when the system gives a wrong answer?"</span><span class="p">,</span>
    <span class="p">],</span>
    <span class="s">"ownership"</span><span class="p">:</span> <span class="p">[</span>
        <span class="s">"Who owns this after handover?"</span><span class="p">,</span>
        <span class="s">"Who maintains the eval set and reviews failures?"</span><span class="p">,</span>
        <span class="s">"Who gets paged when it breaks?"</span><span class="p">,</span>
    <span class="p">],</span>
<span class="p">}</span>

<span class="n">ANSWERS</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s">"user_and_workflow"</span><span class="p">:</span> <span class="p">[</span><span class="s">"unknown"</span><span class="p">,</span> <span class="s">"unknown"</span><span class="p">,</span> <span class="s">"unknown"</span><span class="p">],</span>
    <span class="s">"success_metric"</span><span class="p">:</span> <span class="p">[</span><span class="s">"unknown"</span><span class="p">,</span> <span class="s">"unknown"</span><span class="p">,</span> <span class="s">"unknown"</span><span class="p">],</span>
    <span class="s">"constraints"</span><span class="p">:</span> <span class="p">[</span><span class="s">"unknown"</span><span class="p">,</span> <span class="s">"unknown"</span><span class="p">,</span> <span class="s">"unknown"</span><span class="p">,</span> <span class="s">"unknown"</span><span class="p">],</span>
    <span class="s">"ownership"</span><span class="p">:</span> <span class="p">[</span><span class="s">"unknown"</span><span class="p">,</span> <span class="s">"unknown"</span><span class="p">,</span> <span class="s">"unknown"</span><span class="p">],</span>
<span class="p">}</span>


<span class="k">def</span> <span class="nf">report</span><span class="p">(</span><span class="n">answers</span><span class="p">):</span>
    <span class="s">"""Print what we know, and count what we still need to find out."""</span>
    <span class="n">total_unknown</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">for</span> <span class="n">group</span><span class="p">,</span> <span class="n">questions</span> <span class="ow">in</span> <span class="n">DISCOVERY</span><span class="p">.</span><span class="n">items</span><span class="p">():</span>
        <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"</span><span class="se">\n</span><span class="s">[</span><span class="si">{</span><span class="n">group</span><span class="si">}</span><span class="s">]"</span><span class="p">)</span>
        <span class="k">for</span> <span class="n">q</span><span class="p">,</span> <span class="n">a</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">questions</span><span class="p">,</span> <span class="n">answers</span><span class="p">[</span><span class="n">group</span><span class="p">]):</span>
            <span class="n">mark</span> <span class="o">=</span> <span class="s">"OK "</span> <span class="k">if</span> <span class="n">a</span> <span class="o">!=</span> <span class="s">"unknown"</span> <span class="k">else</span> <span class="s">"?? "</span>
            <span class="k">if</span> <span class="n">a</span> <span class="o">==</span> <span class="s">"unknown"</span><span class="p">:</span>
                <span class="n">total_unknown</span> <span class="o">+=</span> <span class="mi">1</span>
            <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"  </span><span class="si">{</span><span class="n">mark</span><span class="si">}{</span><span class="n">q</span><span class="si">}</span><span class="s"> -&gt; </span><span class="si">{</span><span class="n">a</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>
    <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"</span><span class="se">\n</span><span class="si">{</span><span class="n">total_unknown</span><span class="si">}</span><span class="s"> questions still unanswered."</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">total_unknown</span><span class="p">:</span>
        <span class="k">print</span><span class="p">(</span><span class="s">"Do not design yet. Go ask."</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">print</span><span class="p">(</span><span class="s">"Ready to sketch the architecture."</span><span class="p">)</span>


<span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s">"__main__"</span><span class="p">:</span>
    <span class="n">report</span><span class="p">(</span><span class="n">ANSWERS</span><span class="p">)</span>
</code></pre></div></div>

<p>Run it with everything marked “unknown” and it says the honest thing: do not design yet.</p>

<p>Fill in a few answers — the docs cannot leave the customer’s network, and a wrong answer is a compliance problem — and the architecture starts to narrow itself.</p>

<p>The checklist is not bureaucracy. It is what stops you building a cloud RAG system for a customer whose data is not allowed to leave the building.</p>

<h2 id="what-i-took-away">What I took away</h2>

<p>No box until I can write down the user, the metric, and the one constraint that matters most.
I write the brief back in my own words before I propose anything.
If I cannot answer those, I am still guessing.</p>]]></content><author><name>Kyungbin Lee</name></author><category term="ai-agents" /><category term="solution-design" /><category term="discovery" /><category term="fde" /><category term="system-design" /><summary type="html"><![CDATA[I used to start every design problem the same way: someone gives me a brief, and I start drawing boxes. Database here, API there, maybe a vector store if it sounds like a RAG problem.]]></summary></entry><entry><title type="html">Operating LLMs in Production: Latency, Limits, and Retries</title><link href="https://dlrudqls99.github.io/ai-agents/operating-llms-in-production/" rel="alternate" type="text/html" title="Operating LLMs in Production: Latency, Limits, and Retries" /><published>2026-11-25T00:00:00+00:00</published><updated>2026-11-25T00:00:00+00:00</updated><id>https://dlrudqls99.github.io/ai-agents/operating-llms-in-production</id><content type="html" xml:base="https://dlrudqls99.github.io/ai-agents/operating-llms-in-production/"><![CDATA[<p>The demo worked. That is the easy part.</p>

<p>It ran on my laptop, with one user, no rate limits, and nobody watching the clock. Production is a different job. The short version: measure latency in pieces, design for rate limits, retry with backoff and jitter, cache what you can, and fail honestly when the model is gone.</p>

<h2 id="an-eight-second-request-has-four-different-fixes">An eight-second request has four different fixes</h2>

<p>Latency is not one number. A request that takes eight seconds could be slow for four different reasons, and each one has a different fix.</p>

<p>Time to first token (TTFT) is how long until the user sees anything. It is what makes a system feel fast or slow. Time per output token (TPOT) is how fast the rest of the answer streams in.</p>

<p>Then there is everything before the model starts: the request sitting in a queue, the retrieval step in a RAG system, the tools being called. Log TTFT, TPOT, retrieval time, and queue time separately.</p>

<p>If TTFT is the problem, the prompt may be too long, or the first token is waiting on slow retrieval. If TPOT is the problem, the model is generating a lot of tokens, and the answer should probably be shorter.</p>

<p>If the queue is the problem, you do not have a model problem. You have a capacity problem.</p>

<p>Long prompts hurt twice. They cost more, and they slow the first token, because the model has to process the whole prompt before it can say anything.</p>

<p>That is the argument for tight retrieval. Send the model the three passages it needs, not the twenty it might need.</p>

<h2 id="a-429-is-a-speed-limit-not-an-error">A 429 is a speed limit, not an error</h2>

<p>Every LLM API has limits — requests per minute, tokens per minute — and you will hit them. A 429 is not something going wrong. It is the API telling you exactly how fast you are allowed to go.</p>

<p>The model that clicked for me is a token bucket. The bucket refills at a fixed rate, and every request takes tokens out of it.</p>

<p>A short request costs a little. A long one costs a lot. When the bucket is empty, you wait.</p>

<p>So design for the limit. Queue requests instead of firing them all at once. Track usage, so you know you are close before you hit it.</p>

<p>And when you get a 429, respect the Retry-After header. Do not hammer the API again immediately.</p>

<p>That sounds obvious. I have still done the wrong thing in code more than once.</p>

<h2 id="instant-retries-make-an-overload-worse">Instant retries make an overload worse</h2>

<p>The naive retry is “try again, right away, three times.” If the API is overloaded, three clients retrying instantly make it more overloaded. That is the thundering herd problem, and it is embarrassingly easy to cause by accident.</p>

<p>What works is exponential backoff with jitter. Wait a second, then two, then four — and add a random bit, so not everyone retries at the same moment.</p>

<p>The jitter is the part I used to skip. Without it, a hundred clients that failed together retry together. You get the same spike, just delayed.</p>

<p>Some requests should not be retried at all. A 400 means your request is wrong. Retrying it will not help.</p>

<p>The scary case is a request that went through but timed out on the way back. Retrying it might run the same operation twice. A retried request could double-charge something.</p>

<p>That is why idempotency keys matter. If an operation has a side effect, give it a key. The server can then tell a retry from a new request.</p>

<h2 id="caching-and-batching-are-the-cheapest-speedups">Caching and batching are the cheapest speedups</h2>

<p>Not every request needs to hit the model. If users keep asking the same question, cache the answer.</p>

<p>Some APIs also cache the prompt itself. If you send the same long system prompt every time, the provider may only charge you for processing it once.</p>

<p>I kept putting these off because they felt unglamorous. They are the cheapest way to make a system faster and cheaper at the same time.</p>

<p>Batching is the same idea on the other side. Fifty small jobs sent one at a time mean fifty round trips. Group them, or use a batch API where the provider offers one, and the overhead drops.</p>

<p>The tradeoff is latency for individual requests. Batching is great for background jobs. It is bad for a user waiting on a screen.</p>

<h2 id="a-system-that-fails-honestly-beats-one-that-hangs">A system that fails honestly beats one that hangs</h2>

<p>Guardrails are the checks around the model: input filters for things like prompt injection, output checks for disallowed content or PII, and validation that the output is in the format you asked for.</p>

<p>I used to think of these as a security topic. In production they are an operations topic. They are what stands between a weird input and a bad outcome a user sees.</p>

<p>Graceful degradation is the plan for when the model is unavailable or too slow. Fall back to a smaller, cheaper model for non-critical requests. Serve a cached answer when the question has been seen before.</p>

<p>Return a partial answer with a note that it is incomplete, instead of nothing at all. And sometimes say “I cannot do that right now,” clearly, instead of timing out silently after thirty seconds.</p>

<p>Users can work with “unavailable right now.” They cannot work with a spinner that never ends.</p>

<h2 id="the-retry-wrapper-took-twenty-minutes">The retry wrapper took twenty minutes</h2>

<p>What I built this week: a wrapper around an LLM call that retries with exponential backoff and jitter, logs the timing of each attempt, and gives up cleanly instead of hanging. It is small. It is also the kind of code I would want in production.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># llm_client.py — a retry wrapper with backoff, jitter, and timing
# Replace `call_model` with your real API call.
</span>
<span class="kn">import</span> <span class="nn">random</span>
<span class="kn">import</span> <span class="nn">time</span>


<span class="k">def</span> <span class="nf">call_model</span><span class="p">(</span><span class="n">prompt</span><span class="p">):</span>
    <span class="s">"""Stand-in for a real LLM API call. Raise on failure."""</span>
    <span class="k">raise</span> <span class="nb">NotImplementedError</span><span class="p">(</span><span class="s">"wire this up to your provider"</span><span class="p">)</span>


<span class="k">def</span> <span class="nf">timed_call</span><span class="p">(</span><span class="n">prompt</span><span class="p">,</span> <span class="n">max_retries</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">base_delay</span><span class="o">=</span><span class="mf">1.0</span><span class="p">):</span>
    <span class="s">"""Call the model, retrying rate-limit / transient errors
    with exponential backoff and jitter. Never retry a bad request."""</span>
    <span class="n">attempt</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">while</span> <span class="bp">True</span><span class="p">:</span>
        <span class="n">started</span> <span class="o">=</span> <span class="n">time</span><span class="p">.</span><span class="n">monotonic</span><span class="p">()</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">answer</span> <span class="o">=</span> <span class="n">call_model</span><span class="p">(</span><span class="n">prompt</span><span class="p">)</span>
            <span class="n">elapsed</span> <span class="o">=</span> <span class="n">time</span><span class="p">.</span><span class="n">monotonic</span><span class="p">()</span> <span class="o">-</span> <span class="n">started</span>
            <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"ok in </span><span class="si">{</span><span class="n">elapsed</span><span class="si">:</span><span class="p">.</span><span class="mi">2</span><span class="n">f</span><span class="si">}</span><span class="s">s (attempt </span><span class="si">{</span><span class="n">attempt</span> <span class="o">+</span> <span class="mi">1</span><span class="si">}</span><span class="s">)"</span><span class="p">)</span>
            <span class="k">return</span> <span class="n">answer</span>
        <span class="k">except</span> <span class="nb">Exception</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
            <span class="n">elapsed</span> <span class="o">=</span> <span class="n">time</span><span class="p">.</span><span class="n">monotonic</span><span class="p">()</span> <span class="o">-</span> <span class="n">started</span>
            <span class="c1"># In real code, check the status code: retry 429/5xx,
</span>            <span class="c1"># never retry 400.
</span>            <span class="n">retryable</span> <span class="o">=</span> <span class="s">"rate limit"</span> <span class="ow">in</span> <span class="nb">str</span><span class="p">(</span><span class="n">e</span><span class="p">).</span><span class="n">lower</span><span class="p">()</span> <span class="ow">or</span> <span class="s">"429"</span> <span class="ow">in</span> <span class="nb">str</span><span class="p">(</span><span class="n">e</span><span class="p">)</span>
            <span class="n">attempt</span> <span class="o">+=</span> <span class="mi">1</span>
            <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"attempt </span><span class="si">{</span><span class="n">attempt</span><span class="si">}</span><span class="s"> failed after </span><span class="si">{</span><span class="n">elapsed</span><span class="si">:</span><span class="p">.</span><span class="mi">2</span><span class="n">f</span><span class="si">}</span><span class="s">s: </span><span class="si">{</span><span class="n">e</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>
            <span class="k">if</span> <span class="ow">not</span> <span class="n">retryable</span> <span class="ow">or</span> <span class="n">attempt</span> <span class="o">&gt;</span> <span class="n">max_retries</span><span class="p">:</span>
                <span class="k">raise</span>
            <span class="n">delay</span> <span class="o">=</span> <span class="n">base_delay</span> <span class="o">*</span> <span class="p">(</span><span class="mi">2</span> <span class="o">**</span> <span class="p">(</span><span class="n">attempt</span> <span class="o">-</span> <span class="mi">1</span><span class="p">))</span>
            <span class="n">delay</span> <span class="o">+=</span> <span class="n">random</span><span class="p">.</span><span class="n">uniform</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">delay</span> <span class="o">*</span> <span class="mf">0.5</span><span class="p">)</span>  <span class="c1"># jitter
</span>            <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"waiting </span><span class="si">{</span><span class="n">delay</span><span class="si">:</span><span class="p">.</span><span class="mi">2</span><span class="n">f</span><span class="si">}</span><span class="s">s before retry..."</span><span class="p">)</span>
            <span class="n">time</span><span class="p">.</span><span class="n">sleep</span><span class="p">(</span><span class="n">delay</span><span class="p">)</span>


<span class="c1"># A cheap guardrail for the other side of the call:
# fail fast on an empty or absurdly long prompt before spending money.
</span><span class="k">def</span> <span class="nf">validate_prompt</span><span class="p">(</span><span class="n">prompt</span><span class="p">,</span> <span class="n">max_chars</span><span class="o">=</span><span class="mi">8000</span><span class="p">):</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">prompt</span><span class="p">.</span><span class="n">strip</span><span class="p">():</span>
        <span class="k">raise</span> <span class="nb">ValueError</span><span class="p">(</span><span class="s">"empty prompt — nothing to send"</span><span class="p">)</span>
    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">prompt</span><span class="p">)</span> <span class="o">&gt;</span> <span class="n">max_chars</span><span class="p">:</span>
        <span class="k">raise</span> <span class="nb">ValueError</span><span class="p">(</span><span class="sa">f</span><span class="s">"prompt too long (</span><span class="si">{</span><span class="nb">len</span><span class="p">(</span><span class="n">prompt</span><span class="p">)</span><span class="si">}</span><span class="s"> chars), trim retrieval first"</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">prompt</span>


<span class="c1"># try:
#     answer = timed_call(validate_prompt("Explain backoff in one sentence."))
#     print(answer)
# except Exception as e:
#     print(f"gave up cleanly: {e}")
#     # Fallback here: cached answer, smaller model, or an honest error.
</span></code></pre></div></div>

<p>Two things stuck with me. The jitter line is one line of code, and it is the difference between a retry storm and a polite queue.</p>

<p>The “gave up cleanly” branch matters as much as the retry logic. A wrapper that retries forever is just a slower way to fail.</p>

<h2 id="what-i-took-away">What I took away</h2>

<p>Measure latency in pieces, not as one number.
Retry with backoff and jitter, and never retry a bad request.
Cache what I can, and plan for the day the model is not there.</p>]]></content><author><name>Kyungbin Lee</name></author><category term="ai-agents" /><category term="llm" /><category term="production" /><category term="latency" /><category term="reliability" /><summary type="html"><![CDATA[The demo worked. That is the easy part.]]></summary></entry><entry><title type="html">How Do You Know Your AI System Is Working?</title><link href="https://dlrudqls99.github.io/ai-agents/how-do-you-know-your-ai-system-is-working/" rel="alternate" type="text/html" title="How Do You Know Your AI System Is Working?" /><published>2026-11-22T00:00:00+00:00</published><updated>2026-11-22T00:00:00+00:00</updated><id>https://dlrudqls99.github.io/ai-agents/how-do-you-know-your-ai-system-is-working</id><content type="html" xml:base="https://dlrudqls99.github.io/ai-agents/how-do-you-know-your-ai-system-is-working/"><![CDATA[<p>Someone asked me how I know my RAG system is actually working. My honest answer was: vibes. I had tried a few questions by hand, and the answers looked right.</p>

<p>That is not evidence. So I spent a week learning how evaluation works for LLM systems. The short version: build a small test set before you need one, measure more than one thing, and never trust a single number.</p>

<h2 id="start-with-20-golden-questions-not-a-metric">Start with 20 golden questions, not a metric</h2>

<p>My first mistake was reaching for metrics. Accuracy of what, against which questions? The metric is the easy part. The questions are the work.</p>

<p>A golden set is a list of questions with the right answers — or at least the documents that should back each answer. Twenty is enough to start. I pulled mine from real logs, plus edge cases I knew were tricky, like questions with no answer in the documents.</p>

<p>The edge cases matter most. A system that hallucinates confidently, when it should say “I don’t know,” is worse than one that simply gets things wrong.</p>

<p>Writing the set forced a decision I had never written down: what does “good” mean for each question? Is a short answer fine, or do users need the full context? The eval set became a specification I did not know I was missing.</p>

<h2 id="run-the-eval-on-every-change-not-once-before-shipping">Run the eval on every change, not once before shipping</h2>

<p>I had this backwards. I treated evaluation like a final exam: do it once, then ship. It is a smoke alarm — it has to keep running, because the system keeps changing. New documents, new prompts, a new model version.</p>

<p>So the shape of it is a loop:</p>

<ol>
  <li><strong>Collect</strong> real traffic — actual user questions, anonymized, failures included.</li>
  <li><strong>Label</strong> a small slice by hand, and let the automatic checks handle the rest.</li>
  <li><strong>Measure</strong> on every change, and fail the change if the numbers drop. If a prompt tweak drops faithfulness by five points, it does not ship.</li>
  <li><strong>Review</strong> the failures by hand and sort them into types: retrieval misses, grounding failures, bad questions, stale documents. The categories tell you what to fix next, instead of just “make it better.”</li>
  <li><strong>Grow</strong> the golden set from the failures. Every real failure becomes a test case, so it can never come back silently.</li>
</ol>

<p>That last step is my favorite. The eval set is not a fixed exam. It is a memory of every mistake the system has made.</p>

<h2 id="two-scores-matter-most-recall-and-faithfulness">Two scores matter most: recall and faithfulness</h2>

<p>For retrieval, one number comes first: recall@k. Is the right document in the top k results? If the right document is never retrieved, nothing downstream can save the answer.</p>

<p>For the answer itself, I watch faithfulness. Break the answer into claims and check each claim against the source documents. A claim with no support is a hallucination, even if it sounds right. Especially if it sounds right.</p>

<p>The second score is answer relevance: does it answer the question that was asked? A faithful answer can still be useless. I have seen my system quote a perfectly accurate paragraph that had nothing to do with what the user wanted.</p>

<p>The cheap metrics — exact match, ROUGE, token overlap — I use only as a smoke test. For free-form answers they punish good paraphrases and reward copying. They are not the verdict.</p>

<h2 id="let-a-model-grade-after-humans-check-the-grading">Let a model grade, after humans check the grading</h2>

<p>An LLM judge is simple: a strong model grades my system’s answers, given the question, the source documents, and a rubric. I was suspicious of it at first. It felt circular — the thing grading itself.</p>

<p>The risks are real. The judge can share the system’s blind spots. It also likes long, fluent answers, even when they are wrong.</p>

<p>The alternative is worse. Human grading is the gold standard, but it is slow and expensive, and I cannot rerun it every time I change a prompt. The judge runs the whole set in minutes, so I actually run it. An imperfect metric you run every day beats a perfect one you run twice a year.</p>

<p>Two safeguards keep the judge honest. First, a rubric with examples of each score, not just “rate this 1 to 5.” Second, calibration: grade a small sample by hand first, and if the judge disagrees with people a lot, fix the rubric, not the system.</p>

<p>Humans still get the last word. Tone, real helpfulness, whether a domain expert would trust the answer — only a person can judge those. I grade in small batches: ten answers, two reviewers, three words — correct, grounded, helpful.</p>

<p>People also catch what no metric looks for. The answer that is right but uses a term users never use. The one grounded in a document that is itself out of date. The high-stakes questions always get human eyes.</p>

<h2 id="five-numbers-are-enough-for-a-dashboard">Five numbers are enough for a dashboard</h2>

<p>In production, I would watch five things: faithfulness rate, retrieval recall@k, the share of questions answered versus declined, user feedback rate, and latency and cost per query. A perfect answer that takes thirty seconds and costs a dollar is not a product.</p>

<p>The answered-versus-declined share matters more than it looks. A system that never says “I don’t know” is lying some of the time.</p>

<p>No single number tells the story. The signal is one number moving while the others stay still. Faithfulness drops but recall is fine? The generator is the problem, not retrieval. Recall drops but everything else is steady? Something changed in the documents.</p>

<h2 id="the-harness-took-fifteen-minutes">The harness took fifteen minutes</h2>

<p>What I actually built this week: ten questions, the document each one should come from, and a simple scorer that checks whether the answer mentions the key facts. It is not a real judge — it is a stand-in. But once the harness exists, swapping in a better scorer is easy.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># eval_harness.py — a tiny eval loop you can grow
# Score each answer against the facts it should contain.
</span>
<span class="n">EVAL_SET</span> <span class="o">=</span> <span class="p">[</span>
    <span class="p">{</span>
        <span class="s">"question"</span><span class="p">:</span> <span class="s">"How do I reset the QA inspection flow?"</span><span class="p">,</span>
        <span class="s">"expected_doc"</span><span class="p">:</span> <span class="s">"doc_qa_reset"</span><span class="p">,</span>
        <span class="s">"must_mention"</span><span class="p">:</span> <span class="p">[</span><span class="s">"reset"</span><span class="p">,</span> <span class="s">"inspection"</span><span class="p">],</span>
    <span class="p">},</span>
    <span class="p">{</span>
        <span class="s">"question"</span><span class="p">:</span> <span class="s">"What is the tolerance for the alignment step?"</span><span class="p">,</span>
        <span class="s">"expected_doc"</span><span class="p">:</span> <span class="s">"doc_alignment_spec"</span><span class="p">,</span>
        <span class="s">"must_mention"</span><span class="p">:</span> <span class="p">[</span><span class="s">"0.05"</span><span class="p">,</span> <span class="s">"mm"</span><span class="p">],</span>
    <span class="p">},</span>
    <span class="c1"># ... add 8 more from your own logs, including
</span>    <span class="c1"># at least one question with no answer in the docs.
</span><span class="p">]</span>

<span class="k">def</span> <span class="nf">score_answer</span><span class="p">(</span><span class="n">answer</span><span class="p">,</span> <span class="n">must_mention</span><span class="p">):</span>
    <span class="s">"""Crude but honest: does the answer contain the key facts?"""</span>
    <span class="n">found</span> <span class="o">=</span> <span class="p">[</span><span class="n">fact</span> <span class="k">for</span> <span class="n">fact</span> <span class="ow">in</span> <span class="n">must_mention</span> <span class="k">if</span> <span class="n">fact</span><span class="p">.</span><span class="n">lower</span><span class="p">()</span> <span class="ow">in</span> <span class="n">answer</span><span class="p">.</span><span class="n">lower</span><span class="p">()]</span>
    <span class="k">return</span> <span class="nb">len</span><span class="p">(</span><span class="n">found</span><span class="p">)</span> <span class="o">/</span> <span class="nb">len</span><span class="p">(</span><span class="n">must_mention</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">run_eval</span><span class="p">(</span><span class="n">answer_fn</span><span class="p">):</span>
    <span class="n">scores</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">for</span> <span class="n">case</span> <span class="ow">in</span> <span class="n">EVAL_SET</span><span class="p">:</span>
        <span class="n">answer</span> <span class="o">=</span> <span class="n">answer_fn</span><span class="p">(</span><span class="n">case</span><span class="p">[</span><span class="s">"question"</span><span class="p">])</span>
        <span class="n">score</span> <span class="o">=</span> <span class="n">score_answer</span><span class="p">(</span><span class="n">answer</span><span class="p">,</span> <span class="n">case</span><span class="p">[</span><span class="s">"must_mention"</span><span class="p">])</span>
        <span class="n">scores</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">score</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">score</span> <span class="o">&lt;</span> <span class="mf">1.0</span><span class="p">:</span>
            <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"weak: </span><span class="si">{</span><span class="n">case</span><span class="p">[</span><span class="s">'question'</span><span class="p">]</span><span class="si">!r}</span><span class="s"> -&gt; score </span><span class="si">{</span><span class="n">score</span><span class="si">:</span><span class="p">.</span><span class="mi">2</span><span class="n">f</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>
            <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"   answer: </span><span class="si">{</span><span class="n">answer</span><span class="p">[</span><span class="si">:</span><span class="mi">120</span><span class="p">]</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>
    <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"pass rate: </span><span class="si">{</span><span class="nb">sum</span><span class="p">(</span><span class="n">s</span> <span class="o">==</span> <span class="mf">1.0</span> <span class="k">for</span> <span class="n">s</span> <span class="ow">in</span> <span class="n">scores</span><span class="p">)</span><span class="si">}</span><span class="s">/</span><span class="si">{</span><span class="nb">len</span><span class="p">(</span><span class="n">scores</span><span class="p">)</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>
    <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"mean score: </span><span class="si">{</span><span class="nb">sum</span><span class="p">(</span><span class="n">scores</span><span class="p">)</span> <span class="o">/</span> <span class="nb">len</span><span class="p">(</span><span class="n">scores</span><span class="p">)</span><span class="si">:</span><span class="p">.</span><span class="mi">2</span><span class="n">f</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>

<span class="c1"># Replace this with your real system, or an LLM-as-judge call.
</span><span class="k">def</span> <span class="nf">my_system</span><span class="p">(</span><span class="n">question</span><span class="p">):</span>
    <span class="k">return</span> <span class="s">"TODO: wire up your answer function"</span>

<span class="n">run_eval</span><span class="p">(</span><span class="n">my_system</span><span class="p">)</span>
</code></pre></div></div>

<p>My rule: run it before and after every prompt or retrieval change, and do not ship a change that makes it worse. It is a low bar, on purpose. A low bar you actually check beats a high bar you never measure.</p>

<h2 id="what-i-took-away">What I took away</h2>

<p>No change ships if the eval gets worse. Every failure we find becomes a test case. Vibes are not a metric.</p>]]></content><author><name>Kyungbin Lee</name></author><category term="ai-agents" /><category term="llm" /><category term="evaluation" /><category term="system-design" /><category term="rag" /><summary type="html"><![CDATA[Someone asked me how I know my RAG system is actually working. My honest answer was: vibes. I had tried a few questions by hand, and the answers looked right.]]></summary></entry><entry><title type="html">A Production RAG System, Defended: Decisions and Tradeoffs</title><link href="https://dlrudqls99.github.io/ai-agents/production-rag-defended/" rel="alternate" type="text/html" title="A Production RAG System, Defended: Decisions and Tradeoffs" /><published>2026-11-19T00:00:00+00:00</published><updated>2026-11-19T00:00:00+00:00</updated><id>https://dlrudqls99.github.io/ai-agents/production-rag-defended</id><content type="html" xml:base="https://dlrudqls99.github.io/ai-agents/production-rag-defended/"><![CDATA[<p>I built a RAG system at work. It runs in production, real users ask it real questions, and it mostly works — so I thought explaining it would be easy.</p>

<p>Then I tried explaining it out loud, and it fell apart fast. The short version: I had made a lot of decisions, but I had not defended any of them. This post is that homework — not the code, the reasoning behind the code.</p>

<h2 id="chunk-size-is-a-tradeoff-not-a-setting">Chunk size is a tradeoff, not a setting</h2>

<p>I started with fixed-size chunks, about 500 tokens each, with roughly 20% overlap. It felt arbitrary at the time. Honestly, it was a guess I copied from a tutorial.</p>

<p>Small chunks give precise retrieval: the exact paragraph, nothing extra. But they break context. A table split across two chunks is useless in both.</p>

<p>Large chunks keep context intact. But they drag in noise, and noise eats the context window and confuses the model.</p>

<h2 id="overlap-is-insurance-for-boundaries">Overlap is insurance for boundaries</h2>

<p>The overlap was the part I almost skipped. It looked wasteful — why store the same sentence twice?</p>

<p>Then I found a case where the answer sat exactly on a chunk boundary, split in half. Neither half retrieved well.</p>

<p>Overlap costs storage, which is cheap. Missing the answer costs trust, which is not.</p>

<p>I also tried sentence-based splitting for a while. It sounded cleaner, but it hurt recall on the spec documents I was working with, where a single sentence means nothing without the paragraph around it. I dropped it.</p>

<p>That is the kind of thing I want to be able to say out loud: I tried it, here is what happened, here is why I went back.</p>

<h2 id="vector-search-alone-missed-the-exact-terms">Vector search alone missed the exact terms</h2>

<p>Pure dense retrieval is what I started with. It worked well for questions phrased like the documents.</p>

<p>It failed quietly on the exact stuff: part numbers, error codes, product names. Embeddings are good at meaning and bad at spelling.</p>

<p>So I added BM25 keyword search next to it and combined the scores. Hybrid search is not a fancy idea. It is just admitting that two imperfect tools cover each other’s blind spots: the keyword side catches the exact terms, the vector side catches the paraphrases.</p>

<h2 id="reranking-fixed-the-most-embarrassing-failure">Reranking fixed the most embarrassing failure</h2>

<p>Retrieval gives candidates. A reranker actually reads the question against each one.</p>

<p>It costs a little latency. But it fixed the worst failure mode: the right document retrieved at rank 8, below seven almost-right ones, and the model answering from the wrong one.</p>

<p>Top-k is 5 for the same reason. More context is not more knowledge. Past a point, extra chunks add contradictions, and the model has to guess which one to believe. Five was where our eval numbers stopped improving.</p>

<h2 id="at-100x-the-index-breaks-before-the-model">At 100x, the index breaks before the model</h2>

<p>This is the question I thought about most carefully, because it is the one I was most afraid of getting wrong.</p>

<p>At 100x the documents, the first thing that breaks is not the model. It is the index. A single flat index gets slower and harder to update, so the honest answer is sharding the index, and tuning the approximate search so recall does not quietly fall off a cliff as the corpus grows.</p>

<p>The second thing that breaks is freshness. Re-indexing everything every night stops being cute at that size. You need incremental indexing: only the documents that changed, with a way to prove nothing went stale.</p>

<p>The third is cost. Every retrieved chunk costs tokens, and tokens cost money on every single question. Caching the most common questions, and the embeddings of the most common documents, is the unglamorous fix. I like that answer because it is boring and true.</p>

<h2 id="no-internet-shaped-the-whole-design">No internet shaped the whole design</h2>

<p>One constraint shaped the whole system: the deployment environment had no internet access, and the data could not leave it.</p>

<p>That ruled out hosted APIs entirely. No calling an outside model, no outside embedding service. Everything had to run inside: a smaller local model, local embeddings, and strict allowlists on what the system could touch.</p>

<p>I used to think of that as a limitation to apologize for. Now I think it is the most interesting part of the design, because constraints are what make a design a design. Anyone can build a RAG system with unlimited budget and an open network. The choices only matter when something is off the table.</p>

<h2 id="three-options-i-said-no-to">Three options I said no to</h2>

<p>Fine-tuning: our data was too small and changed too often. Every document update would have meant retraining, and retrieval already solved the knowledge problem. Fine-tuning is for teaching behavior, not for storing facts. That sentence took me a while to earn.</p>

<p>A giant context window instead of retrieval: tempting, and it would have skipped the whole chunking problem. But it is slow and expensive, and the model still gets lost in the middle of long contexts. Retrieval is a way of saying “you only need to read this part.”</p>

<p>Graph RAG: genuinely cool, genuinely overkill for our corpus. I like the idea, and I will probably write about it separately. For this system it would have added a whole layer of complexity for a problem we did not have.</p>

<h2 id="twenty-questions-turned-opinions-into-numbers">Twenty questions turned opinions into numbers</h2>

<p>The habit that changed how I think about all of this: build a tiny eval set before arguing about settings.</p>

<p>Twenty questions, each with the document that should answer it. Then measure how often the right document shows up in the top k.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># eval_recall.py — a tiny recall@k check for your retriever
# You need: a list of (question, expected_doc_id) pairs
# and a retrieve(question, k) function that returns doc ids.
</span>
<span class="k">def</span> <span class="nf">recall_at_k</span><span class="p">(</span><span class="n">eval_set</span><span class="p">,</span> <span class="n">retrieve</span><span class="p">,</span> <span class="n">k</span><span class="o">=</span><span class="mi">5</span><span class="p">):</span>
    <span class="n">hits</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">for</span> <span class="n">question</span><span class="p">,</span> <span class="n">expected_id</span> <span class="ow">in</span> <span class="n">eval_set</span><span class="p">:</span>
        <span class="n">retrieved</span> <span class="o">=</span> <span class="n">retrieve</span><span class="p">(</span><span class="n">question</span><span class="p">,</span> <span class="n">k</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">expected_id</span> <span class="ow">in</span> <span class="n">retrieved</span><span class="p">:</span>
            <span class="n">hits</span> <span class="o">+=</span> <span class="mi">1</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"miss: </span><span class="si">{</span><span class="n">question</span><span class="si">!r}</span><span class="s"> -&gt; got </span><span class="si">{</span><span class="n">retrieved</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">hits</span> <span class="o">/</span> <span class="nb">len</span><span class="p">(</span><span class="n">eval_set</span><span class="p">)</span>

<span class="n">eval_set</span> <span class="o">=</span> <span class="p">[</span>
    <span class="p">(</span><span class="s">"How do I reset the QA inspection flow?"</span><span class="p">,</span> <span class="s">"doc_qa_reset"</span><span class="p">),</span>
    <span class="p">(</span><span class="s">"What is the tolerance for the alignment step?"</span><span class="p">,</span> <span class="s">"doc_alignment_spec"</span><span class="p">),</span>
    <span class="c1"># ... add 15-20 real questions from your own logs
</span><span class="p">]</span>

<span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">10</span><span class="p">]:</span>
    <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"recall@</span><span class="si">{</span><span class="n">k</span><span class="si">}</span><span class="s">: </span><span class="si">{</span><span class="n">recall_at_k</span><span class="p">(</span><span class="n">eval_set</span><span class="p">,</span> <span class="n">retrieve</span><span class="p">,</span> <span class="n">k</span><span class="p">)</span><span class="si">:</span><span class="p">.</span><span class="mi">2</span><span class="n">f</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>
</code></pre></div></div>

<p>This turns “I think chunk size 500 is fine” into “recall@5 went from 0.70 to 0.85 when I changed the chunking.” That is a much better sentence to say out loud.</p>

<h2 id="what-i-took-away">What I took away</h2>

<p>I do not ship a RAG setting I cannot defend out loud.
I measure with 20 real questions before I argue about chunking or top-k.
Every “no” needs a reason I can say in one sentence.</p>]]></content><author><name>Kyungbin Lee</name></author><category term="ai-agents" /><category term="rag" /><category term="llm" /><category term="system-design" /><category term="evaluation" /><summary type="html"><![CDATA[I built a RAG system at work. It runs in production, real users ask it real questions, and it mostly works — so I thought explaining it would be easy.]]></summary></entry><entry><title type="html">Hash Tables in Practice: Collisions, Load Factor, and the LRU Cache</title><link href="https://dlrudqls99.github.io/programming/fundamentals/hash-tables-in-practice/" rel="alternate" type="text/html" title="Hash Tables in Practice: Collisions, Load Factor, and the LRU Cache" /><published>2026-11-17T00:00:00+00:00</published><updated>2026-11-17T00:00:00+00:00</updated><id>https://dlrudqls99.github.io/programming/fundamentals/hash-tables-in-practice</id><content type="html" xml:base="https://dlrudqls99.github.io/programming/fundamentals/hash-tables-in-practice/"><![CDATA[<p>I use dicts every single day, but when I tried to explain why they are fast, my answer was just “because lookup is O(1).” That felt weak, so I went back to the basics.</p>

<p>Day 1 of reviewing CS basics, one topic a day. The short version: hash tables are O(1) on average, not always — only if the hash is decent and the load factor stays under control.</p>

<h2 id="one-formula-puts-each-key-in-its-bucket">One formula puts each key in its bucket</h2>

<p>A hash table stores key–value pairs in an array of buckets. To place a key, run it through a hash function, get a number, and take that number modulo the array size. The result is the index.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">index</span> <span class="o">=</span> <span class="nb">hash</span><span class="p">(</span><span class="n">key</span><span class="p">)</span> <span class="o">%</span> <span class="nb">len</span><span class="p">(</span><span class="n">buckets</span><span class="p">)</span>
</code></pre></div></div>

<p>If the hash function spreads keys out evenly, each bucket has only one or two entries. Lookup is then simple: hash the key, jump to the bucket, check a couple of items.</p>

<p>You pay a small cost — computing the hash — to skip searching through everything.</p>

<h2 id="collisions-always-happen-so-the-fix-has-to-be-built-in">Collisions always happen, so the fix has to be built in</h2>

<p>Two different keys sometimes land in the same bucket. This is not a rare edge case. With enough keys, it always happens.</p>

<p>There are two classic ways to handle it:</p>

<ul>
  <li><strong>Chaining</strong> — each bucket holds a small list of entries, and lookup scans that short list.</li>
  <li><strong>Open addressing</strong> — if the bucket is taken, check the next slots until you find the key or an empty slot. Linear probing is the simplest version.</li>
</ul>

<p>A tiny chaining implementation:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">HashMap</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">size</span><span class="o">=</span><span class="mi">8</span><span class="p">):</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">buckets</span> <span class="o">=</span> <span class="p">[[]</span> <span class="k">for</span> <span class="n">_</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">size</span><span class="p">)]</span>

    <span class="k">def</span> <span class="nf">_index</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">):</span>
        <span class="k">return</span> <span class="nb">hash</span><span class="p">(</span><span class="n">key</span><span class="p">)</span> <span class="o">%</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="p">.</span><span class="n">buckets</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">put</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
        <span class="n">bucket</span> <span class="o">=</span> <span class="bp">self</span><span class="p">.</span><span class="n">buckets</span><span class="p">[</span><span class="bp">self</span><span class="p">.</span><span class="n">_index</span><span class="p">(</span><span class="n">key</span><span class="p">)]</span>
        <span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="n">_</span><span class="p">)</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">bucket</span><span class="p">):</span>
            <span class="k">if</span> <span class="n">k</span> <span class="o">==</span> <span class="n">key</span><span class="p">:</span>
                <span class="n">bucket</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
                <span class="k">return</span>
        <span class="n">bucket</span><span class="p">.</span><span class="n">append</span><span class="p">((</span><span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">))</span>

    <span class="k">def</span> <span class="nf">get</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
        <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="bp">self</span><span class="p">.</span><span class="n">buckets</span><span class="p">[</span><span class="bp">self</span><span class="p">.</span><span class="n">_index</span><span class="p">(</span><span class="n">key</span><span class="p">)]:</span>
            <span class="k">if</span> <span class="n">k</span> <span class="o">==</span> <span class="n">key</span><span class="p">:</span>
                <span class="k">return</span> <span class="n">v</span>
        <span class="k">return</span> <span class="n">default</span>
</code></pre></div></div>

<p>The bad case is worth remembering. If the hash function is poor — or an attacker makes many keys collide on purpose — everything ends up in one bucket. The table becomes a slow linked list with O(n) lookups.</p>

<p>This attack is real. It is called hash flooding, and it is why Python randomizes the hash of strings for each process.</p>

<h2 id="at-075-load-factor-resize--and-the-average-still-holds">At 0.75 load factor, resize — and the average still holds</h2>

<p>The load factor is <code class="language-plaintext highlighter-rouge">entries / buckets</code>. As the table fills up, buckets get crowded and collisions grow.</p>

<p>So implementations set a limit — 0.75 is common — and when the table passes it, they make a bigger array and rehash every key into the new one.</p>

<p>Rehashing costs O(n), which sounds like it breaks the O(1) story. It does not, because of how rarely it happens. If the array doubles each time, the expensive resize is spread over all the inserts that came before it.</p>

<p>So each insert is O(1) on average. That is the honest version of the claim: average O(1), if the hash is decent and the load factor stays under control.</p>

<h2 id="python-dicts-guarantee-order-and-lists-cannot-be-keys">Python dicts guarantee order, and lists cannot be keys</h2>

<p>Three things I checked about the dict I use every day:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">dict</code> uses open addressing, and since Python 3.7 it also remembers insertion order — that is a language guarantee, not luck.</li>
  <li>Keys must be hashable. That is why lists can’t be dict keys but tuples can.</li>
  <li>String hashes are randomized per process, so never depend on a specific hash value.</li>
</ul>

<h2 id="i-already-use-hash-tables-in-three-places-at-work">I already use hash tables in three places at work</h2>

<p>Deduplication: when I index documents for a RAG pipeline, I keep a set of content hashes and drop duplicates before embedding them. Caching: an LLM response cache keys answers by a hash of the normalized prompt — the table gives fast lookup, the eviction policy is separate (see the LRU exercise below). Counting and grouping: <code class="language-plaintext highlighter-rouge">Counter</code> and <code class="language-plaintext highlighter-rouge">defaultdict</code> are just dicts with a small policy on top.</p>

<h2 id="an-lru-cache-is-o1-access-plus-o1-eviction">An LRU cache is O(1) access plus O(1) eviction</h2>

<p>This is the classic exercise, and it is also a pattern I really use: a cache with fixed size that removes the least recently used entry first.</p>

<p><code class="language-plaintext highlighter-rouge">OrderedDict</code> can move an entry to the end and pop from the front, both in O(1). So <code class="language-plaintext highlighter-rouge">get</code> and <code class="language-plaintext highlighter-rouge">put</code> stay O(1):</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">collections</span> <span class="kn">import</span> <span class="n">OrderedDict</span>

<span class="k">class</span> <span class="nc">LRUCache</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">capacity</span><span class="p">:</span> <span class="nb">int</span><span class="p">):</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">capacity</span> <span class="o">=</span> <span class="n">capacity</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">cache</span> <span class="o">=</span> <span class="n">OrderedDict</span><span class="p">()</span>

    <span class="k">def</span> <span class="nf">get</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">key</span> <span class="ow">not</span> <span class="ow">in</span> <span class="bp">self</span><span class="p">.</span><span class="n">cache</span><span class="p">:</span>
            <span class="k">return</span> <span class="o">-</span><span class="mi">1</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">cache</span><span class="p">.</span><span class="n">move_to_end</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>  <span class="c1"># mark as recently used
</span>        <span class="k">return</span> <span class="bp">self</span><span class="p">.</span><span class="n">cache</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>

    <span class="k">def</span> <span class="nf">put</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">key</span> <span class="ow">in</span> <span class="bp">self</span><span class="p">.</span><span class="n">cache</span><span class="p">:</span>
            <span class="bp">self</span><span class="p">.</span><span class="n">cache</span><span class="p">.</span><span class="n">move_to_end</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">cache</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">value</span>
        <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="p">.</span><span class="n">cache</span><span class="p">)</span> <span class="o">&gt;</span> <span class="bp">self</span><span class="p">.</span><span class="n">capacity</span><span class="p">:</span>
            <span class="bp">self</span><span class="p">.</span><span class="n">cache</span><span class="p">.</span><span class="n">popitem</span><span class="p">(</span><span class="n">last</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>  <span class="c1"># evict least recently used
</span></code></pre></div></div>

<p>The hash table gives O(1) access, and the ordering gives O(1) eviction. Most real caches are this pair, plus extras — a TTL, a lock for threads, and so on.</p>

<h2 id="four-questions-are-the-test-for-day-1">Four questions are the test for Day 1</h2>

<p>What happens when collisions pile up, and how does the complexity change? Why “average O(1)” instead of just O(1)? What triggers a resize, and why doesn’t rehashing ruin the average? How can an attacker hurt a hash table, and what do languages do about it?</p>

<p>If I can answer these without waving my hands, Day 1 did its job.</p>

<h2 id="what-i-took-away">What I took away</h2>

<p>Say “average O(1),” not just “O(1).”
Keep the hash decent and the load factor under control.
If I cannot explain it without waving my hands, I do not know it yet.</p>]]></content><author><name>Kyungbin Lee</name></author><category term="Programming" /><category term="Fundamentals" /><category term="python" /><category term="data-structures" /><category term="caching" /><summary type="html"><![CDATA[I use dicts every single day, but when I tried to explain why they are fast, my answer was just “because lookup is O(1).” That felt weak, so I went back to the basics.]]></summary></entry><entry><title type="html">Designing a Production RAG System</title><link href="https://dlrudqls99.github.io/ai/system%20design/designing-a-production-rag-system/" rel="alternate" type="text/html" title="Designing a Production RAG System" /><published>2026-11-14T00:00:00+00:00</published><updated>2026-11-14T00:00:00+00:00</updated><id>https://dlrudqls99.github.io/ai/system%20design/designing-a-production-rag-system</id><content type="html" xml:base="https://dlrudqls99.github.io/ai/system%20design/designing-a-production-rag-system/"><![CDATA[<p>I build RAG systems at work, and RAG is the topic I get asked about most when I study system design. So I wrote down how I would design one for a real company.</p>

<p>A demo takes an afternoon. A production system is a different problem. The short version: the model is the easy part — most of the work is chunking, permissions, sources, and checking whether answers are right.</p>

<p>A demo is simple: load some documents, embed them, grab the top few chunks, let the model answer. In production the documents are private, permissions differ per person, and the data keeps changing. If the model makes something up, a real person might act on it.</p>

<h2 id="three-answers-decide-most-of-the-design">Three answers decide most of the design</h2>

<p>Before I draw anything, I want four answers. Who uses it, and what do they actually ask? How many documents are there, and how often do they change? Is the data confidential, and who can see which documents? How fast does it need to be?</p>

<p>A lookup question (“what is the spec for X”) and a research question (“compare these three reports”) need different systems. A slower answer with sources can also beat a fast one without them.</p>

<p>In a company, the answers are usually: yes, it is confidential; permissions are per team or per document; and every answer needs a source. Those three answers decide most of the design.</p>

<h2 id="keep-the-two-pipelines-separate">Keep the two pipelines separate</h2>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[Documents] → Ingestion → Chunking → Embedding → [Vector index + Keyword index]
                                                          ↓
[User question] → Query rewrite → Hybrid search → Rerank → Top chunks
                                                          ↓
                              Answer generation with citations → [User]
                                                          ↓
                                          Feedback + evaluation logs
</code></pre></div></div>

<p>There are two pipelines here, not one. The ingestion pipeline runs offline: it reads documents, chunks them, embeds them, and updates the index. The query pipeline runs when a user asks something, and it has to be fast.</p>

<p>I keep them separate on purpose. Then I can re-index everything or try a new chunking strategy without touching the part users depend on.</p>

<h2 id="chunking-is-where-most-of-the-quality-is-won-or-lost">Chunking is where most of the quality is won or lost</h2>

<p>Chunking decides what one piece of retrieval is. If chunks are too small, each one has no context. Too big, and the embedding becomes an average of three different topics, which matches nothing well.</p>

<p>What I do: split by structure first — headings, sections, paragraphs — and only use fixed-size windows when the document has no structure. I add a small overlap, so a sentence cut in half still exists whole in the next chunk.</p>

<p>Every chunk also keeps metadata: document id, section, page, when it was updated, and who is allowed to see it. If you skip the metadata, you built a demo.</p>

<h2 id="use-both-kinds-of-search-then-rerank-50-down-to-5">Use both kinds of search, then rerank 50 down to 5</h2>

<p>Embedding search is good at meaning and bad at exact words. It will miss part numbers, error codes, and product names — exactly the things people search for at work. Keyword search (BM25) is the opposite.</p>

<p>So most real systems run both and merge the results. This is called hybrid search.</p>

<p>Then a reranker scores the merged results against the question one more time. Retrieval casts a wide net, say the top 50. The reranker picks the real top 5.</p>

<p>Two stages like this are cheap to run and clearly better than one stage alone.</p>

<h2 id="an-answer-without-a-source-is-almost-useless-at-work">An answer without a source is almost useless at work</h2>

<p>If an answer has no source, the user cannot check it. So the model is told to answer only from the retrieved chunks and to cite them, and the UI shows the source text next to the answer. The user can click through and verify in seconds.</p>

<p>The other half is the honest failure. If nothing relevant comes back from search, the system should say “I couldn’t find this in the documents” instead of guessing.</p>

<p>I learned this the hard way. A system that always answers will eventually answer wrong with full confidence, and that is worse than no answer.</p>

<h2 id="filter-by-permission-during-retrieval-never-after">Filter by permission during retrieval, never after</h2>

<p>This is the part every tutorial leaves out. In a real company it is often the hardest part.</p>

<p>First, filter by permission during retrieval, using the permission list stored with each chunk — not after the answer is made. If the model never sees the chunk, it cannot leak it.</p>

<p>Second, handle removal fast. When a document is deleted or someone loses access, its chunks need to leave the index quickly. Normal indexing can be slow and eventual. Permission removal should not be.</p>

<h2 id="measure-three-things-on-a-golden-set-not-a-feeling">Measure three things on a golden set, not a feeling</h2>

<p>“It feels better” is not a test. I keep a small set of real questions with known good answers — a golden set — and measure three things:</p>

<ul>
  <li><strong>Retrieval</strong>: did the right chunk show up in the top k? (recall@k)</li>
  <li><strong>Answer quality</strong>: is the answer actually based on the cited chunks, and does it answer the question?</li>
  <li><strong>Refusals</strong>: when the answer is not in the documents, does the system say so?</li>
</ul>

<p>Every thumbs-down from a user is a new candidate for the golden set. That loop is what makes the system get better after launch instead of slowly getting worse.</p>

<h2 id="cache-only-common-verified-questions">Cache only common, verified questions</h2>

<p>Caching exact questions rarely helps, because people ask the same thing in different words. Semantic caching is the better version: embed the question, and if a very similar question was answered before, reuse that answer.</p>

<p>This can help a lot when the same questions repeat, like in support. But a wrong match gives a confident wrong answer.</p>

<p>So I would only cache common, verified questions, keep the similarity threshold high, and set a TTL based on how fast the documents change.</p>

<h2 id="every-trade-off-is-speed-freshness-or-isolation">Every trade-off is speed, freshness, or isolation</h2>

<p>Speed vs. quality comes first. Reranking and extra retrieval steps make answers better and slower. Streaming the answer hides some of the wait, not all of it.</p>

<p>Freshness vs. cost is next. Re-embedding everything on every change is simple and expensive. Incremental indexing is cheaper and much easier to get wrong.</p>

<p>One index vs. one per tenant is last. A shared index is cheaper to run. Separate indexes isolate customers better, and some customers will simply require that.</p>

<h2 id="what-i-took-away">What I took away</h2>

<p>Treat production RAG as normal engineering, not magic.
Spend the effort on data, permissions, and checking answers.
The model is the easy part.</p>]]></content><author><name>Kyungbin Lee</name></author><category term="AI" /><category term="System Design" /><category term="rag" /><category term="llm" /><category term="system-design" /><category term="search" /><summary type="html"><![CDATA[I build RAG systems at work, and RAG is the topic I get asked about most when I study system design. So I wrote down how I would design one for a real company.]]></summary></entry><entry><title type="html">How LLM Tool Calling Works: Building a Simple Agent Loop</title><link href="https://dlrudqls99.github.io/ai/agents/llm-tool-calling-agent-loop/" rel="alternate" type="text/html" title="How LLM Tool Calling Works: Building a Simple Agent Loop" /><published>2026-11-14T00:00:00+00:00</published><updated>2026-11-14T00:00:00+00:00</updated><id>https://dlrudqls99.github.io/ai/agents/llm-tool-calling-agent-loop</id><content type="html" xml:base="https://dlrudqls99.github.io/ai/agents/llm-tool-calling-agent-loop/"><![CDATA[<p>Tool calling confused me at first because the name sounds like the model runs code. It doesn’t.</p>

<p>The short version: the model only writes a request — “call this tool with these arguments.” My code runs the tool, and my code can also say no. Once I understood that, agent frameworks stopped looking like magic. Most of them are this one loop with better packaging.</p>

<h2 id="five-steps-are-the-whole-loop">Five steps are the whole loop</h2>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1. Send the user's question + a list of tool definitions to the model.
2. The model either answers directly, or replies: "call tool X with these arguments."
3. My code runs the tool and gets a result.
4. Send the result back to the model.
5. The model answers using the result — or asks for another tool call.
   Repeat from 3 until there is a final answer (or a step limit hits).
</code></pre></div></div>

<p>That is really the whole thing. Frameworks add state, retries, and nicer APIs on top, but the skeleton is these five steps.</p>

<h2 id="one-small-tool-is-enough-to-learn-it">One small tool is enough to learn it</h2>

<p>Say the user asks: <em>“Who was the second person to walk on the moon?”</em> The model might not know, so I give it one tool:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">tools</span> <span class="o">=</span> <span class="p">[{</span>
    <span class="s">"name"</span><span class="p">:</span> <span class="s">"wikipedia_search"</span><span class="p">,</span>
    <span class="s">"description"</span><span class="p">:</span> <span class="s">"Search Wikipedia and return the top result's summary."</span><span class="p">,</span>
    <span class="s">"parameters"</span><span class="p">:</span> <span class="p">{</span>
        <span class="s">"type"</span><span class="p">:</span> <span class="s">"object"</span><span class="p">,</span>
        <span class="s">"properties"</span><span class="p">:</span> <span class="p">{</span>
            <span class="s">"query"</span><span class="p">:</span> <span class="p">{</span><span class="s">"type"</span><span class="p">:</span> <span class="s">"string"</span><span class="p">,</span> <span class="s">"description"</span><span class="p">:</span> <span class="s">"Search query"</span><span class="p">}</span>
        <span class="p">},</span>
        <span class="s">"required"</span><span class="p">:</span> <span class="p">[</span><span class="s">"query"</span><span class="p">],</span>
    <span class="p">},</span>
<span class="p">}]</span>
</code></pre></div></div>

<p>The tool itself is just normal code. Wikipedia has a public API that needs no key:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">requests</span>

<span class="k">def</span> <span class="nf">wikipedia_search</span><span class="p">(</span><span class="n">query</span><span class="p">:</span> <span class="nb">str</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">str</span><span class="p">:</span>
    <span class="n">resp</span> <span class="o">=</span> <span class="n">requests</span><span class="p">.</span><span class="n">get</span><span class="p">(</span>
        <span class="s">"https://en.wikipedia.org/w/api.php"</span><span class="p">,</span>
        <span class="n">params</span><span class="o">=</span><span class="p">{</span>
            <span class="s">"action"</span><span class="p">:</span> <span class="s">"query"</span><span class="p">,</span>
            <span class="s">"list"</span><span class="p">:</span> <span class="s">"search"</span><span class="p">,</span>
            <span class="s">"srsearch"</span><span class="p">:</span> <span class="n">query</span><span class="p">,</span>
            <span class="s">"format"</span><span class="p">:</span> <span class="s">"json"</span><span class="p">,</span>
        <span class="p">},</span>
        <span class="n">headers</span><span class="o">=</span><span class="p">{</span><span class="s">"User-Agent"</span><span class="p">:</span> <span class="s">"study-notes/1.0"</span><span class="p">},</span>
        <span class="n">timeout</span><span class="o">=</span><span class="mi">10</span><span class="p">,</span>
    <span class="p">)</span>
    <span class="n">results</span> <span class="o">=</span> <span class="n">resp</span><span class="p">.</span><span class="n">json</span><span class="p">()[</span><span class="s">"query"</span><span class="p">][</span><span class="s">"search"</span><span class="p">]</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">results</span><span class="p">:</span>
        <span class="k">return</span> <span class="s">"No results found."</span>
    <span class="n">top</span> <span class="o">=</span> <span class="n">results</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="s">"title"</span><span class="p">]</span>
    <span class="n">page</span> <span class="o">=</span> <span class="n">requests</span><span class="p">.</span><span class="n">get</span><span class="p">(</span>
        <span class="s">"https://en.wikipedia.org/w/api.php"</span><span class="p">,</span>
        <span class="n">params</span><span class="o">=</span><span class="p">{</span>
            <span class="s">"action"</span><span class="p">:</span> <span class="s">"query"</span><span class="p">,</span>
            <span class="s">"prop"</span><span class="p">:</span> <span class="s">"extracts"</span><span class="p">,</span>
            <span class="s">"exintro"</span><span class="p">:</span> <span class="bp">True</span><span class="p">,</span>
            <span class="s">"explaintext"</span><span class="p">:</span> <span class="bp">True</span><span class="p">,</span>
            <span class="s">"titles"</span><span class="p">:</span> <span class="n">top</span><span class="p">,</span>
            <span class="s">"format"</span><span class="p">:</span> <span class="s">"json"</span><span class="p">,</span>
        <span class="p">},</span>
        <span class="n">headers</span><span class="o">=</span><span class="p">{</span><span class="s">"User-Agent"</span><span class="p">:</span> <span class="s">"study-notes/1.0"</span><span class="p">},</span>
        <span class="n">timeout</span><span class="o">=</span><span class="mi">10</span><span class="p">,</span>
    <span class="p">)</span>
    <span class="n">pages</span> <span class="o">=</span> <span class="n">page</span><span class="p">.</span><span class="n">json</span><span class="p">()[</span><span class="s">"query"</span><span class="p">][</span><span class="s">"pages"</span><span class="p">]</span>
    <span class="k">return</span> <span class="nb">next</span><span class="p">(</span><span class="nb">iter</span><span class="p">(</span><span class="n">pages</span><span class="p">.</span><span class="n">values</span><span class="p">()))[</span><span class="s">"extract"</span><span class="p">]</span>
</code></pre></div></div>

<p>And the loop. This is pseudocode, but it maps onto any provider’s API:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">ask</span><span class="p">(</span><span class="n">question</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span> <span class="n">max_steps</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">5</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">str</span><span class="p">:</span>
    <span class="n">messages</span> <span class="o">=</span> <span class="p">[{</span><span class="s">"role"</span><span class="p">:</span> <span class="s">"user"</span><span class="p">,</span> <span class="s">"content"</span><span class="p">:</span> <span class="n">question</span><span class="p">}]</span>
    <span class="k">for</span> <span class="n">_</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">max_steps</span><span class="p">):</span>
        <span class="n">response</span> <span class="o">=</span> <span class="n">chat</span><span class="p">(</span><span class="n">messages</span><span class="p">,</span> <span class="n">tools</span><span class="o">=</span><span class="n">tools</span><span class="p">)</span>          <span class="c1"># provider call
</span>        <span class="n">tool_call</span> <span class="o">=</span> <span class="n">response</span><span class="p">.</span><span class="n">tool_calls</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="k">if</span> <span class="n">response</span><span class="p">.</span><span class="n">tool_calls</span> <span class="k">else</span> <span class="bp">None</span>
        <span class="k">if</span> <span class="n">tool_call</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">response</span><span class="p">.</span><span class="n">text</span>                        <span class="c1"># final answer
</span>        <span class="c1"># validate before executing — see below
</span>        <span class="n">result</span> <span class="o">=</span> <span class="n">run_tool</span><span class="p">(</span><span class="n">tool_call</span><span class="p">.</span><span class="n">name</span><span class="p">,</span> <span class="n">tool_call</span><span class="p">.</span><span class="n">arguments</span><span class="p">)</span>
        <span class="n">messages</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">response</span><span class="p">.</span><span class="n">message</span><span class="p">)</span>
        <span class="n">messages</span><span class="p">.</span><span class="n">append</span><span class="p">({</span><span class="s">"role"</span><span class="p">:</span> <span class="s">"tool"</span><span class="p">,</span> <span class="s">"content"</span><span class="p">:</span> <span class="n">result</span><span class="p">})</span>
    <span class="k">return</span> <span class="s">"Stopped: too many steps."</span>
</code></pre></div></div>

<h2 id="model-output-is-untrusted-input-so-check-before-you-run-anything">Model output is untrusted input, so check before you run anything</h2>

<p>The arguments come from a model, so they are untrusted input, same as text from a web form. I check the tool name against a list of allowed tools and validate the argument types.</p>

<p>Anything with real side effects — sending mail, deleting data, paying for something — should need a human’s approval, not run on its own.</p>

<h2 id="an-uncapped-loop-just-burns-money">An uncapped loop just burns money</h2>

<p>A step limit and a timeout are not optional. Models sometimes bounce between two tools forever, and an agent that never stops just burns money.</p>

<h2 id="small-boring-tools-get-called-correctly">Small, boring tools get called correctly</h2>

<p>“Search Wikipedia and return a summary” works well. “Do research” does not.</p>

<p>Small tools with clear descriptions get called correctly. Vague tools get called in creative ways I did not expect.</p>

<h2 id="without-logs-you-cannot-tell-what-went-wrong">Without logs, you cannot tell what went wrong</h2>

<p>Log every step: the question, the tool call, the arguments, the result, the final answer.</p>

<p>When an agent does something wrong, the log is the only way to tell what happened. Did the model choose the wrong tool, did the tool return junk, or was my parsing broken?</p>

<h2 id="history-is-cheap-until-the-process-restarts">History is cheap until the process restarts</h2>

<p>Saving each question and answer costs almost nothing. It pays off the first time someone asks “what did it tell the user yesterday?”</p>

<p>In-memory storage is fine for a study project. The moment it matters, I move to a real database — everything in memory is gone when the process restarts.</p>

<h2 id="what-i-took-away">What I took away</h2>

<p>Building the loop by hand once taught me more than reading about three frameworks.
Now I ask what a framework adds: validation, limits, logging, well-designed tools.
Sometimes the answer is “a lot.” Sometimes it is “not much, but with nice docs.”</p>]]></content><author><name>Kyungbin Lee</name></author><category term="AI" /><category term="Agents" /><category term="llm" /><category term="tool-calling" /><category term="ai-agents" /><category term="python" /><summary type="html"><![CDATA[Tool calling confused me at first because the name sounds like the model runs code. It doesn’t.]]></summary></entry><entry><title type="html">Practical Python Patterns I Keep Reusing</title><link href="https://dlrudqls99.github.io/programming/python/practical-python-patterns/" rel="alternate" type="text/html" title="Practical Python Patterns I Keep Reusing" /><published>2026-11-14T00:00:00+00:00</published><updated>2026-11-14T00:00:00+00:00</updated><id>https://dlrudqls99.github.io/programming/python/practical-python-patterns</id><content type="html" xml:base="https://dlrudqls99.github.io/programming/python/practical-python-patterns/"><![CDATA[<p>When I practice problem solving, I keep coming back to the same handful of patterns. They show up in my real work too — rate limiters, stream parsers, schedulers.</p>

<p>The short version: each pattern is a trade. Once I see which trade the problem is asking for, the code is usually short. I wrote them down in one place, each with the smallest example that shows the idea.</p>

<h2 id="1-a-heap-beats-a-full-sort-when-only-the-top-k-matter">1. A heap beats a full sort when only the top k matter</h2>

<p><strong>When:</strong> “the k most frequent / largest / most recent” anything.</p>

<p>Counting is a <code class="language-plaintext highlighter-rouge">Counter</code>. Picking the top k is <code class="language-plaintext highlighter-rouge">heapq.nlargest</code>, which is O(n log k) instead of sorting the whole thing.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">collections</span> <span class="kn">import</span> <span class="n">Counter</span>
<span class="kn">import</span> <span class="nn">heapq</span>

<span class="k">def</span> <span class="nf">top_k_frequent</span><span class="p">(</span><span class="n">items</span><span class="p">,</span> <span class="n">k</span><span class="p">):</span>
    <span class="n">counts</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">items</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">heapq</span><span class="p">.</span><span class="n">nlargest</span><span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="n">counts</span><span class="p">.</span><span class="n">items</span><span class="p">(),</span> <span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span>
</code></pre></div></div>

<h2 id="2-a-sliding-window-scans-once-because-it-only-moves-forward">2. A sliding window scans once, because it only moves forward</h2>

<p><strong>When:</strong> a condition over a continuous range — longest substring without repeats, max sum of a fixed-size window, “at most N events in any 60 seconds.”</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">longest_unique</span><span class="p">(</span><span class="n">s</span><span class="p">:</span> <span class="nb">str</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">int</span><span class="p">:</span>
    <span class="n">seen</span> <span class="o">=</span> <span class="p">{}</span>
    <span class="n">left</span> <span class="o">=</span> <span class="n">best</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">for</span> <span class="n">right</span><span class="p">,</span> <span class="n">ch</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">ch</span> <span class="ow">in</span> <span class="n">seen</span> <span class="ow">and</span> <span class="n">seen</span><span class="p">[</span><span class="n">ch</span><span class="p">]</span> <span class="o">&gt;=</span> <span class="n">left</span><span class="p">:</span>
            <span class="n">left</span> <span class="o">=</span> <span class="n">seen</span><span class="p">[</span><span class="n">ch</span><span class="p">]</span> <span class="o">+</span> <span class="mi">1</span>
        <span class="n">seen</span><span class="p">[</span><span class="n">ch</span><span class="p">]</span> <span class="o">=</span> <span class="n">right</span>
        <span class="n">best</span> <span class="o">=</span> <span class="nb">max</span><span class="p">(</span><span class="n">best</span><span class="p">,</span> <span class="n">right</span> <span class="o">-</span> <span class="n">left</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">best</span>
</code></pre></div></div>

<p>The window only moves forward, so the whole scan is O(n). Change the characters to timestamps and this same shape becomes a sliding-window rate limiter.</p>

<h2 id="3-mark-nodes-as-seen-when-they-enter-the-queue-not-when-they-leave">3. Mark nodes as seen when they enter the queue, not when they leave</h2>

<p><strong>When:</strong> shortest path in an unweighted graph or grid, or anything level by level.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">collections</span> <span class="kn">import</span> <span class="n">deque</span>

<span class="k">def</span> <span class="nf">bfs</span><span class="p">(</span><span class="n">start</span><span class="p">,</span> <span class="n">graph</span><span class="p">):</span>
    <span class="n">q</span> <span class="o">=</span> <span class="n">deque</span><span class="p">([</span><span class="n">start</span><span class="p">])</span>
    <span class="n">seen</span> <span class="o">=</span> <span class="p">{</span><span class="n">start</span><span class="p">}</span>
    <span class="n">order</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">while</span> <span class="n">q</span><span class="p">:</span>
        <span class="n">node</span> <span class="o">=</span> <span class="n">q</span><span class="p">.</span><span class="n">popleft</span><span class="p">()</span>
        <span class="n">order</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">node</span><span class="p">)</span>
        <span class="k">for</span> <span class="n">nxt</span> <span class="ow">in</span> <span class="n">graph</span><span class="p">[</span><span class="n">node</span><span class="p">]:</span>
            <span class="k">if</span> <span class="n">nxt</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">seen</span><span class="p">:</span>
                <span class="n">seen</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">nxt</span><span class="p">)</span>
                <span class="n">q</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">nxt</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">order</span>
</code></pre></div></div>

<p>I got this wrong before: mark on the way out, and the same node gets added again and again. The work blows up.</p>

<h2 id="4-a-token-bucket-allows-bursts-without-falling-over">4. A token bucket allows bursts without falling over</h2>

<p><strong>When:</strong> any “allow N operations per second” rule — API quotas, job dispatch, retry pacing. This one is worth knowing as real code, not just as an interview answer.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">time</span>

<span class="k">class</span> <span class="nc">TokenBucket</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">rate_per_sec</span><span class="p">:</span> <span class="nb">float</span><span class="p">,</span> <span class="n">capacity</span><span class="p">:</span> <span class="nb">float</span><span class="p">):</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">rate</span> <span class="o">=</span> <span class="n">rate_per_sec</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">capacity</span> <span class="o">=</span> <span class="n">capacity</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">tokens</span> <span class="o">=</span> <span class="n">capacity</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">updated</span> <span class="o">=</span> <span class="n">time</span><span class="p">.</span><span class="n">monotonic</span><span class="p">()</span>

    <span class="k">def</span> <span class="nf">allow</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">bool</span><span class="p">:</span>
        <span class="n">now</span> <span class="o">=</span> <span class="n">time</span><span class="p">.</span><span class="n">monotonic</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">tokens</span> <span class="o">=</span> <span class="nb">min</span><span class="p">(</span>
            <span class="bp">self</span><span class="p">.</span><span class="n">capacity</span><span class="p">,</span>
            <span class="bp">self</span><span class="p">.</span><span class="n">tokens</span> <span class="o">+</span> <span class="p">(</span><span class="n">now</span> <span class="o">-</span> <span class="bp">self</span><span class="p">.</span><span class="n">updated</span><span class="p">)</span> <span class="o">*</span> <span class="bp">self</span><span class="p">.</span><span class="n">rate</span><span class="p">,</span>
        <span class="p">)</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">updated</span> <span class="o">=</span> <span class="n">now</span>
        <span class="k">if</span> <span class="bp">self</span><span class="p">.</span><span class="n">tokens</span> <span class="o">&gt;=</span> <span class="mi">1</span><span class="p">:</span>
            <span class="bp">self</span><span class="p">.</span><span class="n">tokens</span> <span class="o">-=</span> <span class="mi">1</span>
            <span class="k">return</span> <span class="bp">True</span>
        <span class="k">return</span> <span class="bp">False</span>
</code></pre></div></div>

<p>Tokens refill over time, and each request spends one. It handles short bursts up to the bucket size.</p>

<h2 id="5-temperature-top-k-and-top-p-are-just-ways-of-cutting-a-tail">5. Temperature, top-k, and top-p are just ways of cutting a tail</h2>

<p><strong>When:</strong> understanding how an LLM picks its next token. Given logits, the whole thing is a small piece of NumPy:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="n">np</span>

<span class="k">def</span> <span class="nf">sample</span><span class="p">(</span><span class="n">logits</span><span class="p">,</span> <span class="n">temperature</span><span class="o">=</span><span class="mf">1.0</span><span class="p">,</span> <span class="n">top_k</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">top_p</span><span class="o">=</span><span class="mf">1.0</span><span class="p">,</span> <span class="n">rng</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
    <span class="n">rng</span> <span class="o">=</span> <span class="n">rng</span> <span class="ow">or</span> <span class="n">np</span><span class="p">.</span><span class="n">random</span><span class="p">.</span><span class="n">default_rng</span><span class="p">()</span>
    <span class="n">probs</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">exp</span><span class="p">((</span><span class="n">logits</span> <span class="o">-</span> <span class="n">logits</span><span class="p">.</span><span class="nb">max</span><span class="p">())</span> <span class="o">/</span> <span class="n">temperature</span><span class="p">)</span>
    <span class="n">probs</span> <span class="o">/=</span> <span class="n">probs</span><span class="p">.</span><span class="nb">sum</span><span class="p">()</span>

    <span class="k">if</span> <span class="n">top_k</span><span class="p">:</span>                                   <span class="c1"># keep only the k best
</span>        <span class="n">idx</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">argpartition</span><span class="p">(</span><span class="o">-</span><span class="n">probs</span><span class="p">,</span> <span class="n">top_k</span><span class="p">)[:</span><span class="n">top_k</span><span class="p">]</span>
        <span class="n">mask</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">zeros_like</span><span class="p">(</span><span class="n">probs</span><span class="p">);</span> <span class="n">mask</span><span class="p">[</span><span class="n">idx</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span>
        <span class="n">probs</span> <span class="o">=</span> <span class="n">probs</span> <span class="o">*</span> <span class="n">mask</span><span class="p">;</span> <span class="n">probs</span> <span class="o">/=</span> <span class="n">probs</span><span class="p">.</span><span class="nb">sum</span><span class="p">()</span>

    <span class="k">if</span> <span class="n">top_p</span> <span class="o">&lt;</span> <span class="mf">1.0</span><span class="p">:</span>                             <span class="c1"># keep the smallest set
</span>        <span class="n">order</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">argsort</span><span class="p">(</span><span class="o">-</span><span class="n">probs</span><span class="p">)</span>             <span class="c1"># whose mass reaches top_p
</span>        <span class="n">cum</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">cumsum</span><span class="p">(</span><span class="n">probs</span><span class="p">[</span><span class="n">order</span><span class="p">])</span>
        <span class="n">keep</span> <span class="o">=</span> <span class="n">order</span><span class="p">[</span><span class="n">cum</span> <span class="o">-</span> <span class="n">probs</span><span class="p">[</span><span class="n">order</span><span class="p">]</span> <span class="o">&lt;</span> <span class="n">top_p</span><span class="p">]</span>
        <span class="n">mask</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">zeros_like</span><span class="p">(</span><span class="n">probs</span><span class="p">);</span> <span class="n">mask</span><span class="p">[</span><span class="n">keep</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span>
        <span class="n">probs</span> <span class="o">=</span> <span class="n">probs</span> <span class="o">*</span> <span class="n">mask</span><span class="p">;</span> <span class="n">probs</span> <span class="o">/=</span> <span class="n">probs</span><span class="p">.</span><span class="nb">sum</span><span class="p">()</span>

    <span class="k">return</span> <span class="nb">int</span><span class="p">(</span><span class="n">rng</span><span class="p">.</span><span class="n">choice</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">probs</span><span class="p">),</span> <span class="n">p</span><span class="o">=</span><span class="n">probs</span><span class="p">))</span>
</code></pre></div></div>

<p>Greedy decoding is just the special case where you always take the argmax.</p>

<p>Writing this once taught me more than any diagram did. The knobs made sense when I saw they cut the tail of a probability distribution.</p>

<h2 id="6-backoff-with-randomness-spreads-retries-out">6. Backoff with randomness spreads retries out</h2>

<p><strong>When:</strong> calling anything over a network. If every client retries at the same fixed interval, they all hit the server at the same time and make the problem worse.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">random</span><span class="p">,</span> <span class="n">time</span>

<span class="k">def</span> <span class="nf">call_with_retry</span><span class="p">(</span><span class="n">fn</span><span class="p">,</span> <span class="n">attempts</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">base</span><span class="o">=</span><span class="mf">0.5</span><span class="p">):</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">attempts</span><span class="p">):</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">fn</span><span class="p">()</span>
        <span class="k">except</span> <span class="n">TransientError</span><span class="p">:</span>
            <span class="k">if</span> <span class="n">i</span> <span class="o">==</span> <span class="n">attempts</span> <span class="o">-</span> <span class="mi">1</span><span class="p">:</span>
                <span class="k">raise</span>
            <span class="n">time</span><span class="p">.</span><span class="n">sleep</span><span class="p">(</span><span class="n">base</span> <span class="o">*</span> <span class="p">(</span><span class="mi">2</span> <span class="o">**</span> <span class="n">i</span><span class="p">)</span> <span class="o">+</span> <span class="n">random</span><span class="p">.</span><span class="n">uniform</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mf">0.1</span><span class="p">))</span>
</code></pre></div></div>

<h2 id="what-i-took-away">What I took away</h2>

<p>Every pattern here is a trade: a heap for a full sort, remembering positions for a single pass, perfect fairness for simplicity. I name the trade first; the code is usually short.</p>]]></content><author><name>Kyungbin Lee</name></author><category term="Programming" /><category term="Python" /><category term="python" /><category term="algorithms" /><summary type="html"><![CDATA[When I practice problem solving, I keep coming back to the same handful of patterns. They show up in my real work too — rate limiters, stream parsers, schedulers.]]></summary></entry><entry><title type="html">My Notes on “Every React Concept Explained in 12 Minutes”</title><link href="https://dlrudqls99.github.io/frontend/react/react-concepts/" rel="alternate" type="text/html" title="My Notes on “Every React Concept Explained in 12 Minutes”" /><published>2026-10-18T00:00:00+00:00</published><updated>2026-10-18T00:00:00+00:00</updated><id>https://dlrudqls99.github.io/frontend/react/react-concepts</id><content type="html" xml:base="https://dlrudqls99.github.io/frontend/react/react-concepts/"><![CDATA[<p>I kept nodding at words like “reconciliation” and “hydration” without really getting them. Then a 12-minute video from Coding2GO filled in the gaps.</p>

<p>That helped because React is one loop, not a pile of terms. The short version: components hold props and state, a state change triggers a re-render, and reconciliation makes that re-render cheap.</p>

<iframe width="560" height="315" src="https://www.youtube.com/embed/mOfWjc3SP6A" title="Every React Concept Explained in 12 Minutes" frameborder="0" allowfullscreen=""></iframe>

<p>These are my notes from the video, so I can come back here instead of watching it again.</p>

<h2 id="everything-is-a-component-and-components-are-just-functions">Everything is a component, and components are just functions</h2>

<p>A component is a JavaScript function that returns markup. A button is a component. A navbar is a component. A whole page is a component.</p>

<p>You build small pieces and put them together like Lego.</p>

<div class="language-jsx highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">Greeting</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">return</span> <span class="p">&lt;</span><span class="nt">h1</span><span class="p">&gt;</span>Hello!<span class="p">&lt;/</span><span class="nt">h1</span><span class="p">&gt;;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Props pass data into a component, like function arguments.</p>

<div class="language-jsx highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">Greeting</span><span class="p">({</span> <span class="nx">name</span> <span class="p">})</span> <span class="p">{</span>
  <span class="k">return</span> <span class="p">&lt;</span><span class="nt">h1</span><span class="p">&gt;</span>Hello, <span class="si">{</span><span class="nx">name</span><span class="si">}</span>!<span class="p">&lt;/</span><span class="nt">h1</span><span class="p">&gt;;</span>
<span class="p">}</span>

<span class="p">&lt;</span><span class="nc">Greeting</span> <span class="na">name</span><span class="p">=</span><span class="s">"KB"</span> <span class="p">/&gt;</span>
</code></pre></div></div>

<p>The special prop is <code class="language-plaintext highlighter-rouge">children</code>. Anything between the opening and closing tags goes into <code class="language-plaintext highlighter-rouge">children</code>. That is how you make layout components and wrappers.</p>

<h2 id="jsx-looks-like-html-but-it-is-javascript">JSX looks like HTML, but it is JavaScript</h2>

<p>JSX is not real HTML. It gets compiled to JavaScript calls.</p>

<p>Three differences confused me at first. It uses <code class="language-plaintext highlighter-rouge">className</code> instead of <code class="language-plaintext highlighter-rouge">class</code>. Attributes are camelCase — <code class="language-plaintext highlighter-rouge">onClick</code>, not <code class="language-plaintext highlighter-rouge">onclick</code>. And a component can return only one parent element.</p>

<p>For that last rule, wrap things in a Fragment (<code class="language-plaintext highlighter-rouge">&lt;&gt;...&lt;/&gt;</code>) so you do not add an extra <code class="language-plaintext highlighter-rouge">div</code>. Curly braces <code class="language-plaintext highlighter-rouge">{}</code> put JavaScript inside JSX: variables, function calls, and ternaries for conditional rendering.</p>

<h2 id="pass-the-function-do-not-call-it">Pass the function, do not call it</h2>

<p>You attach events with props like <code class="language-plaintext highlighter-rouge">onClick</code> or <code class="language-plaintext highlighter-rouge">onChange</code> and pass a function. Pass the function itself. Do not call it:</p>

<div class="language-jsx highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">&lt;</span><span class="nt">button</span> <span class="na">onClick</span><span class="p">=</span><span class="si">{</span><span class="nx">handleClick</span><span class="si">}</span><span class="p">&gt;</span>Click<span class="p">&lt;/</span><span class="nt">button</span><span class="p">&gt;</span>   <span class="c1">// good</span>
<span class="p">&lt;</span><span class="nt">button</span> <span class="na">onClick</span><span class="p">=</span><span class="si">{</span><span class="nx">handleClick</span><span class="p">()</span><span class="si">}</span><span class="p">&gt;</span>Click<span class="p">&lt;/</span><span class="nt">button</span><span class="p">&gt;</span> <span class="c1">// runs on every render</span>
</code></pre></div></div>

<p>I made this mistake more than once.</p>

<p>Lists have a similar trap. When you render a list with <code class="language-plaintext highlighter-rouge">.map()</code>, each item needs a unique <code class="language-plaintext highlighter-rouge">key</code>, so React knows which item is which when the list changes.</p>

<p>I used the array index at first. It works until you reorder or delete items, and then weird bugs show up. Use a real ID.</p>

<h2 id="state-changes-are-what-make-react-fast--and-predictable">State changes are what make React fast — and predictable</h2>

<p>React does not touch the real DOM every time something changes. It follows four steps:</p>

<ol>
  <li>State changes.</li>
  <li>React builds a new virtual DOM, a lightweight copy in memory.</li>
  <li>It compares the new one with the old one. This is diffing.</li>
  <li>It updates only the parts of the real DOM that actually changed.</li>
</ol>

<p>The whole process is called reconciliation. That is why React stays fast even when the UI updates a lot.</p>

<p>State is the data a component remembers between renders. A normal variable resets every render, so React gives us <code class="language-plaintext highlighter-rouge">useState</code>:</p>

<div class="language-jsx highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="p">[</span><span class="nx">count</span><span class="p">,</span> <span class="nx">setCount</span><span class="p">]</span> <span class="o">=</span> <span class="nx">useState</span><span class="p">(</span><span class="mi">0</span><span class="p">);</span>
</code></pre></div></div>

<p>Always update state with the setter. Changing <code class="language-plaintext highlighter-rouge">count</code> directly does nothing, because React does not know it changed and will not re-render.</p>

<p>Controlled components follow the same rule. A form input shows the state, and <code class="language-plaintext highlighter-rouge">onChange</code> updates the state. The state is the single source of truth.</p>

<h2 id="hooks-follow-two-rules-and-two-of-them-do-most-of-the-work">Hooks follow two rules, and two of them do most of the work</h2>

<p>Hooks are functions that start with <code class="language-plaintext highlighter-rouge">use</code>. Call them only at the top level of a component, never inside loops or <code class="language-plaintext highlighter-rouge">if</code> statements.</p>

<p>The video groups them roughly like this:</p>

<ul>
  <li><strong>State hooks</strong>: <code class="language-plaintext highlighter-rouge">useState</code>, <code class="language-plaintext highlighter-rouge">useReducer</code></li>
  <li><strong>Context hook</strong>: <code class="language-plaintext highlighter-rouge">useContext</code></li>
  <li><strong>Ref hook</strong>: <code class="language-plaintext highlighter-rouge">useRef</code></li>
  <li><strong>Effect hook</strong>: <code class="language-plaintext highlighter-rouge">useEffect</code></li>
  <li><strong>Performance hooks</strong>: <code class="language-plaintext highlighter-rouge">useMemo</code>, <code class="language-plaintext highlighter-rouge">useCallback</code></li>
</ul>

<p>I will not need all of them right away. So far, <code class="language-plaintext highlighter-rouge">useState</code> and <code class="language-plaintext highlighter-rouge">useEffect</code> are the ones I use every day.</p>

<h2 id="effects-are-for-leaving-react-so-use-them-only-when-you-must">Effects are for leaving React, so use them only when you must</h2>

<p><code class="language-plaintext highlighter-rouge">useEffect</code> is for talking to things outside React: fetching data, timers, subscriptions, browser APIs.</p>

<div class="language-jsx highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">useEffect</span><span class="p">(()</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="nx">fetchUser</span><span class="p">(</span><span class="nx">id</span><span class="p">);</span>
<span class="p">},</span> <span class="p">[</span><span class="nx">id</span><span class="p">]);</span>
</code></pre></div></div>

<p>The array at the end is the dependency array. The effect runs again only when those values change.</p>

<p>The video’s advice is the rule I am trying to follow: if you can do it without an effect, do it without an effect. A lot of my early <code class="language-plaintext highlighter-rouge">useEffect</code> calls were unnecessary.</p>

<p>Refs solve a different problem. <code class="language-plaintext highlighter-rouge">useRef</code> gives you a box that keeps a value between renders without causing a re-render. The common use is grabbing a real DOM element, for example to focus an input.</p>

<h2 id="pure-components-make-bugs-easier-to-find">Pure components make bugs easier to find</h2>

<p>A React component should be pure. Same input (props), same output (JSX). It should not change outside variables while rendering.</p>

<p>Strict Mode helps catch mistakes during development. It renders components twice on purpose, so impure code shows up.</p>

<p>At first I thought my code was broken because my <code class="language-plaintext highlighter-rouge">console.log</code> ran twice. Nope, it was just Strict Mode.</p>

<h2 id="context-portals-and-fallbacks-each-fix-one-specific-pain">Context, portals, and fallbacks each fix one specific pain</h2>

<p>Passing props down five levels to reach one component is called prop drilling. It gets messy fast.</p>

<p>Context fixes it. Wrap part of the tree in a provider, and any component inside can read the value with <code class="language-plaintext highlighter-rouge">useContext</code>. Theme and logged-in user are the classic examples.</p>

<p>A portal renders a component somewhere else in the DOM, outside its parent. It is useful for modals, tooltips, and dropdowns that would otherwise get cut off by the parent’s CSS.</p>

<p>Suspense shows a fallback, like a spinner, while a component or its data is still loading. Error Boundaries catch errors in part of the tree and show a fallback UI instead of crashing the whole app with a blank white screen.</p>

<h2 id="server-components-send-less-javascript-and-hydration-makes-the-page-live">Server Components send less JavaScript, and hydration makes the page live</h2>

<p>Server Components run on the server. They can fetch data directly and send less JavaScript to the browser.</p>

<p>Hydration is what happens next. React takes HTML already rendered on the server and attaches the event handlers in the browser, so it becomes interactive.</p>

<p>You mostly see these when using a framework like Next.js.</p>

<h2 id="what-i-took-away">What I took away</h2>

<p>Build a small app and use these ideas, instead of just reading about them.
State changes, re-renders, and reconciliation are the loop to remember.
If I can do it without an effect, I will.</p>]]></content><author><name>Kyungbin Lee</name></author><category term="Frontend" /><category term="React" /><category term="react" /><category term="javascript" /><category term="hooks" /><summary type="html"><![CDATA[I kept nodding at words like “reconciliation” and “hydration” without really getting them. Then a 12-minute video from Coding2GO filled in the gaps.]]></summary></entry><entry><title type="html">AI-Ready Codebase Design and Token Cost Optimization</title><link href="https://dlrudqls99.github.io/ai/engineering/cost-optimization/ai-ready-codebase/" rel="alternate" type="text/html" title="AI-Ready Codebase Design and Token Cost Optimization" /><published>2026-07-02T00:00:00+00:00</published><updated>2026-07-02T00:00:00+00:00</updated><id>https://dlrudqls99.github.io/ai/engineering/cost-optimization/ai-ready-codebase</id><content type="html" xml:base="https://dlrudqls99.github.io/ai/engineering/cost-optimization/ai-ready-codebase/"><![CDATA[<p>I used to think an AI coding agent reads some code, writes some code, and is done. This lecture broke that model.</p>

<p>Most of the cost, and most of the failures, happen before any code is written. The agent is just trying to find its way around.</p>

<p>The short version: cut exploration cost first with a map of the codebase, then cut repeat cost with cache discipline, and measure both at team level, not on your own.</p>

<h2 id="exploration-can-eat-80-of-the-tokens">Exploration can eat 80% of the tokens</h2>

<p>In one payment task, an agent missed 5 out of 40 related files. It modified duplicate payment code instead, and then broke the tests.</p>

<p>In cases like that, 80% of token usage can go to exploration. Only 20% goes to the actual change.</p>

<p>The failure was not poor code quality by itself. It was the cost of exploration and understanding. If the agent cannot find the right place, it reads code it does not need and builds things that already exist.</p>

<h2 id="an-agent-starts-from-zero-every-session">An agent starts from zero every session</h2>

<p>An AI-ready codebase is one an agent can enter in a new session and work in accurately, without losing its way.</p>

<p>A human developer may need about a week to learn a codebase. An agent has the same problem, except it has to re-evaluate its surroundings every time it enters a session.</p>

<p>That is why the work splits into two steps: check the codebase is healthy, then build it a map.</p>

<h2 id="a-map-is-useless-on-an-unhealthy-codebase">A map is useless on an unhealthy codebase</h2>

<p>Health comes first. That means test coverage, dead code removal, consistent conventions, and removing code smells.</p>

<p>If the codebase is unhealthy, an accurate exploration map is meaningless. The map would just describe the mess more precisely.</p>

<h2 id="cartography-gives-the-agent-coordinates">Cartography gives the agent coordinates</h2>

<p>The second step is cartography: a customized codebase map for agents.</p>

<p>It lists entry points, dependency graphs, and a domain glossary. It also marks disposable or safe-to-change areas, and gives accurate task paths.</p>

<p>The point is instruction coordinates. The agent should recognise the correct entry point at once, instead of searching for it. So the map is more than documentation: it also includes verification routines and path information.</p>

<p>An AI Readiness Cartography Skill automates this. It scores navigation, context quality, documentation level, dependency mapping, verification status, freshness, and outcomes, then presents the results as a report.</p>

<p>In the demo, on an actual project, navigation scored low and context document quality scored well. The generated map included <code class="language-plaintext highlighter-rouge">CLAUDE.md</code> and architecture documentation, showing the entry paths agents should reference.</p>

<p>The report also gave an ROI action plan. The suggested actions were splitting and refining <code class="language-plaintext highlighter-rouge">CLAUDE.md</code>, automating PR verification, introducing visualisation, and using ADRs (Architecture Decision Records).</p>

<p>One-time checks have limited effect, though. Diagnosis, reporting, PR creation, and code application should be automated, so checking stays regular and cheap.</p>

<h2 id="the-old-quality-rules-now-do-new-jobs">The old quality rules now do new jobs</h2>

<p>Test coverage, conventions, and dead code removal still matter. In the AI era, they do different jobs.</p>

<p>Test coverage is a signal system. It lets an agent verify its own work. Test code is central here, because it lets agents detect and fix errors inside their feedback loops.</p>

<p>Consistent conventions let agents generalise and reuse patterns. Dead code removal stops agents following incorrect exploration routes. Removing code smells stops them reproducing low-quality code.</p>

<p>The practices were the ones I already knew. The reasons changed.</p>

<h2 id="tokens-turn-into-real-money-fast">Tokens turn into real money fast</h2>

<p>The numbers from the lecture: 500,000 input tokens cost about 5 USD, with 100,000 output tokens included. Over 20 days, that is about 100 USD for one person a month.</p>

<p>For a team of 20, it is about 1,000 USD a month. Over 12 months, about 12,000 USD a year.</p>

<table>
  <thead>
    <tr>
      <th>Category</th>
      <th style="text-align: right">Approximate Token Count</th>
      <th style="text-align: right">Cost</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Input tokens</td>
      <td style="text-align: right">500,000 tokens</td>
      <td style="text-align: right">About 5 USD</td>
    </tr>
    <tr>
      <td>Output tokens</td>
      <td style="text-align: right">100,000 tokens</td>
      <td style="text-align: right">Included</td>
    </tr>
    <tr>
      <td>Individual monthly usage</td>
      <td style="text-align: right">Based on 20 days</td>
      <td style="text-align: right">About 100 USD</td>
    </tr>
    <tr>
      <td>Team usage</td>
      <td style="text-align: right">Based on 20 people</td>
      <td style="text-align: right">About 1,000 USD</td>
    </tr>
    <tr>
      <td>Annual usage</td>
      <td style="text-align: right">Team basis, 12 months</td>
      <td style="text-align: right">About 12,000 USD</td>
    </tr>
  </tbody>
</table>

<p>In large organizations, costs can rise exponentially. Large codebases, second brains, and specification documents can consume hundreds of thousands of tokens.</p>

<p>Individuals tend to use AI carefully, because they pay the bill directly. At company level, people often lack cost awareness and use AI as if it were unlimited. That is why this needs leadership-level control policies, plus the dashboards and cost gates below.</p>

<h2 id="a-token-is-not-a-word-and-korean-costs-more">A token is not a word, and Korean costs more</h2>

<p>A token is the smallest unit of text a model processes. Text is split with a BPE (Byte Pair Encoding) vocabulary, so it does not match words one-to-one.</p>

<p>English runs at about 0.75 words per token. Code is similar. Korean runs at about 1.5 to 2 characters per token, roughly twice as costly.</p>

<p>Korean can be used. But English is recommended when cost efficiency is the priority.</p>

<h2 id="cache-reads-cost-about-a-tenth-of-cache-writes">Cache reads cost about a tenth of cache writes</h2>

<p>When the same prefix is sent again and again, the server caches the computation. That prefix is then handled as a cache read, not a normal input token.</p>

<p>A cache read is much cheaper than a cache write, roughly one-tenth of the cost. Repeated text across sessions, such as <code class="language-plaintext highlighter-rouge">CLAUDE.md</code> and system prompts, should use caching.</p>

<p>The cache TTL (Time To Live) is about 5 minutes. After that it expires and must be written again, so long continuous sessions get the most benefit.</p>

<p>Reconnecting during work, or changing the prefix, can raise cost sharply. Switching models mid-session, from Opus to Sonnet for example, can remove the cache benefit entirely. When a session is restored, token limits may force re-input, which is another sudden increase. The lecture gave a real case where Claude Code asked the user whether cache loss was acceptable, and recommended compacting the session instead.</p>

<p>So the writing rule is simple. Fixed information, such as <code class="language-plaintext highlighter-rouge">CLAUDE.md</code> and second-brain content, goes in the cacheable area. Variable information, such as the current time or the user message, goes in the cache-miss area. Putting the current time later in the prompt maximizes the cacheable area.</p>

<h2 id="six-techniques-cover-most-of-the-saving">Six techniques cover most of the saving</h2>

<ol>
  <li>Read large files once and use cache effectively. Claude Code handles some of this automatically.</li>
  <li>Place <code class="language-plaintext highlighter-rouge">CLAUDE.md</code> near the top of the document structure for quick reference.</li>
  <li>Delegate heavy exploration tasks to separate sub-agents to prevent excessive output token usage during exploration.</li>
  <li>Use compacting for long sessions, while recognizing that starting a new session is sometimes more efficient.</li>
  <li>Do not change the prefix or model in the middle of a session.</li>
  <li>Reuse results from the same engine call to avoid duplicate token consumption.</li>
</ol>

<p>These work better when users understand the basics of how agents work. The anti-patterns are the mirror image: repeatedly sending large files every session, duplicating context input, keeping a prefix cache that will not be used within 5 minutes, frequent <code class="language-plaintext highlighter-rouge">CLAUDE.md</code> and session resets, careless offloading, and simply retaining completed work nodes, which wastes context.</p>

<p>One warning matters. Cutting cost too aggressively can also cut AI performance.</p>

<h2 id="a-good-dashboard-starts-with-cache-utilisation">A good dashboard starts with cache utilisation</h2>

<p>The lecture parses JSON log files from Claude Code sessions automatically. The logs hold input tokens, output tokens, and cache read and write information, and the script turns them into token and cost dashboard reports.</p>

<p>It visualizes session-level and project-level efficiency, cost, cache hit rate, and tool call frequency. Scoring is rubric-based, and each team can customize it.</p>

<table>
  <thead>
    <tr>
      <th>Metric</th>
      <th>Description</th>
      <th>Top Score Standard</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Cache utilization</td>
      <td>Ratio of cache read tokens compared to input tokens</td>
      <td>0.85 or higher</td>
    </tr>
    <tr>
      <td>Output token density</td>
      <td>Ratio of input tokens to output tokens</td>
      <td>If too low, it may indicate excessive exploration</td>
    </tr>
    <tr>
      <td>Tool call frequency</td>
      <td>Number of tool calls per 1K output tokens</td>
      <td>2 to 10 is appropriate; 20 or more indicates excessive exploration</td>
    </tr>
    <tr>
      <td>Total cost</td>
      <td>USD-converted cost by session and project</td>
      <td>Varies by situation; teams should identify an appropriate level</td>
    </tr>
  </tbody>
</table>

<p>The higher the cache utilisation, the less unnecessary retransmission, and the greater the saving.</p>

<p>In a test project, there were 31 active sessions and 347 USD in total cost, an average of 11 USD per session. The cache hit rate was 89%, the average number of tool calls was 13, and the score was around 90 points. That was acceptable overall, but it could decline as the amount of work increases.</p>

<p>The dashboard also surfaces fixes. Too many cache misses, insufficient compacting, or excessive offloading.</p>

<h2 id="dashboards-explain-the-past-cost-gates-act-now">Dashboards explain the past; cost gates act now</h2>

<p>A dashboard visualizes past cost data. A cost gate monitors cost in real time, with proactive alerts or controls.</p>

<p>At session level, a gate can warn or stop execution when token usage passes a threshold. At PR level, if cumulative session cost passes a threshold, it can trigger labelling and follow-up optimisation actions.</p>

<p>Together, the gate and the dashboard combine real-time control with post-work improvement.</p>

<h2 id="what-i-took-away">What I took away</h2>

<p>I fix exploration before I blame the model.
I keep the prefix and the model stable inside a session.
I watch cost at team level, because one careful person does not fix a team’s bill.</p>]]></content><author><name>Kyungbin Lee</name></author><category term="AI" /><category term="Engineering" /><category term="Cost-Optimization" /><category term="ai-agents" /><category term="token-optimization" /><category term="codebase-design" /><summary type="html"><![CDATA[I used to think an AI coding agent reads some code, writes some code, and is done. This lecture broke that model.]]></summary></entry></feed>