<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[AGI Software Solutions]]></title><description><![CDATA[AGI Software Solutions]]></description><link>https://agisoftwaresolutions.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 05 Dec 2026 00:00:58 GMT</lastBuildDate><atom:link href="https://agisoftwaresolutions.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Your Support Tickets Are Full of PII. Your LLM Prompts Shouldn't Be.]]></title><description><![CDATA[Here’s a prompt that gets sent to a third-party model API thousands of times a day, at thousands of companies, in some form: “Summarize this support…]]></description><link>https://agisoftwaresolutions.hashnode.dev/your-support-tickets-are-full-of-pii-your-llm-prompts-shouldn-t-be</link><guid isPermaLink="true">https://agisoftwaresolutions.hashnode.dev/your-support-tickets-are-full-of-pii-your-llm-prompts-shouldn-t-be</guid><category><![CDATA[Python]]></category><category><![CDATA[Security]]></category><category><![CDATA[llm]]></category><category><![CDATA[AI]]></category><dc:creator><![CDATA[AGI Software Solutions]]></dc:creator><pubDate>Wed, 02 Dec 2026 05:53:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b07dfcffaea672dbebbf381/c2663afd-ccee-4f6c-a60b-189cea3339f4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Here’s a prompt that gets sent to a third-party model API thousands of times a day, at thousands of companies, in some form:</p>
<blockquote>
<p>“Summarize this support ticket: Customer Riya Shah (<a href="mailto:riya.shah@example.com">riya.shah@example.com</a>, +91 98765 43210) says her card 4111 1111 1111 1111 was charged twice…”</p>
</blockquote>
<p>The model doesn’t need the real email address to summarize the ticket. It doesn’t need the real phone number to classify the complaint, or the real card number to draft the apology. But we send them anyway, because the ticket text arrives as one blob and redacting it felt like a later problem.</p>
<p>It’s a now problem. Depending on where you operate, that payload intersects GDPR, India’s DPDP Act, or PCI DSS — and even with a provider’s zero-retention agreement, your own logs, traces, and eval datasets now contain copies of everything you sent. Every prompt log becomes a PII store you have to protect like one.</p>
<p>The good news: for the structured PII that matters most, you can build a useful redaction layer in an afternoon, stdlib only. The design has three parts — detect, substitute, rehydrate.</p>
<h2>Detect: regexes, plus one trick to cut false positives</h2>
<p>Emails and phone numbers are regex territory. Card numbers are too, with a catch: <code>(?:\d[ -]?){13,19}</code> happily matches order IDs, tracking numbers, and invoice totals. The trick is that real card numbers satisfy the <strong>Luhn checksum</strong> — a one-digit parity check built into every card number precisely so systems can tell “card” from “random digits.” Validate candidates before redacting:</p>
<pre><code class="language-python">def luhn_ok(digits):
    total, alt = 0, False
    for d in reversed(digits):
        n = int(d)
        if alt:
            n *= 2
            if n &gt; 9:
                n -= 9
        total += n
        alt = not alt
    return total % 10 == 0
</code></pre>
<p>That single check is the difference between a redactor your team trusts and one that mangles every order number — at which point someone “temporarily” disables it, forever.</p>
<h2>Substitute: placeholders with memory</h2>
<p>Don’t replace PII with <code>[REDACTED]</code>. If every email becomes the same black box, the model can no longer tell “reach her at the same address” from “reach her at a different one,” and quality drops for no security gain. Replace each distinct value with a <strong>stable, typed placeholder</strong> — <code>&lt;EMAIL_1&gt;</code>, <code>&lt;CARD_1&gt;</code> — and remember the mapping:</p>
<pre><code class="language-python">class Redactor:
    def __init__(self):
        self.vault = {}   # placeholder -&gt; original
        self.seen = {}    # original -&gt; placeholder (stable within a session)
        self.counters = {}

    def _placeholder(self, kind, original):
        if original in self.seen:
            return self.seen[original]
        self.counters[kind] = self.counters.get(kind, 0) + 1
        ph = f"&lt;{kind}_{self.counters[kind]}&gt;"
        self.vault[ph] = original
        self.seen[original] = ph
        return ph

    def redact(self, text):
        for kind, pattern in PATTERNS:
            def repl(m, kind=kind):
                value = m.group(0)
                if kind == "CARD":
                    digits = re.sub(r"\D", "", value)
                    if not (13 &lt;= len(digits) &lt;= 19 and luhn_ok(digits)):
                        return value  # not a real card; leave it
                return self._placeholder(kind, value)
            text = pattern.sub(repl, text)
        return text

    def rehydrate(self, text):
        for ph, original in self.vault.items():
            text = text.replace(ph, original)
        return text
</code></pre>
<p>The <code>seen</code> map matters more than it looks: the same email appearing twice in a ticket must become the same placeholder both times, or you’ve destroyed information the model legitimately needs (“the customer wrote in twice from one address” vs “two different people”).</p>
<h2>Rehydrate: the model never knew</h2>
<p>Because placeholders are stable and typed, the model can reason about them, reference them, even include them in its output — and you swap the real values back in <em>after</em> the response returns, inside your infrastructure. Real run:</p>
<pre><code class="language-plaintext">SENT TO MODEL:
Customer Riya Shah (&lt;EMAIL_1&gt;, &lt;PHONE_1&gt;) says her card &lt;CARD_1&gt; was charged
twice for order 20261130. Order total was 12 499 which is not a card number.
Reach her at &lt;EMAIL_1&gt; before 5pm.

MODEL OUTPUT (still redacted):
Draft reply: Hi, we've confirmed the duplicate charge on card &lt;CARD_1&gt;
and emailed &lt;EMAIL_1&gt; with the refund timeline.

REHYDRATED FOR THE AGENT UI:
Draft reply: Hi, we've confirmed the duplicate charge on card 4111 1111 1111 1111
and emailed riya.shah@example.com with the refund timeline.
</code></pre>
<p>Three details worth noticing in that output:</p>
<ul>
<li>The order number <code>20261130</code> and the total <code>12 499</code> survived untouched — Luhn rejected both, so the summary stays readable.</li>
<li><code>&lt;EMAIL_1&gt;</code> appears twice in the input and maps consistently, so the model understood it was one person.</li>
<li>The draft reply came back <em>with placeholders in it</em>, and rehydration happened on our side. The provider never saw the card number at any point in the round trip.</li>
</ul>
<p>The vault lives in memory for the duration of one request/session and is never written to the prompt log. Log the redacted text; your traces stop being a compliance liability.</p>
<h2>What regexes won’t catch — be honest about it</h2>
<p>Names, addresses, medical conditions, “my neighbor at flat 4B” — free-text PII doesn’t yield to patterns. The production-grade options are NER models (spaCy, Presidio) or a dedicated redaction pass by a model you <em>do</em> trust in-house. Two practical notes from deploying this:</p>
<ul>
<li><strong>Tier it.</strong> Regex catches the highest-severity structured identifiers (cards, emails, phones, government IDs) deterministically and for free. Run it always, even if a smarter layer sits behind it — deterministic beats probabilistic for the stuff that triggers breach-notification letters.</li>
<li><strong>Measure leakage, don’t assume zero.</strong> Sample redacted prompts weekly and grep-audit them. A redactor you don’t audit degrades silently as input formats drift — a new phone format from a new market is invisible until you look.</li>
</ul>
<p>Redaction is one component, not the whole posture — where it sits among prompt-injection defenses, output handling, and tool permissions is laid out in <a href="https://agisoftwaresolutions.com/blogs/llm-app-security.html">the wider LLM app security checklist we work from</a>.</p>
<p>Your model gets exactly the information the task needs. Your logs stop collecting what you’d one day have to disclose you’d collected. An afternoon well spent.</p>
]]></content:encoded></item><item><title><![CDATA[Your Chat History Doesn't Fit Anymore. Now What?]]></title><description><![CDATA[Every chat application hits this wall. Turn 30 of a support conversation, the context window is full (or the per-request token bill has become…]]></description><link>https://agisoftwaresolutions.hashnode.dev/your-chat-history-doesn-t-fit-anymore-now-what</link><guid isPermaLink="true">https://agisoftwaresolutions.hashnode.dev/your-chat-history-doesn-t-fit-anymore-now-what</guid><category><![CDATA[llm]]></category><category><![CDATA[Python]]></category><category><![CDATA[AI]]></category><category><![CDATA[chatbot]]></category><dc:creator><![CDATA[AGI Software Solutions]]></dc:creator><pubDate>Tue, 01 Dec 2026 05:42:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b07dfcffaea672dbebbf381/1d29fbca-539d-43f8-83ab-f79fe7ca56d3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Every chat application hits this wall. Turn 30 of a support conversation, the context window is full (or the per-request token bill has become indefensible), and something has to go. Most codebases handle it with one line — <code>messages = messages[-20:]</code> — and that one line quietly breaks the product.</p>
<p>Here’s what sliding-window truncation actually deletes, and a trimming strategy that keeps conversations coherent after the history stops fitting.</p>
<h2>What naive truncation breaks</h2>
<p>Dropping the oldest messages feels safe because old messages feel stale. Three things say otherwise:</p>
<p><strong>The system prompt is message zero.</strong> <code>messages[-20:]</code> eventually deletes your instructions, persona, and guardrails. Everyone fixes this after the first incident report where the bot changed personality mid-conversation. Pin it explicitly, not by hoping the window never reaches it.</p>
<p><strong>Commitments live in the middle.</strong> “I need this fixed before our audit on Dec 12 — that date is hard” was turn 3 of 40. The user will not repeat it, the model no longer sees it, and the assistant cheerfully proposes a January service window. From the user’s perspective the product just <em>forgot a promise</em>.</p>
<p><strong>Reference data anchors later turns.</strong> Serial numbers, order IDs, the file the user uploaded — stated once, early, then referred to as “it” forever after. Delete the anchor and every later pronoun dangles.</p>
<h2>The structure that works: pin + tail + rolling summary</h2>
<p>The fix is to stop treating history as one undifferentiated list. Three zones, three policies:</p>
<ol>
<li><strong>Pinned zone</strong> — the system prompt (and any tool schemas). Never evicted, period.</li>
<li><strong>Tail zone</strong> — the N most recent turns, kept verbatim. This is where the conversation’s working state lives; paraphrasing it degrades the model’s next reply.</li>
<li><strong>Everything between</strong> — eviction candidates. But evicted turns don’t vanish: they get folded into a <strong>rolling summary</strong> that rides along as a synthetic system message.</li>
</ol>
<p>Here’s a runnable stdlib-only implementation (token counts are a chars/4 estimate — swap in your model’s real tokenizer in production):</p>
<pre><code class="language-python">from dataclasses import dataclass, field


def est_tokens(text: str) -&gt; int:
    # ~4 chars/token heuristic. Use your model's real tokenizer in production.
    return max(1, len(text) // 4)


@dataclass
class Trimmer:
    budget: int                 # max tokens for the whole message list
    keep_tail: int = 4          # recent turns that must survive verbatim
    summary: str = ""           # rolling summary of evicted turns
    evicted: list = field(default_factory=list)

    def summarize(self, turns):
        # Stand-in for a cheap summarizer-model call. Deterministic here so the
        # demo runs offline: keeps each evicted turn's first sentence.
        firsts = [t["content"].split(". ")[0] for t in turns]
        return " / ".join(firsts)

    def fit(self, messages):
        system, convo = messages[0], messages[1:]

        def total(msgs):
            parts = [system["content"], self.summary] + [m["content"] for m in msgs]
            return sum(est_tokens(p) for p in parts if p)

        while total(convo) &gt; self.budget and len(convo) &gt; self.keep_tail:
            self.evicted.append(convo.pop(0))

        if self.evicted:
            self.summary = self.summarize(self.evicted)

        out = [system]
        if self.summary:
            out.append({"role": "system",
                        "content": f"Summary of earlier conversation: {self.summary}"})
        out.extend(convo)
        return out, total(convo)
</code></pre>
<p>Run against a 8-turn support conversation with a 120-token budget:</p>
<pre><code class="language-plaintext">before: 8 msgs, ~142 tok
after : 7 msgs, ~117 tok (budget 120)
evicted 2 turns -&gt; summary:
  Summary of earlier conversation: My RX-7 arm drops payloads above 4 kg / Thanks
tail kept verbatim, oldest first:
  [user] Troubleshoot first. Also I need any fix done before our audi
  [assistant] Understood: resolution before Dec 12. First check the grippe
  [user] Torque was at 60%. I raised it to 85% and it still drops at
  [assistant] Then it is likely the load cell. I recommend a warranty clai
  [user] OK file the claim. What happens next?
</code></pre>
<p>Under budget, system prompt intact, recent turns verbatim, evicted turns summarized. Working as designed.</p>
<h2>Look closer: the summary lost the serial number</h2>
<p>Read that output again. The evicted turn said “Serial ACM-9931” — and the first-sentence summarizer dropped it. The next time the assistant files that warranty claim, the one identifier it needs is gone. The demo <em>reproduces the exact bug this pattern exists to prevent</em>, one layer down.</p>
<p>That’s the real lesson, and it’s why “just summarize old turns” is not the end of the design:</p>
<ul>
<li><strong>Summarization is lossy in proportion to how generic it is.</strong> A cheap “summarize this conversation” call keeps narrative and drops specifics — and the specifics (IDs, dates, quantities, constraints) are precisely what later turns need.</li>
<li><strong>Durable facts deserve extraction, not summarization.</strong> Alongside the prose summary, run a second pass that pulls typed facts — serial numbers, deadlines, stated constraints, decisions made — into a small key-value block that is pinned like the system prompt. Facts are small; dozens of them fit in fewer tokens than one paragraph of summary.</li>
<li><strong>Summarize incrementally, not from scratch.</strong> Re-summarizing the whole history each time compounds the loss (a summary of a summary of a summary). Fold only the newly evicted turns into the existing summary.</li>
</ul>
<p>This split — a lossy narrative of <em>what happened</em> plus a pinned store of <em>what’s true</em> — is the same distinction between episodic and semantic memory that agent architectures make; we wrote up how we structure <a href="https://agisoftwaresolutions.com/blogs/agent-memory-episodic-semantic.html">episodic and semantic memory for agents</a> on longer-running systems, where the same two-track design applies beyond a single conversation.</p>
<h2>Production checklist</h2>
<ol>
<li><strong>Pin the system prompt structurally</strong> — it must be unreachable by eviction, not just usually out of range.</li>
<li><strong>Keep a verbatim tail</strong> (4–10 turns). Never paraphrase the turns the model is actively working with.</li>
<li><strong>Fold evicted turns into a rolling summary</strong> — incremental, never full re-summarization.</li>
<li><strong>Extract durable facts separately</strong> (IDs, dates, constraints, decisions) into a pinned block; don’t trust prose summaries to carry them.</li>
<li><strong>Count tokens with the real tokenizer</strong> — the chars/4 estimate above is fine for a demo and off by enough to matter at the margin.</li>
<li><strong>Log every eviction</strong> (what was dropped, summary before/after). When a user says “it forgot what I told it,” you want to know exactly which turn fell out and what the summary said at that moment.</li>
</ol>
<p>The window being full is not an edge case; for any conversation worth having, it’s the steady state. Design for it like one.</p>
]]></content:encoded></item><item><title><![CDATA[Why Your LLM's JSON Keeps Breaking in Production (and the Validation Loop That Fixes It)]]></title><description><![CDATA[You ask the model for JSON. In testing it returns clean JSON every time. Then production traffic arrives and the parse errors start: a trailing comma, a…]]></description><link>https://agisoftwaresolutions.hashnode.dev/why-your-llm-s-json-keeps-breaking-in-production-and-the-validation-loop-that-fixes-it</link><guid isPermaLink="true">https://agisoftwaresolutions.hashnode.dev/why-your-llm-s-json-keeps-breaking-in-production-and-the-validation-loop-that-fixes-it</guid><dc:creator><![CDATA[AGI Software Solutions]]></dc:creator><pubDate>Sat, 28 Nov 2026 08:33:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b07dfcffaea672dbebbf381/a17e2ed9-0027-4b73-bd6d-66ca95b50085.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>You ask the model for JSON. In testing it returns clean JSON every time. Then production traffic arrives and the parse errors start: a trailing comma, a field that came back as a string instead of a number, a truncated response, an <code>intent</code> value you never defined. Every one of those crashes the code path that assumed the model would behave.</p>
<p>The mistake is treating the model's output as data. It isn't data until you've validated it — it's a <em>proposal</em> for data. Production LLM code needs a boundary that checks every output against a schema and, when it fails, <strong>tells the model exactly what was wrong and asks again.</strong> That loop is cheap to build and it's the difference between a feature that works in the demo and one that survives real users.</p>
<h2>Step 1: validate against a schema, with precise errors</h2>
<p>The validator's job isn't just to say "invalid" — it's to produce a message specific enough that the model can fix it on the next try. Vague errors give vague repairs. Here's a tiny structural validator in stdlib Python:</p>
<pre><code class="language-python">class SchemaError(Exception):
    pass

def validate(obj, schema):
    """Checks required keys and primitive types; raises a precise, model-readable error."""
    if not isinstance(obj, dict):
        raise SchemaError("top-level value must be a JSON object")
    for key, spec in schema.items():
        if spec.get("required", True) and key not in obj:
            raise SchemaError(f"missing required field '{key}'")
        if key in obj:
            want = spec["type"]
            if want is float and isinstance(obj[key], int):
                obj[key] = float(obj[key])           # ints are acceptable numbers
            elif not isinstance(obj[key], want):
                raise SchemaError(
                    f"field '{key}' must be {want.__name__}, got {type(obj[key]).__name__}")
            if "enum" in spec and obj[key] not in spec["enum"]:
                raise SchemaError(f"field '{key}' must be one of {spec['enum']}")
    return obj
</code></pre>
<p>Note the small kindnesses: it coerces an <code>int</code> into a <code>float</code> instead of rejecting it (the model shouldn't fail because it wrote <code>1</code> instead of <code>1.0</code>), and every error names the field and the problem. That specificity is what makes the repair step work.</p>
<h2>Step 2: the validate-and-repair loop</h2>
<p>Now wrap the model call so a failure feeds the exact error back in and tries again — a bounded number of times, never infinite:</p>
<pre><code class="language-python">import json

def call_with_repair(fake_model, schema, max_attempts=3):
    """Ask the model, validate, and on failure feed the exact error back for one repair."""
    error = None
    for attempt in range(1, max_attempts + 1):
        raw = fake_model(error)                       # model sees the prior error, if any
        try:
            obj = json.loads(raw)
        except json.JSONDecodeError as e:
            error = f"output was not valid JSON: {e}"
            print(f"attempt {attempt}: JSON parse failed -&gt; repairing"); continue
        try:
            obj = validate(obj, schema)
        except SchemaError as e:
            error = str(e)
            print(f"attempt {attempt}: schema error '{e}' -&gt; repairing"); continue
        print(f"attempt {attempt}: valid")
        return obj
    raise RuntimeError("model could not produce valid output")
</code></pre>
<p>In a real system <code>fake_model(error)</code> is your LLM call, and when <code>error</code> is set you append something like <em>"Your previous response was invalid: {error}. Return corrected JSON only."</em> to the prompt.</p>
<h2>Step 3: watch it recover</h2>
<p>Point it at a model that fails twice — truncated JSON, then a bad enum — before getting it right:</p>
<pre><code class="language-python">SCHEMA = {
    "intent":     {"type": str, "enum": ["refund", "status", "complaint"]},
    "order_id":   {"type": str},
    "confidence": {"type": float},
}
</code></pre>
<p>Real output:</p>
<pre><code class="language-plaintext">attempt 1: JSON parse failed -&gt; repairing
attempt 2: schema error 'field 'intent' must be one of ['refund', 'status', 'complaint']' -&gt; repairing
attempt 3: valid
final: {"intent": "refund", "order_id": "ORD-9", "confidence": 0.8}
</code></pre>
<p>Two bad responses, one good result, and the calling code only ever sees validated data.</p>
<h2>The rules that keep this sane</h2>
<ul>
<li><strong>Bound the retries.</strong> Three attempts, not a <code>while True</code>. If the model can't produce valid output in a few tries, that's a real failure to surface — not something to loop on forever while burning tokens.</li>
<li><strong>Validate structure <em>and</em> values.</strong> Type-checking catches <code>"0.8"</code> vs <code>0.8</code>; enum/range checks catch a plausible-but-wrong <code>intent</code>. The dangerous errors are the ones that parse fine and mean the wrong thing.</li>
<li><strong>Use the platform's native structured-output mode if it has one</strong> — it reduces how often you hit the repair path, but it does not replace validation. Constrained decoding makes malformed output rarer; it doesn't make your schema assumptions true.</li>
<li><strong>Log every repair.</strong> A rising repair rate is an early signal that a prompt change or model update regressed your output quality, long before a user reports a bug.</li>
</ul>
<p>The pattern is small, but it's the seam where flaky model output becomes reliable structured data. If you take one thing to production: never trust the first response, and make your error messages good enough for the model to fix itself. It's the same validate-at-the-boundary discipline we apply across <a href="https://agisoftwaresolutions.com/">production LLM systems</a> — the model proposes, the boundary decides.</p>
]]></content:encoded></item><item><title><![CDATA[Streaming LLM Responses Is a Contract, Not a Firehose]]></title><description><![CDATA[We build production AI systems at AGI Software Solutions — more at agisoftwaresolutions.com*.*Everyone's first streaming endpoint looks the same: proxy the…]]></description><link>https://agisoftwaresolutions.hashnode.dev/streaming-llm-responses-is-a-contract-not-a-firehose</link><guid isPermaLink="true">https://agisoftwaresolutions.hashnode.dev/streaming-llm-responses-is-a-contract-not-a-firehose</guid><dc:creator><![CDATA[AGI Software Solutions]]></dc:creator><pubDate>Fri, 27 Nov 2026 11:01:13 GMT</pubDate><content:encoded><![CDATA[<hr />
<p><em>We build production AI systems at AGI Software Solutions — more at</em> <a href="https://agisoftwaresolutions.com/"><em>agisoftwaresolutions.com</em></a>*.*Everyone's first streaming endpoint looks the same: proxy the model's token iterator straight into the HTTP response and call it done. It works in the demo. Then the frontend team asks three questions you can't answer: <em>How do I know the stream finished normally? What happens when the model dies mid-sentence? Why is my UI re-rendering 40 times a second?</em></p>
<p>All three are the same mistake: treating a stream as a firehose of text instead of a <strong>contract with the client</strong>. The server half of that contract has three clauses — frame your events, batch your tokens, and make failure a first-class event. None of them require a framework.</p>
<h2>Clause 1: typed events, not raw text</h2>
<p>Server-Sent Events gives you an <code>event:</code> field — use it. A stream that only ever emits text forces the client to guess what's happening. A stream with <code>start</code> / <code>chunk</code> / <code>done</code> / <code>error</code> event types lets the client switch on intent:</p>
<pre><code class="language-python">import json

def sse(event, data):
    """Format one Server-Sent Event frame."""
    return f"event: {event}\ndata: {json.dumps(data)}\n\n"
</code></pre>
<p>The <code>done</code> event is the one teams skip, and it's the most important: a TCP connection closing tells the client <em>nothing</em> about whether the response was complete. <code>done</code> with a <code>finish_reason</code> is the difference between "the answer ended" and "the answer was cut off" — which your UI should render differently.</p>
<h2>Clause 2: batch tokens into chunks the UI can render</h2>
<p>Sending every token as its own event is wasteful on the wire and hostile to the renderer. Batch tokens until you hit a natural boundary (sentence end, newline) or a size cap — whichever comes first:</p>
<pre><code class="language-python">class ChunkBatcher:
    """Batch raw model tokens into render-friendly chunks."""
    BOUNDARIES = (".", "!", "?", "\n")

    def __init__(self, max_chars=48):
        self.buf = ""
        self.max_chars = max_chars

    def feed(self, token):
        self.buf += token
        if self.buf.endswith(self.BOUNDARIES) or len(self.buf) &gt;= self.max_chars:
            chunk, self.buf = self.buf, ""
            return chunk
        return None

    def flush(self):
        chunk, self.buf = self.buf, ""
        return chunk or None
</code></pre>
<p>The boundary rule matters more than the size cap. Chunks that end at sentence boundaries let the client treat everything received so far as "committed" text that will never change — which is exactly what a good streaming renderer needs to avoid re-parsing markdown on every frame. That's the browser side of this contract; <a href="https://agisoftwaresolutions.com/blogs/streaming-ui-llm.html">the rendering pipeline our team settled on for the browser side</a> — committed/tentative markdown split, chunked rendering, scroll handling — is written up separately, and this server-side batching is what makes it work cleanly.</p>
<h2>Clause 3: errors are events, not silence</h2>
<p>The ugliest streaming failure is the silent one: the upstream model drops, the server's generator throws, the connection closes, and the client is left with half a sentence and no idea anything went wrong. Mid-stream failure can't set an HTTP status — you already sent 200. So failure has to travel <strong>in-band</strong>, as an event:</p>
<pre><code class="language-python">def stream_response(tokens, fail_after=None):
    """Yield SSE frames for a token iterator; emit a typed error mid-stream."""
    batcher = ChunkBatcher()
    yield sse("start", {"ts": 0})
    try:
        for i, tok in enumerate(tokens):
            if fail_after is not None and i == fail_after:
                raise ConnectionError("upstream model dropped the stream")
            chunk = batcher.feed(tok)
            if chunk:
                yield sse("chunk", {"text": chunk})
        tail = batcher.flush()
        if tail:
            yield sse("chunk", {"text": tail})
        yield sse("done", {"finish_reason": "stop"})
    except ConnectionError as e:
        tail = batcher.flush()
        if tail:
            yield sse("chunk", {"text": tail})
        yield sse("error", {"message": str(e), "recoverable": True})
</code></pre>
<p>Note the two details that make this production-shaped: the batcher is flushed <em>before</em> the error goes out (the user keeps every word the model actually produced), and the error carries a <code>recoverable</code> flag so the client knows whether a retry button is honest.</p>
<h2>Run it</h2>
<p>This is the real output of the failure path — stdlib Python, no dependencies:</p>
<pre><code class="language-plaintext">event: start
data: {"ts": 0}

event: chunk
data: {"text": "Streaming is a contract. The client "}

event: error
data: {"message": "upstream model dropped the stream", "recoverable": true}
</code></pre>
<p>The client got clean, sentence-bounded text, then a typed, actionable failure. Compare that with what most streaming endpoints ship: a connection that just… stops.</p>
<h2>The checklist</h2>
<p>Before you call a streaming endpoint done:</p>
<ol>
<li>Every stream ends with exactly one <code>done</code> or one <code>error</code> event — connection close is never the signal.</li>
<li>Chunks break on sentence boundaries, not token boundaries.</li>
<li>Buffered text is flushed before an error event — never swallow words the model produced.</li>
<li><code>error</code> events say whether retrying is worthwhile.</li>
<li>A heartbeat comment (<code>: ping\n\n</code>) goes out every ~15s so proxies don't kill idle connections.</li>
</ol>
<p>Your frontend team will stop asking questions. That's how you know the contract is right.</p>
]]></content:encoded></item></channel></rss>