<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nurhayat Yurtaslan on Medium]]></title>
        <description><![CDATA[Stories by Nurhayat Yurtaslan on Medium]]></description>
        <link>https://medium.com/@nurhayatyurtaslan?source=rss-c026048cd122------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-_qQ_HdWIkliwDLinecvPA.jpeg</url>
            <title>Stories by Nurhayat Yurtaslan on Medium</title>
            <link>https://medium.com/@nurhayatyurtaslan?source=rss-c026048cd122------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 12:35:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nurhayatyurtaslan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Memory Across Runs Is Not Context in a Window]]></title>
            <link>https://nurhayatyurtaslan.medium.com/memory-across-runs-is-not-context-in-a-window-ba17563f184f?source=rss-c026048cd122------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba17563f184f</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Nurhayat Yurtaslan]]></dc:creator>
            <pubDate>Tue, 24 Nov 2026 06:01:03 GMT</pubDate>
            <atom:updated>2026-11-24T06:01:03.365Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ih1JTVqNzHl9xr0dmpHxAw.jpeg" /></figure><p>When people say an agent “remembers,” they usually mean one of three different things: the tokens currently in the prompt, a durable summary the product wrote down, or state sitting on a machine the agent can open again. Those are not the same object. Treating them as one store is how a scratch observation inherits the authority of a fact, and how a fact inherits a completeness it never had.</p><p>I wrote about agent memory lifetimes in an earlier piece — process scratch, tool results, and write-back as three ends that do not arrive together. Cache-augmented generation and long-context RAG make a related mistake on the model side: they confuse the window you were sold with the window you can actually use. Living with Grok Bot made the distinction operational for me, because the product names memory, keeps a shared computer, and still tells you not to treat memory as the source of truth.</p><h3>Three stores that share a sentence</h3><p><strong>Context in a window</strong> is whatever fits in the live prompt for this turn: recent messages, retrieved snippets, tool outputs pasted back in. When the turn ends, that arrangement of tokens is gone unless something else saved a projection of it. Long-context models widen the window. They do not turn the window into a database.</p><p><strong>Bot memory</strong>, in Grok Bot’s docs, is the durable layer that retains stable preferences, role context, important facts, and summaries of prior work. Conversations and learned roles stay separate across Bots. A few facts about you — name, time zone — are shared. The same docs say memory is not a substitute for an authoritative source: keep changing facts in the source system, ask the Bot to reopen current data for consequential decisions, and back safety boundaries with approvals rather than memory alone. Logins and cards belong in Vault, not in memory.</p><p><strong>Shared computer state</strong> is a third lifetime: files under a workspace, browser sessions, downloaded PDFs, a carousel built last night. Every Bot on the account shares one cloud computer, so another Bot can open what the first Bot wrote. That is handoff. It is also not “memory” in the product sense, and it is not context until someone reads the file back into a turn.</p><p>If you collapse the three, a preference (“always ask before sending”) starts to look like a live grant, a file on disk starts to look like a verified fact, and a tool result from yesterday starts to look like a reading performed now.</p><h3>Why the CAG lesson still applies</h3><p>Cache-augmented generation preloads a bounded corpus into a KV cache and answers without a retriever. It works while the corpus fits inside effective context and stays stable enough that the cache is not constantly invalid. The moment the knowledge moves faster than the cache, or grows past what the model can actually use, the elegant removal of retrieval becomes a liability.</p><p>Agent memory has the same shape at human scale. A Bot that remembers your posting rules is valuable because those rules are small and change slowly. A Bot that “remembers” last week’s metrics without reopening the dashboard is dangerous for the same reason CAG is dangerous on a volatile corpus: the durable prefix is no longer a faithful stand-in for the world. Official Grok Bot guidance already points at the fix — check the current source for important decisions — which is retrieval by another name, applied only where freshness matters.</p><h3>Write-back is a projection</h3><p>Surveys of language-model agent memory describe writing as a projection from raw observations into stored contents, often more concise than the original pair. That projection is a new fact about what was kept, not a photograph of the run.</p><p>When a Bot summarizes a week of work into memory, the summary is the stored object. The raw tool outputs are not inside it unless the writer put them there. The next run that trusts the summary as if it still contained the traces is inventing evidence. The correct next step is usually boring: open the source again, take a new observation, and treat the memory line as a claim to check.</p><p>I use that rule on my own content workflows. A note that “the LinkedIn roundup posted” is useful. It is not a substitute for opening the activity page when the question is whether the URN is correct, or whether a company mention is a real tag instead of plain text.</p><h3>Role memory is a feature; shared memory is a narrow channel</h3><p>Separate Bot memories are why a roster works. One Bot can stay specialized on LinkedIn publishing rules without drowning in another Bot’s research digressions. Shared facts stay minimal on purpose. Context that needs to move between Bots should move through an explicit channel: a file on the shared computer, a handoff message, a group thread — something you can point at later.</p><p>That is the agent-identity lesson in miniature. Two processes that share an undifferentiated store become one blurry principal. Two Bots with separate roles and a deliberate handoff stay auditable as two actors, even though they share a machine.</p><h3>Practical rules I keep</h3><ol><li>Preferences and standing boundaries may live in Bot memory.</li><li>Metrics, prices, CVE status, and anything that changes live in the source system until re-read.</li><li>Secrets never live in memory; they live in Vault or a password manager.</li><li>Files on the shared computer are work products, not beliefs.</li><li>For any action that leaves my account, memory of a rule is not enough; an approval still has to fire on the object.</li></ol><p>Memory across runs is what lets a teammate pick up on Wednesday without a monologue. Context in a window is what the model can attend to on this turn. Mixing the words makes both worse. Keep the lifetimes separate, and a persistent agent stops feeling like a chat with amnesia — without pretending it has omniscience.</p><h3>Sources</h3><ul><li>What a Bot remembers / Create and manage Bots: <a href="https://docs.x.ai/grok-bot/bots">https://docs.x.ai/grok-bot/bots</a></li><li>FAQ — what does a Bot remember: <a href="https://docs.x.ai/grok-bot/faq">https://docs.x.ai/grok-bot/faq</a></li><li>Approvals, security, and privacy: <a href="https://docs.x.ai/grok-bot/approvals-security-and-privacy">https://docs.x.ai/grok-bot/approvals-security-and-privacy</a></li><li>Chan et al., Don’t Do RAG (CAG): <a href="https://arxiv.org/abs/2412.15605">https://arxiv.org/abs/2412.15605</a></li><li>Zhang et al., A Survey on the Memory Mechanism of LLM-based Agents: <a href="https://arxiv.org/abs/2404.13501">https://arxiv.org/abs/2404.13501</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba17563f184f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Approvals Before the Write]]></title>
            <link>https://nurhayatyurtaslan.medium.com/approvals-before-the-write-bf082137239b?source=rss-c026048cd122------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf082137239b</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Nurhayat Yurtaslan]]></dc:creator>
            <pubDate>Fri, 20 Nov 2026 06:01:02 GMT</pubDate>
            <atom:updated>2026-11-20T06:01:02.250Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pRNAmj8SFGhjcx27GlsyEw.jpeg" /></figure><p>A language model can name an action long before anything has happened. That gap is where most agent demos quietly fail. The sentence looks like work. The side effect has not occurred. Persistent agents make the gap impossible to ignore, because the product can actually send the email, publish the post, or change the record. The question stops being “can it draft?” and becomes “what sits between the proposal and the write?”</p><p>I have argued elsewhere that a production agent needs a policy engine: the model proposes, a layer turns that proposal into a typed object, an engine evaluates it, authorization binds a result, and only then does execution touch the system. Grok Bot is not that full stack, and pretending it is would be marketing. What it does offer, in a form you can use every day, is a practical gate: Auto Review, Ask-first rules, draft cards for outbound messages, Vault for secrets the model must not see, and standing boundaries you tell the Bot to remember. This piece is about why that gate is the interesting part of living with a persistent agent, not a compliance afterthought.</p><h3>Proposal is cheap; side effects are not</h3><p>In a pure chat product, almost everything is reversible by ignoring it. You can dislike the answer. Nothing left your account. The moment the same model can act through a connector or a signed-in browser, reversibility disappears for a class of actions. A sent message is not a sample. A published post is not a draft. A purchase is not a plan.</p><p>Official Grok Bot docs put consequential actions in a short list you should bound explicitly: sending messages, publishing, purchases and transfers, deleting or overwriting, changing permissions, production changes, accepting legal terms. An approval controls the proposed action. It does not reverse work already completed. That last sentence is the systems point. The gate has to sit before the write, because the product cannot unsend the world.</p><h3>What Auto Review actually does</h3><p>Auto Review checks actions the Bot is about to take — for example before it runs a command, uses a connected app, or uses its computer. Most actions proceed. When one needs your OK, you get a card with the proposed operation and its inputs. An action that matches an Ask-first rule always gets a card. Built-in safety checks still apply even when your custom rules would allow something.</p><p>Two details from the docs matter more than the happy path screenshots.</p><p>First, Auto Review takes into account what you asked for in <strong>your</strong> messages. Text from somewhere else, such as an email or a web page, does not count as your request. That is the right default for a world full of prompt injection. An agent that treats a page’s instructions as your instructions will eventually do someone else’s work with your credentials.</p><p>Second, outbound email has a split path. When you ask for an email in chat, it can go out once Auto Review allows it. Email from a routine, an incoming message, or other work you did not start with that request waits as a draft until you press Send. Forwards and attachments Auto Review cannot fully read always wait. Background approvals expire after about thirty minutes; approvals in a live chat wait for you.</p><p>I run content workflows under the stricter reading of that design. Drafting is allowed. Publishing waits. Commenting on other people’s posts does not happen at all. The Bot can be industrious on my computer and still quiet on the public network until I say yes to a specific object.</p><h3>Ask-first rules are narrow by design</h3><p>Custom rules let you say, in plain words, that certain actions must ask first or may run automatically. Ask-first wins when both match. Docs recommend short, narrow rules around a known action and scope — ask first before sending any external email; allow automatically when running git status in a reports folder — and warn against broad rules such as “allow everything in the browser.”</p><p>That advice matches how I already think about agent permissions. A tool list is not a policy. Publishing a merge tool advertises a capability; it does not install a gate. A longer prompt that says “be careful” is not enforcement, because the next sample can ignore the paragraph. Enforcement is a function that returns deny, or needs-approval, before the credential is used. Auto Review is model-assisted and imperfect; the docs say so by telling you it should complement least privilege, not replace it. Narrow Ask-first rules are how you harden the parts you refuse to leave to judgment.</p><h3>Secrets are not prompt tokens</h3><p>Approvals are only half of the gate. The other half is keeping secret values out of the model.</p><p>Vault holds logins, cards, and contact info so Bots can sign in and check out without seeing the values. A connected password manager such as 1Password can sit in the same path. Secure Forms fill a page without showing the Bot the field contents. When a step cannot be filled that way — single sign-on, passkeys, captchas, device approvals — the Bot hands you the computer, you finish the sensitive step, and you hand it back. API keys go through a masked secret card, not ordinary chat.</p><p>This is the part that made agent work feel usable to me. The old question was always how to give an agent access without pasting the password into the transcript. Filling the page without showing the model is a better answer than “trust the prompt” or “don’t automate logins.”</p><h3>Standing boundaries belong in the Bot, not only in your head</h3><p>Docs encourage you to tell each Bot its standing boundaries and ask it to remember them, and to add Ask-first rules for sending, publishing, deleting, purchasing, or changing production systems. Memory of a rule is still not a substitute for Auto Review. I use both. The remembered rule shapes how the Bot plans. The approval card is what stops the write when planning goes wrong, or when a routine wakes without me in the room.</p><p>A useful test I apply to my own Bots: if a stranger’s email told the Bot to publish something in my name, would any path let that happen without my yes? If the honest answer is yes, the gate is not finished.</p><h3>What this changes in daily work</h3><p>I stopped treating “the Bot finished” as “it is live.” Finished means the artifact exists on the computer or as a draft. Live means I approved a specific action with a visible target. That sounds slower. In practice it is faster than cleaning up a mistaken send, and it is the only way I am willing to leave routines running overnight.</p><p>Approvals before the write are not a personality trait of a cautious user. They are the minimum interface between a model that can propose anything and a computer that can change the world. Persistent agents without that interface are demos. Persistent agents with it start to look like colleagues you can actually leave alone with the draft.</p><h3>Sources</h3><ul><li>Approvals, security, and privacy: <a href="https://docs.x.ai/grok-bot/approvals-security-and-privacy">https://docs.x.ai/grok-bot/approvals-security-and-privacy</a></li><li>Vault and secure sign-in: <a href="https://docs.x.ai/grok-bot/vault">https://docs.x.ai/grok-bot/vault</a></li><li>FAQ — what actions require approval: <a href="https://docs.x.ai/grok-bot/faq">https://docs.x.ai/grok-bot/faq</a></li><li>Grok Bot overview: <a href="https://docs.x.ai/grok-bot/overview">https://docs.x.ai/grok-bot/overview</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf082137239b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Grok Bot Is Different (From a Daily User’s Desk)]]></title>
            <link>https://nurhayatyurtaslan.medium.com/why-grok-bot-is-different-from-a-daily-users-desk-51bfed1ff2bf?source=rss-c026048cd122------2</link>
            <guid isPermaLink="false">https://medium.com/p/51bfed1ff2bf</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Nurhayat Yurtaslan]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 06:01:02 GMT</pubDate>
            <atom:updated>2026-11-17T06:01:02.182Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M1mrrCtJ1JcAszh5URZzJQ.jpeg" /></figure><p>I use Grok Bot every day for content prep, follow-ups, and the small operational jobs that used to die in browser tabs. After a few weeks of that rhythm, the useful distinction is not “better answers.” It is that the product is built as a persistent teammate with a computer, not as a chat window that forgets the world between messages.</p><p>The official overview puts it plainly: Grok Bot is an agent with access to a real computer in the cloud, so it can do the kinds of work a person does inside apps and sites, not only answer questions. The FAQ draws the same line against a generic AI assistant: Bots use a persistent cloud computer, connected tools, websites, and files to complete work; they can continue in the background, keep role-specific context, and coordinate with other Bots. That is the spine of this piece. Everything else is what that architecture forces you to notice when you actually live with it.</p><h3>A computer that outlives the chat</h3><p>Chat is still the main interface. The work is not trapped inside the chat.</p><p>Your Bots share one cloud computer with a browser, a filesystem, and a terminal. Closing the laptop does not stop a background turn or a routine; that work runs on the cloud computer. Several Bots can reason and use connectors in parallel, and each Bot gets its own screen on that shared machine. One Bot can run one computer-use task on its screen at a time. Official docs are also explicit about a boundary people miss: the computer is assigned per user, not per Bot, so separate Bots are not a security boundary. Files, browser sessions, and logins are shared so handoffs are possible. That is a feature for coordination and a constraint for threat modeling. I will come back to it in a later piece in this series.</p><p>In practice, the computer is what turns a request into a finished artifact. A daily LinkedIn roundup is not a paragraph I paste from a model. It is a Bot that reads sources, builds a carousel, opens LinkedIn, and stops where my rules say it must stop. The transcript is the conversation. The computer is where the PDF and the signed-in session live.</p><h3>Routines are the schedule; skills are the method</h3><p>Grok Bot splits repeatable work into two objects that people often conflate.</p><p>A <strong>skill</strong> describes how to perform a task. A <strong>routine</strong> assigns a workflow to one Bot and tells it when to run — on a schedule, or when something happens, such as a Slack message, a GitHub, Linear, Sentry, or PagerDuty event, an email, or a webhook. The docs’ advice is the same advice I would give a junior engineer: start with a one-time task, make it reliable, save the method as a skill, and only then automate it. Routines run in the cloud while the laptop is closed.</p><p>That split matters because automation without a method becomes a brittle prompt on a timer. Automation with a method becomes something you can revise. When I change a roundup rule — for example, never comment on other people’s content, or only publish one LinkedIn post at 22:00 — I am editing the standing instructions of a Bot and its routine, not hoping the next sample remembers a paragraph from last Tuesday.</p><h3>Memory that is not the whole truth</h3><p>A Bot retains stable preferences, role context, and summaries of prior work. Conversations and learned roles are separate across Bots; a few facts about you, such as name and time zone, are shared. Shared files, browser sessions, group messages, and direct handoffs can move context between Bots.</p><p>The docs are careful where many product pages are not: memory is not a source of truth. Changing facts should stay in the source system. For important decisions, you ask the Bot to check the current source rather than rely on memory. Logins, cards, and contact info belong in Vault, not in memory.</p><p>I treat that the same way I treat agent memory in systems work. What the process held during a run, what a tool just returned, and what was written into a durable store are different lifetimes. Collapsing them is how a scratch observation starts looking like a fact. Grok Bot’s design at least names the durable side and warns you not to treat it as authoritative for live decisions. That warning is part of why the product feels different from a long chat history that pretends to be a database.</p><h3>Connectors, and the sites that have none</h3><p>Bots work best when you connect the tools you already use. The overview lists everyday examples — Drive, Calendar, Gmail, Slack, Notion — and notes that custom tooling can talk to MCP servers or APIs. When there is no connector, the shared computer is the fallback: the Bot can use the website the way a person would, within the limits of automation, captchas, and sites that block cloud traffic.</p><p>Official guidance is to prefer a connector when one exists, because structured integrations are more reliable than driving a UI. When a site blocks the cloud computer, the Bot is supposed to hand the step to you rather than bypass it. You can also route traffic through your own machine so the site sees your connection. Those are production details, not marketing footnotes. They are the difference between “it can browse” and “it can finish the job on Thursday morning without inventing a login.”</p><h3>Approvals sit between proposal and side effect</h3><p>The part I care about most is the gate.</p><p>Sensitive or consequential actions can stop for approval. Auto Review checks actions before the Bot runs a command, uses a connected app, or uses its computer. Ask-first rules always raise a card. Text from somewhere else — an email, a web page — does not count as your request. For email from the Bot’s own address, a message you asked for in chat can go out once Auto Review allows it; email from a routine or other background work waits as a draft until you press Send. Approvals raised by background work expire after about thirty minutes; approvals in a chat you are in wait for you.</p><p>Vault and password-manager flows keep secret values out of the model. A Bot can sign in or check out without seeing the password or card number; single sign-on, passkeys, and captchas hand the computer to you. That is the practical answer to the question every agent demo eventually hits: how do I give it access without pasting secrets into the prompt?</p><p>I have written before about policy engines for agentic systems — a proposal object, a deterministic evaluation, authorization, then execution. Grok Bot is not a full enterprise policy engine, and I am not claiming it is. It is the first consumer-facing agent stack I use daily where the product itself insists that sending, publishing, deleting, and purchasing are not just more tokens. They are actions that wait.</p><h3>Many Bots, one desk</h3><p>You can run a roster. One Bot owns a daily digest. Another owns a research lane. Another reviews. They hand work to each other and bring you in for the yes. Official docs frame that as the difference: Bots hand off work, share a computer, remember you, and meet you on desktop, mobile, Slack, or X.</p><p>The operational lesson is narrower. Specialization helps because role context stays with the Bot. Shared state helps because the file another Bot wrote is already on the computer. Neither fact replaces an approval when the action leaves your account. A teammate who can finish the draft is useful. A teammate who can publish without you is a different product, and Grok Bot’s defaults lean toward the first.</p><h3>What I actually leave to it</h3><p>I leave preparation, gathering, drafting, carousel builds, and scheduled quiet jobs. I keep publishing, commenting on other people’s content, and anything that speaks in my name behind an explicit yes. That boundary is not a vibe. It is written into the Bot’s rules and into Auto Review.</p><p>Grok Bot is different because the unit of work is a finished task on a computer that persists, under a role that remembers, on a schedule that runs without the laptop, through connectors when they exist and a browser when they do not — and because the consequential write still stops for you. A chat that answers faster is incremental. A teammate that waits at the gate is a systems change.</p><h3>Sources</h3><ul><li>Grok Bot overview, SpaceXSI Docs: <a href="https://docs.x.ai/grok-bot/overview">https://docs.x.ai/grok-bot/overview</a></li><li>Frequently asked questions: <a href="https://docs.x.ai/grok-bot/faq">https://docs.x.ai/grok-bot/faq</a></li><li>Skills and routines: <a href="https://docs.x.ai/grok-bot/skills-routines-and-automations">https://docs.x.ai/grok-bot/skills-routines-and-automations</a></li><li>Create and manage Bots / what a Bot remembers: <a href="https://docs.x.ai/grok-bot/bots">https://docs.x.ai/grok-bot/bots</a></li><li>Approvals, security, and privacy: <a href="https://docs.x.ai/grok-bot/approvals-security-and-privacy">https://docs.x.ai/grok-bot/approvals-security-and-privacy</a></li><li>Vault and secure sign-in: <a href="https://docs.x.ai/grok-bot/vault">https://docs.x.ai/grok-bot/vault</a></li><li>Product page: <a href="https://x.ai/bot">https://x.ai/bot</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51bfed1ff2bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG, CAG, KAG: un modelo de decisión según corpus, volatilidad y lógica de la consulta]]></title>
            <link>https://nurhayatyurtaslan.medium.com/rag-cag-kag-un-modelo-de-decisi%C3%B3n-seg%C3%BAn-corpus-volatilidad-y-l%C3%B3gica-de-la-consulta-866e02306af0?source=rss-c026048cd122------2</link>
            <guid isPermaLink="false">https://medium.com/p/866e02306af0</guid>
            <category><![CDATA[aprendizaje-automático]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Nurhayat Yurtaslan]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 18:01:03 GMT</pubDate>
            <atom:updated>2026-11-03T18:01:03.674Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DhA9g39dcaFD8zbrW4vAYA.jpeg" /></figure><p>Elegir entre generación aumentada por recuperación, por caché o por conocimiento es un problema de satisfacción de restricciones, no una cuestión de gusto. Cada diseño apuesta de forma distinta sobre dónde entra el conocimiento externo en la ruta de inferencia y cuánto cuesta llevarlo hasta allí. Cada apuesta solo se sostiene dentro de una región delimitada por unas pocas variables medibles: el tamaño del corpus frente al contexto efectivo, la frecuencia con que cambia, la forma lógica de las preguntas, el presupuesto de latencia y lo que uno puede permitirse construir. Dentro de esas regiones, un diseño domina con claridad. En las fronteras, que es donde vive la mayoría de los sistemas reales, lo más acertado suele ser un híbrido que enrute entre diseños.</p><p>Los cinco textos anteriores de la serie examinaron cada uno un extremo del eje. <em>La recuperación es un modo de fallo: el argumento de sistemas detrás de la generación aumentada por caché</em> presentó <a href="https://arxiv.org/abs/2412.15605">CAG (Chan et al.)</a> como la eliminación del recuperador a cambio de un prellenado único. <em>La ventana de contexto que tienes y la que puedes usar: los límites de CAG</em> situó su techo en el contexto efectivo y en la memoria KV. <em>Caché de prefijos en producción: de la CAG del paper a los motores de inferencia</em> mostró que los motores de inferencia ya ofrecen la primitiva. <em>Cuando similitud no es relevancia: por qué Ant Group construyó KAG</em> y <em>Formas lógicas como plan de ejecución: dentro del solver de KAG</em> trataron <a href="https://arxiv.org/abs/2409.13731">KAG (Liang et al.)</a>, que va en sentido contrario y dota a la recuperación de un esquema, un grafo y un plan ejecutable. Este texto los coloca a todos en un mismo mapa.</p><h3>Cinco variables que deciden el diseño</h3><p><strong>Tamaño del corpus frente al contexto efectivo.</strong> La primera prueba es si el conocimiento necesario para una respuesta cabe en el prompt, medido no contra la ventana anunciada sino contra la longitud a la que el modelo sigue razonando con fiabilidad. El artículo de CAG cita <a href="https://arxiv.org/abs/2404.06654">RULER</a> para situar el contexto efectivo de Llama 3.1 8B en unos 32K tokens, frente a una ventana de entrenamiento de 128K. <a href="https://arxiv.org/abs/2411.03538">Leng et al.</a> comprobaron, con 20 modelos, que solo un puñado de los más recientes mantenía una precisión RAG estable por encima de 64K tokens. Los resultados de CAG en HotPotQA van en la misma dirección: su ventaja de BERTScore sobre la mejor configuración RAG con unos 21k tokens (0,7951 frente a 0,7676) se convierte en desventaja con unos 85k (0,7407 frente a 0,7535).</p><p><strong>Volatilidad.</strong> Una caché KV solo es válida para un prefijo exacto, así que cada edición invalida todo lo que viene después. Las actualizaciones frecuentes convierten el prellenado único de CAG en uno recurrente. En KAG, actualizar significa volver a ejecutar la extracción y la alineación sobre los fragmentos afectados. RAG es el que absorbe los cambios con menos coste: volver a calcular el embedding de un documento y actualizar una entrada del índice es rutina.</p><p><strong>Lógica de la consulta.</strong> Las consultas directas («qué dice la cláusula 4.2») se resuelven bien con cualquier diseño que ponga el pasaje correcto delante del modelo. Las preguntas multisalto necesitan resultados intermedios que guíen la recuperación posterior, la observación en la que se basan métodos iterativos como IRCoT. Las preguntas numéricas, temporales o sujetas a reglas requieren operaciones que la similitud no puede expresar y que la predicción de tokens hace mal, justo el hueco para el que se diseñó KAG. El F1 multisalto que informa KAG (76,2 en HotpotQA frente a 63,7 de IRCoT con HippoRAG, ambos sobre DeepSeek-V2) y su precisión y exhaustividad en administración electrónica (91,6 y 71,8 frente a 66,5 y 52,6 de un RAG simple, con 492 preguntas) son evidencia para esa región en concreto.</p><p><strong>Presupuesto de latencia.</strong> CAG elimina la recuperación y el prellenado por consulta, pero sigue decodificando sobre la caché completa. En el artículo de CAG, RAG disperso top-3 generó más rápido que CAG en el conjunto de 85k tokens, 0,6667 s frente a 2,2631 s, mientras que CAG fue muchísimo más rápido que el aprendizaje en contexto sin caché, que tardó 92,0824 s. KAG está en el otro extremo. Su propio estudio de tiempos muestra que el recuperador de fragmentos simple supera en velocidad al solver completo de formas lógicas en un 149 %, un 101 % y un 134 % en tres pruebas, y la planificación genera aproximadamente el doble de tokens que una descomposición simple.</p><p><strong>Coste de construcción y auditabilidad.</strong> RAG necesita un pipeline de embeddings y un índice. CAG necesita un prellenado y memoria para mantener el resultado residente. KAG necesita un esquema, extracción con LLM sobre cada fragmento, curación de conceptos y un almacén de grafos, y a cambio ofrece planes que se pueden inspeccionar paso a paso. Cuando una respuesta tiene que justificarse ante un regulador, un plan ejecutable con fragmentos de apoyo rastreables vale mucho; cuando no, es sobrecoste.</p><h3>El mapa</h3><p>La Fig. 1 reduce estas variables a dos ejes. El horizontal combina tamaño y volatilidad del corpus, porque ambos empujan en la misma dirección: lejos de la precarga. El vertical mide cuánta estructura de razonamiento necesitan las preguntas. CAG ocupa la esquina inferior izquierda: corpus pequeños y estables con preguntas de consulta directa. RAG ocupa la parte inferior derecha: corpus grandes o cambiantes con preguntas que se responden casi siempre con unos pocos pasajes. KAG ocupa la franja superior, donde dominan las relaciones, los números y las reglas, con cualquier tamaño de corpus que justifique la construcción. Las fronteras no son líneas sino zonas, y ahí es donde están los híbridos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NWcu9gyhKPjDMopMaT8ukw.jpeg" /></figure><p><em>Fig. 1. El mapa de decisión. Las regiones puras son aquellas donde domina un diseño; en las franjas rayadas, enrutar entre diseños suele ser mejor que comprometerse con uno.</em></p><h3>En las fronteras, los híbridos son la opción por defecto</h3><p>El propio artículo de CAG propone el primer híbrido: precargar en caché un núcleo estable de documentos y recuperar de forma selectiva los casos límite y el material más nuevo. Así se mantiene la ruta de baja variabilidad para la mayoría de las consultas y la cola larga tiene adónde ir. Con la caché de prefijos de producción, el núcleo estable se convierte en un prefijo fijo del prompt y los pasajes recuperados en el sufijo. La reutilización de KV por fragmentos, como en <a href="https://arxiv.org/abs/2410.07590">TurboRAG</a> o <a href="https://arxiv.org/abs/2405.16444">CacheBlend</a>, abarata además la parte recuperada.</p><p>El segundo híbrido es el enrutamiento según el criterio del propio modelo. <a href="https://arxiv.org/abs/2407.16833">Li et al.</a> compararon directamente RAG con modelos de contexto largo y vieron que, con recursos suficientes, el contexto largo supera a RAG en promedio, mientras que RAG sigue siendo mucho más barato. Su método Self-Route deja que el modelo decida, por autorreflexión, si una consulta puede responderse con los fragmentos recuperados o necesita el contexto largo, y logra un rendimiento comparable al del contexto largo con un coste de cómputo bastante menor. La lección para el diseño de sistemas es que enrutar no exige un clasificador aparte para ser útil: el juicio del propio generador sobre si el material recuperado basta es una señal barata e informativa.</p><p>El tercer híbrido está en la frontera de KAG y ya forma parte de su diseño. Su solver intenta primero la recuperación en el grafo y recurre a la recuperación híbrida de fragmentos cuando el grafo no ofrece una respuesta fiable. En la práctica, eso significa que todo despliegue de KAG contiene un sistema RAG, y un camino de migración razonable va en ese mismo sentido: empezar con RAG sobre documentos bien fragmentados, añadir extracción restringida por esquema para los tipos de entidad y las reglas que provocan los errores caros, y dejar que el solver de formas lógicas se ocupe solo de las preguntas que lo necesitan.</p><h3>Un enrutador que se puede escribir</h3><p>Las variables de decisión son lo bastante concretas como para codificarlas. La función siguiente es un punto de partida, no una política. Sus umbrales salen de mediciones propias: una cifra de contexto efectivo para el modelo en tareas parecidas a las consultas reales, una tasa de actualización sacada de los registros de cambios y un clasificador de consultas, que puede ser tan sencillo como la autoevaluación del generador al estilo de Self-Route.</p><pre>from dataclasses import dataclass<br><br>@dataclass<br>class CargaDeTrabajo:<br>    tokens_corpus: int          # con el tokenizador del modelo, incluido el prompt de sistema<br>    contexto_efectivo: int      # medido en tareas como las tuyas, no la ventana anunciada<br>    cambios_por_dia: float      # ediciones que invalidarían un prefijo en caché<br>    tipo_consulta: str          # &quot;directa&quot; | &quot;multisalto&quot; | &quot;numerica_regla&quot;<br>    requiere_auditoria: bool<br><br>def elegir_estrategia(c: CargaDeTrabajo, margen: float = 0.7) -&gt; str:<br>    cabe = c.tokens_corpus &lt;= margen * c.contexto_efectivo<br>    estable = c.cambios_por_dia &lt; 1<br>    if c.tipo_consulta == &quot;numerica_regla&quot; or (c.tipo_consulta == &quot;multisalto&quot; and c.requiere_auditoria):<br>        return &quot;KAG (solver de formas lógicas, recuperación híbrida como respaldo)&quot;<br>    if cabe and estable:<br>        return &quot;CAG (corpus en caché de prefijos)&quot; if c.tipo_consulta == &quot;directa&quot; \<br>               else &quot;CAG + recuperación de respaldo (al estilo Self-Route)&quot;<br>    if estable and c.tokens_corpus &lt;= 3 * c.contexto_efectivo:<br>        return &quot;Híbrido: núcleo estable en caché, recuperar la cola&quot;<br>    return &quot;RAG (índice + recuperador, reutilización opcional de KV por fragmento)&quot;</pre><p>El factor margen reserva espacio para la consulta, la respuesta y los efectos de posición. El multiplicador de la rama híbrida es un valor provisional que hay que ajustar, no una constante medida. Lo importante es que cada rama se justifica con una variable observable, de modo que la decisión pueda revisarse cuando cambien el corpus, el modelo o el tráfico.</p><h3>Lo que queda abierto</h3><p>Tres incertidumbres limitan cualquier modelo de decisión estático. El contexto efectivo se mueve: cada generación de modelos desplaza la frontera de CAG, así que la medición hay que repetirla, no heredarla. La evidencia es desigual: los resultados de CAG abarcan un único modelo de 8B y corpus de 21k a 85k tokens medidos con BERTScore, y los mejores resultados de KAG son de los propios autores, en parte sobre datos internos, de modo que ambos merecen replicarse sobre la carga propia antes de condicionar la arquitectura. Y los costes de frontera rara vez se miden: la frecuencia de invalidación, la tasa de aciertos de caché, la tasa de fallos de planificación y el ruido de extracción determinan el coste total real más que las puntuaciones de las pruebas, y solo aparecen en la telemetría de producción. Una revisión de diseño que anote las cinco variables, las mediciones que las respaldan y la región del mapa en la que cae el sistema elegirá mejor que una que parta de unas siglas favoritas, y sabrá cuándo conviene revisar esa elección.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=866e02306af0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG, CAG, KAG: A Decision Model by Corpus, Volatility and Query Logic]]></title>
            <link>https://nurhayatyurtaslan.medium.com/rag-cag-kag-a-decision-model-by-corpus-volatility-and-query-logic-206815477251?source=rss-c026048cd122------2</link>
            <guid isPermaLink="false">https://medium.com/p/206815477251</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Nurhayat Yurtaslan]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 14:01:04 GMT</pubDate>
            <atom:updated>2026-11-03T14:01:04.039Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DhA9g39dcaFD8zbrW4vAYA.jpeg" /></figure><p>Choosing between retrieval-augmented, cache-augmented and knowledge-augmented generation is a constraint-satisfaction problem, not a question of taste. Each design makes a different bet about where external knowledge enters the inference path and what it costs to get it there. Each bet holds only inside a region bounded by a handful of measurable variables: corpus size against effective context, how often the corpus changes, what logical shape the questions have, the latency budget, and what you can afford to build. Inside those regions one design clearly dominates. At the boundaries, which is where most real systems live, hybrids that route between designs are usually the right answer.</p><p>The five earlier pieces in this series each examined one end of the axis. <em>Retrieval Is a Failure Mode: The Systems Case Behind Cache-Augmented Generation</em> framed <a href="https://arxiv.org/abs/2412.15605">CAG (Chan et al.)</a> as removing the retriever in exchange for a one-time prefill. <em>The Context Window You Have vs. the One You Can Use: Limits of CAG</em> set its ceiling at effective context and KV memory. <em>Prefix Caching in Production: From Paper CAG to Serving Engines</em> showed that serving engines already provide the primitive. <em>When Similarity Is Not Relevance: Why Ant Group Built KAG</em> and <em>Logical Forms as an Execution Plan: Inside the KAG Solver</em> covered <a href="https://arxiv.org/abs/2409.13731">KAG (Liang et al.)</a>, which goes the other way and gives retrieval a schema, a graph and an executable plan. This piece puts all of them on one map.</p><h3>Five variables that decide the design</h3><p><strong>Corpus size against effective context.</strong> The first test is whether the knowledge needed for an answer can sit in the prompt at all, measured not against the advertised window but against the length at which the model still reasons reliably. The CAG paper cites <a href="https://arxiv.org/abs/2404.06654">RULER</a> for an effective context of about 32K tokens for Llama 3.1 8B, against a 128K training window. <a href="https://arxiv.org/abs/2411.03538">Leng et al.</a> found, across 20 models, that only a handful of recent ones kept consistent RAG accuracy above 64K tokens. CAG’s own HotPotQA results move the same way: its BERTScore lead over the best RAG configuration at about 21k tokens (0.7951 against 0.7676) turns into a deficit at about 85k (0.7407 against 0.7535).</p><p><strong>Volatility.</strong> A KV cache is valid only for an exact prefix, so every edit invalidates everything after it. Frequent updates turn CAG’s one-time prefill into a recurring one. In KAG, updates mean re-running extraction and alignment over the affected chunks. RAG absorbs change most cheaply, since re-embedding a document and updating an index entry is routine.</p><p><strong>Query logic.</strong> Lookups (“what does clause 4.2 say”) are served well by any design that puts the right passage in front of the model. Multi-hop questions need intermediate results to steer later retrieval, which is the observation behind iterative methods such as IRCoT. Numeric, temporal and rule-bound questions need operations that similarity cannot express and that token prediction performs poorly, which is the gap KAG was designed for. KAG’s self-reported multi-hop F1 (76.2 on HotpotQA against 63.7 for IRCoT with HippoRAG, both on DeepSeek-V2) and its e-government precision and recall (91.6 and 71.8 against 66.5 and 52.6 for naive RAG, on 492 questions) are evidence for that region specifically.</p><p><strong>Latency budget.</strong> CAG removes retrieval and per-query prefill but still decodes over the full cache. In the CAG paper, sparse top-3 RAG generated faster than CAG on the 85k-token set, 0.6667 s against 2.2631 s, while CAG was far faster than in-context learning without a cache, at 92.0824 s. KAG sits at the other extreme. Its own timing study shows the plain chunk retriever outperforming the full logical-form solver in speed by 149%, 101% and 134% across three benchmarks, and planning generates about twice as many tokens as plain decomposition.</p><p><strong>Build cost and auditability.</strong> RAG needs an embedding pipeline and an index. CAG needs one prefill and memory to keep the result resident. KAG needs a schema, LLM extraction over every chunk, concept curation and a graph store, and pays back with plans that can be inspected step by step. When an answer has to be justified to a regulator, an executable plan with traceable supporting chunks is worth a lot. When it does not, it is overhead.</p><h3>The map</h3><p>Fig. 1 collapses these variables onto two axes. The horizontal axis combines corpus size and volatility, because both push in the same direction, away from preloading. The vertical axis is how much reasoning structure the questions need. CAG occupies the lower-left corner: small, stable corpora with lookup-style questions. RAG occupies the lower right: large or changing corpora where questions are mostly answerable from a few passages. KAG occupies the upper band, where relations, numbers and rules dominate, at any corpus size large enough to justify the build. The boundaries are not lines but zones, and that is where the hybrids sit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I0PCe2m3l9DgcIw-VxZd_w.jpeg" /></figure><p><em>Fig. 1. The decision map. Pure regions are where one design dominates; hatched bands are where routing between designs usually beats committing to one.</em></p><h3>Hybrids are the default at the boundaries</h3><p>The CAG paper itself proposes the first hybrid. Preload a stable core of documents into the cache and retrieve selectively for edge cases and newer material. This keeps the low-variance path for the bulk of queries and gives the long tail somewhere to go. With production prefix caching, the stable core becomes a fixed prompt prefix and the retrieved passages become the suffix. Chunk-level KV reuse such as <a href="https://arxiv.org/abs/2410.07590">TurboRAG</a> or <a href="https://arxiv.org/abs/2405.16444">CacheBlend</a> then lowers the cost of the retrieved part as well.</p><p>The second hybrid is routing by the model’s own judgement. <a href="https://arxiv.org/abs/2407.16833">Li et al.</a> compared RAG with long-context models directly and found that, when resourced sufficiently, long context outperforms RAG on average, while RAG remains far cheaper. Their Self-Route method lets the model decide, through self-reflection, whether a query can be answered from retrieved chunks or needs the long context, and reports performance comparable to long context at a significantly lower computation cost. The lesson for system design is that routing does not need a separate classifier to be useful. The generator’s own judgement about whether the retrieved material is sufficient is a cheap and informative signal.</p><p>The third hybrid lives at the KAG boundary and is already part of KAG’s design. Its solver tries graph retrieval first and falls back to hybrid chunk retrieval when the graph has no confident answer. In practice that means a KAG deployment always contains a RAG system, and a reasonable migration path runs in the same direction: start with RAG over well-chunked documents, add schema-constrained extraction for the entity types and rules that drive the expensive errors, and let the logical-form solver handle only the questions that need it.</p><h3>A router you can write down</h3><p>The decision variables are concrete enough to encode. The function below is a starting point, not a policy. Its thresholds come from your own measurements: an effective-context figure for your model on tasks like your queries, an update rate from your change logs, and a query classifier, which can be as simple as the generator’s self-assessment in the style of Self-Route.</p><pre>from dataclasses import dataclass<br><br>@dataclass<br>class Workload:<br>    corpus_tokens: int        # in the serving model&#39;s tokenizer, incl. system prompt<br>    effective_ctx: int        # measured on tasks like yours, not the advertised window<br>    updates_per_day: float    # edits that would invalidate a cached prefix<br>    query_type: str           # &quot;lookup&quot; | &quot;multi_hop&quot; | &quot;numeric_rule&quot;<br>    needs_audit_trail: bool<br><br>def choose_strategy(w: Workload, headroom: float = 0.7) -&gt; str:<br>    fits = w.corpus_tokens &lt;= headroom * w.effective_ctx<br>    stable = w.updates_per_day &lt; 1<br>    if w.query_type == &quot;numeric_rule&quot; or (w.query_type == &quot;multi_hop&quot; and w.needs_audit_trail):<br>        return &quot;KAG (logical-form solver, hybrid retrieval as fallback)&quot;<br>    if fits and stable:<br>        return &quot;CAG (prefix-cached corpus)&quot; if w.query_type == &quot;lookup&quot; \<br>               else &quot;CAG + retrieval fallback (Self-Route style)&quot;<br>    if stable and w.corpus_tokens &lt;= 3 * w.effective_ctx:<br>        return &quot;Hybrid: cache stable core, retrieve tail&quot;<br>    return &quot;RAG (index + retriever, optional chunk-KV reuse)&quot;</pre><p>The headroom factor reserves space for the query, the answer and position effects. The multiplier on the hybrid branch is a placeholder to tune, not a measured constant. What matters is that every branch is justified by a variable you can observe, so the decision can be revisited when the corpus, the model or the traffic changes.</p><h3>What remains open</h3><p>Three uncertainties limit any static decision model. Effective context is moving: each model generation shifts the CAG boundary, so the measurement has to be repeated, not inherited. The evidence is uneven: CAG’s results cover one 8B model and corpora of 21k to 85k tokens with BERTScore, and KAG’s strongest results are self-reported, partly on internal data, so both deserve replication on your own workload before they drive architecture. And the boundary costs are rarely measured: invalidation frequency, cache hit rate, planning failure rate and extraction noise decide real total cost more than benchmark scores do, and they only show up in production telemetry. A design review that writes down the five variables, the measurements behind them and the region of the map they place the system in will make a better choice than one that starts from a preferred acronym, and it will know when to revisit that choice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=206815477251" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Formas lógicas como plan de ejecución: dentro del solver de KAG]]></title>
            <link>https://nurhayatyurtaslan.medium.com/formas-l%C3%B3gicas-como-plan-de-ejecuci%C3%B3n-dentro-del-solver-de-kag-c09ee0ac3c71?source=rss-c026048cd122------2</link>
            <guid isPermaLink="false">https://medium.com/p/c09ee0ac3c71</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[aprendizaje-automático]]></category>
            <dc:creator><![CDATA[Nurhayat Yurtaslan]]></dc:creator>
            <pubDate>Sat, 31 Oct 2026 18:01:01 GMT</pubDate>
            <atom:updated>2026-10-31T18:01:01.678Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EoQ-x4ptZPGWiakUnvBqLQ.jpeg" /></figure><p>El solver de KAG trata la respuesta a una pregunta como la ejecución de un programa. La pregunta se traduce primero en una secuencia corta de llamadas a funciones tipadas, una forma lógica (<em>logical form</em>), cuyas variables encadenan los pasos. Después, cada paso lo ejecuta el operador más adecuado: una búsqueda en el grafo, una búsqueda en texto, una ordenación, un cálculo determinista o una deducción. La recuperación deja de ser todo el pipeline y pasa a ser una instrucción más dentro de un plan, y eso es lo que permite auditar cada paso y calcular la aritmética en lugar de predecirla token a token. El precio es la sobrecarga de planificación, y el artículo es franco sobre su tamaño.</p><p>El texto anterior, <em>Cuando similitud no es relevancia: por qué Ant Group construyó KAG</em>, trataba el lado de la representación en <a href="https://arxiv.org/abs/2409.13731">KAG (Liang et al.)</a>: una estructura de conocimiento en tres capas (conocimiento con esquema, información de grafo extraída y fragmentos originales) unida por indexación mutua. Un índice más rico solo sirve si algo puede consultarlo con la estructura adecuada. Una búsqueda por similitud sobre el grafo desperdiciaría casi todo lo que codifica el esquema. Ese algo es el solver, y hacía falta por el mismo motivo que el índice: las preguntas multisalto, numéricas o basadas en reglas fallan en RAG no porque el texto correcto sea inalcanzable, sino porque nada en el pipeline representa los <em>pasos</em> que conectan la pregunta con la respuesta.</p><h3>Por qué un plan, y por qué este tipo de plan</h3><p>Los métodos de recuperación iterativa ya habían mostrado que las preguntas multisalto exigen intercalar recuperación y razonamiento. <a href="https://arxiv.org/abs/2212.10509">IRCoT (Trivedi et al.)</a> formuló la observación central: en preguntas de varios pasos, <em>qué recuperar</em> depende de <em>lo que ya se ha deducido</em>, así que una única pasada de recuperar y leer no basta. IRCoT intercala frases de cadena de pensamiento con llamadas de recuperación e informa de mejoras de hasta 21 puntos en recuperación y 15 en respuesta. <a href="https://arxiv.org/abs/2407.13101">ReSP (Jiang et al.)</a> abordó dos problemas que eso genera: la sobrecarga de contexto tras muchas rondas de recuperación y la planificación repetitiva o excesiva cuando no se guarda registro de la trayectoria. Añadió un resumidor que comprime la evidencia recuperada tanto respecto a la pregunta global como a la subpregunta en curso. Ambos métodos siguen expresando el plan en lenguaje natural, de modo que el estado intermedio es prosa: difícil de comprobar, imposible de ejecutar de forma determinista e incapaz de decir «cuenta esto» o «quédate con el más antiguo» si no es pidiendo al modelo que lo haga de cabeza. KAG conserva el bucle iterativo, con la reflexión en varias rondas adaptada de ReSP, y cambia la representación de cada paso por una llamada simbólica.</p><p>El artículo define cinco funciones. Retrieval(s=si:type[name], p=pi:edge, o=oi:type[name], s.prop=value, ...) busca patrones sujeto-predicado-objeto con restricciones opcionales sobre propiedades. Sort(A, direction=min|max, limit=n) ordena los resultados de una variable. Math(expr) evalúa una expresión en sintaxis LaTeX sobre conjuntos o constantes, como un recuento o una suma, y liga el resultado a una variable nueva. Deduce(left=A, right=B, op=entailment|greater|less|equal) compara o infiere. Output(A, B, ...) devuelve los resultados ligados. Las reglas sobre variables hacen trabajo real. Cuando un paso posterior se refiere a una variable anterior, tiene que reutilizar el mismo nombre y omitir el tipo, lo que convierte el plan en un grafo de flujo de datos y no en una lista de búsquedas independientes. La Fig. 1 muestra esa forma.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wlgVpm9qOXiU6JEa2uN1gA.jpeg" /></figure><p><em>Fig. 1. Un plan en forma lógica como DAG. Cada nodo es una llamada a un operador y cada arista una referencia a una variable. La ampliación es ilustrativa: parte del ejemplo de recuperación única del artículo y muestra dónde entran Math y Sort cuando la pregunta los necesita.</em></p><h3>Ejecutar un paso: primero el grafo, el texto como respaldo</h3><p>El ejemplo del artículo muestra cómo un paso de recuperación lleva una estructura que una consulta vectorial no puede expresar. Para «¿Qué documentos se necesitan para solicitar un certificado de discapacidad en West Lake, Hangzhou?», la función de recuperación es Retrieval(s=s1:Event[applying for a disability certificate], p=p1:support_chunks, o=o1:Chunk, s.location=West Lake, Hangzhou). El tipo de evento, la arista hacia los fragmentos que lo sustentan y el filtro de ubicación son explícitos. Los nombres propios, lugares, fechas y números, que según el artículo los codificadores densos representan mal, se convierten en condiciones de filtro exactas en lugar de ser términos dentro de una puntuación de similitud. Cada subconsulta pasa después por la recuperación en dos niveles del razonador. GraphRetrieval prueba primero las capas estructuradas y, si el resultado está vacío o por debajo de un umbral de confianza, HybridRetrieval busca en los fragmentos, combinando coincidencia dispersa y densa guiada por lo que el grafo sí haya encontrado. Un generador responde entonces a la subconsulta con el material recuperado. El ejecutor de juguete siguiente reproduce ese flujo de control sobre un grafo en memoria. No es el código de KAG, que trabaja contra un almacén LPG y un índice vectorial, pero la lógica de despacho tiene la misma forma:</p><pre>PLAN = [  # forma lógica del ejemplo de West Lake, una llamada por paso<br>    (&quot;Retrieval&quot;, dict(s=&quot;s1:Event[solicitar certificado de discapacidad]&quot;,<br>                       p=&quot;p1:support_chunks&quot;, o=&quot;o1:Chunk&quot;,<br>                       filtros={&quot;s.location&quot;: &quot;West Lake, Hangzhou&quot;})),<br>    (&quot;Output&quot;, dict(args=[&quot;o1&quot;])),<br>]<br><br>def recuperar_grafo(kg, s, p, filtros):<br>    tipo, nombre = s.split(&quot;:&quot;)[1].rstrip(&quot;]&quot;).split(&quot;[&quot;)<br>    return [o for (suj, rel, o) in kg[&quot;tripletas&quot;]<br>            if suj[&quot;type&quot;] == tipo and suj[&quot;name&quot;] == nombre and rel == p.split(&quot;:&quot;)[1]<br>            and all(suj.get(k.split(&quot;.&quot;)[1]) == v for k, v in filtros.items())]<br><br>def ejecutar(plan, kg, busqueda_hibrida, umbral=1):<br>    entorno = {}<br>    for op, a in plan:<br>        if op == &quot;Retrieval&quot;:<br>            hits = recuperar_grafo(kg, a[&quot;s&quot;], a[&quot;p&quot;], a[&quot;filtros&quot;])<br>            if len(hits) &lt; umbral:                     # fallo de GraphRetrieval -&gt; respaldo<br>                hits = busqueda_hibrida(a[&quot;s&quot;], a[&quot;filtros&quot;])<br>            entorno[a[&quot;o&quot;].split(&quot;:&quot;)[0]] = hits<br>        elif op == &quot;Math&quot;:                             # determinista, no generado<br>            entorno[a[&quot;var&quot;]] = a[&quot;fn&quot;](*(entorno[x] for x in a[&quot;args&quot;]))<br>        elif op == &quot;Output&quot;:<br>            return {x: entorno[x] for x in a[&quot;args&quot;]}</pre><p>La línea importante es la rama Math. Cuando una pregunta pide cuántos, cuánto o cuál fue antes, el plan entrega un conjunto a una función en lugar de pedir al modelo que cuente sobre texto, que es justo la debilidad de «lógica del conocimiento» que el artículo de KAG atribuye a la predicción del siguiente token.</p><h3>El bucle exterior y la capa de alineación</h3><p>Alrededor del ejecutor de un solo plan está el Algoritmo 1 del artículo. LFPlanner descompone la consulta actual en formas lógicas. El Reasoner ejecuta cada una y añade a un historial la subconsulta, lo recuperado y la respuesta. Memory consolida ese historial. Judge decide si la pregunta original está respondida y, si no lo está, SupplyQuery redacta una pregunta complementaria y el bucle se repite, hasta <em>n</em> rondas. Es el mecanismo de reflexión tomado de ReSP, y permite al sistema recuperarse de un plan que recuperó la entidad intermedia equivocada. La alineación de conocimiento actúa por debajo tanto de la indexación como de la consulta. El mismo razonamiento sobre sinonimia, hiperonimia e inclusión que ordenó el grafo durante la construcción traduce, en el momento de la consulta, la formulación del usuario a los conceptos indexados, de modo que una llamada Retrieval con un término coloquial pueda acabar en el nodo canónico.</p><h3>Lo que informa el artículo</h3><p>En pruebas de preguntas multisalto, KAG con el solver de formas lógicas, recuperación híbrida y hasta tres rondas de reflexión (LFSH_ref3, sobre la API de DeepSeek-V2) informa de un F1 de 76,2 en HotpotQA, 76,2 en 2WikiMultiHopQA y 48,7 en MuSiQue. La línea base más fuerte de la misma tabla, IRCoT con HippoRAG sobre DeepSeek-V2, obtiene 63,7, 57,1 y 36,5. En el despliegue de preguntas sobre administración electrónica de Ant Group, evaluado con 492 preguntas, KAG informa de una precisión de 91,6 y una exhaustividad de 71,8, frente a 66,5 y 52,6 de una línea base RAG simple. Son resultados de los propios autores. El conjunto de administración electrónica es interno y la comparación en las pruebas públicas depende de líneas base ejecutadas en su propio entorno, así que conviene leerlos como evidencia sólida de que el diseño funciona en los problemas para los que se pensó, no como una replicación independiente.</p><h3>La factura, en palabras del propio artículo</h3><p>El artículo es inusualmente explícito con el coste. Su análisis de tiempos ejecuta 1.000 preguntas por conjunto con 20 tareas concurrentes y hasta tres iteraciones. La variante más simple, un recuperador de fragmentos con reflexión (CR_ref3), fue la más rápida y LFSH_ref3 la más lenta: CR_ref3 la superó en velocidad en un 149 %, un 101 % y un 134 % en los tres conjuntos. La sección de limitaciones añade que el marco «requiere múltiples llamadas al LLM en las fases de construcción y resolución» y que, como la descomposición produce a la vez subpreguntas y funciones lógicas, la planificación genera aproximadamente el doble de tokens que una descomposición simple. La planificación es además un punto único de fallo. El ejemplo del propio artículo es una pregunta del tipo «¿quién es mayor?», que debería descomponerse en comparar fechas de nacimiento, porque preguntar la edad de personas fallecidas devuelve la edad al morir y lleva a una comparación errónea. Un plan sintácticamente válido pero semánticamente equivocado se ejecuta a la perfección y devuelve un error con total seguridad. Si a eso se suma el ruido de OpenIE en el grafo sobre el que se ejecuta el plan, el cuadro es claro: el solver compra auditabilidad y cálculo exacto a cambio de latencia, tokens y un planificador que tiene que acertar.</p><p>Es un buen intercambio para preguntas en las que un número equivocado o una regla omitida salen caros, y uno caro para consultas directas que un recuperador, o una caché precargada como en <em>La recuperación es un modo de fallo: el argumento de sistemas detrás de la generación aumentada por caché</em>, resolvería sin más. El último texto de la serie, <em>RAG, CAG, KAG: un modelo de decisión según corpus, volatilidad y lógica de la consulta</em>, convierte estos compromisos en una decisión de enrutamiento.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c09ee0ac3c71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logical Forms as an Execution Plan: Inside the KAG Solver]]></title>
            <link>https://nurhayatyurtaslan.medium.com/logical-forms-as-an-execution-plan-inside-the-kag-solver-6266f417deb0?source=rss-c026048cd122------2</link>
            <guid isPermaLink="false">https://medium.com/p/6266f417deb0</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Nurhayat Yurtaslan]]></dc:creator>
            <pubDate>Sat, 31 Oct 2026 13:01:02 GMT</pubDate>
            <atom:updated>2026-10-31T13:01:02.481Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EoQ-x4ptZPGWiakUnvBqLQ.jpeg" /></figure><p>The KAG solver treats question answering as running a program. A question is first translated into a short sequence of typed function calls (a logical form) whose variables link the steps together. Each step is then executed by the operator that suits it best: a graph lookup, a text search, a sort, a deterministic calculation, or a deduction. Retrieval stops being the whole pipeline and becomes one instruction in a plan, which is what makes each step auditable and lets arithmetic be computed instead of predicted token by token. The cost is planning overhead, and the paper is candid about how large that overhead is.</p><p>The previous piece, <em>When Similarity Is Not Relevance: Why Ant Group Built KAG</em>, covered the representation side of <a href="https://arxiv.org/abs/2409.13731">KAG (Liang et al.)</a>: a three-layer knowledge structure (schema-constrained knowledge, extracted graph information, raw chunks) tied together by mutual indexing. A richer index only helps if something can query it with the right structure. A similarity search over the graph would throw away most of what the schema encodes. The solver is that something, and it was needed for the same reason the index was: multi-hop, numeric and rule-based questions fail in RAG not because the right text is unreachable, but because nothing in the pipeline represents the <em>steps</em> that connect the question to the answer.</p><h3>Why a plan, and why this kind of plan</h3><p>Iterative retrieval methods had already shown that multi-hop questions need retrieval interleaved with reasoning. <a href="https://arxiv.org/abs/2212.10509">IRCoT (Trivedi et al.)</a> made the core observation: in multi-step QA, <em>what to retrieve</em> depends on <em>what has already been derived</em>, so a single retrieve-then-read pass is not enough. IRCoT interleaves chain-of-thought sentences with retrieval calls and reports gains of up to 21 points in retrieval and 15 in QA. <a href="https://arxiv.org/abs/2407.13101">ReSP (Jiang et al.)</a> addressed two problems this creates: context overload from many retrieval rounds, and repetitive or excessive planning when no record of the trajectory is kept. It added a summariser that compresses retrieved evidence both against the overall question and against the current sub-question. Both methods still express the plan in natural language, so the intermediate state is prose: hard to check, hard to execute deterministically, and unable to say “count these” or “take the earliest” except by asking the model to do it in its head. KAG keeps the iterative loop, adapting its multi-round reflection from ReSP, and changes the representation of each step to a symbolic call.</p><p>The paper defines five functions. Retrieval(s=si:type[name], p=pi:edge, o=oi:type[name], s.prop=value, ...) fetches subject-predicate-object patterns with optional constraints on properties. Sort(A, direction=min|max, limit=n) orders a variable&#39;s results. Math(expr) evaluates an expression written in LaTeX syntax over sets or constants, such as a count or a sum, and binds the result to a new variable. Deduce(left=A, right=B, op=entailment|greater|less|equal) compares or infers. Output(A, B, ...) returns the bound results. The rules for variables do real work. When a later step refers to an earlier variable, it must reuse the same name and omit the type, which makes the plan a dataflow graph rather than a list of independent searches. Fig. 1 shows that shape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f5fCtZBa4Dx9HUwgrpr_gw.jpeg" /></figure><p><em>Fig. 1. A logical-form plan as a DAG. Each node is one operator call; edges are variable references. The illustrative expansion builds on the paper’s single-retrieval example and shows where Math and Sort slot in when a question needs them.</em></p><h3>Executing a step: graph first, text as fallback</h3><p>The paper’s worked example shows how a retrieval step carries structure that a vector query cannot. For “What documents are required to apply for a disability certificate at West Lake, Hangzhou?”, the retrieval function is Retrieval(s=s1:Event[applying for a disability certificate], p=p1:support_chunks, o=o1:Chunk, s.location=West Lake, Hangzhou). The event type, the edge to supporting chunks and the location filter are all explicit. Proper nouns, places, times and numbers, which the paper notes dense encoders represent poorly, become exact filter conditions instead of terms in a similarity score. Each sub-query then goes through the reasoner’s two-tier retrieval. GraphRetrieval tries the structured layers first, and if its result is empty or below a confidence threshold, HybridRetrieval searches the chunks, combining sparse and dense matching guided by whatever the graph did find. A generator then answers the sub-query from the retrieved material. The toy executor below captures that control flow over an in-memory graph. It is not KAG’s code, which runs against an LPG store and a vector index, but the dispatch logic has the same shape:</p><pre>PLAN = [  # logical form for the West Lake example, one call per step<br>    (&quot;Retrieval&quot;, dict(s=&quot;s1:Event[applying for a disability certificate]&quot;,<br>                       p=&quot;p1:support_chunks&quot;, o=&quot;o1:Chunk&quot;,<br>                       filters={&quot;s.location&quot;: &quot;West Lake, Hangzhou&quot;})),<br>    (&quot;Output&quot;, dict(args=[&quot;o1&quot;])),<br>]<br><br>def graph_retrieve(kg, s, p, filters):<br>    typ, name = s.split(&quot;:&quot;)[1].rstrip(&quot;]&quot;).split(&quot;[&quot;)<br>    return [o for (subj, rel, o) in kg[&quot;triples&quot;]<br>            if subj[&quot;type&quot;] == typ and subj[&quot;name&quot;] == name and rel == p.split(&quot;:&quot;)[1]<br>            and all(subj.get(k.split(&quot;.&quot;)[1]) == v for k, v in filters.items())]<br><br>def execute(plan, kg, hybrid_search, threshold=1):<br>    env = {}<br>    for op, a in plan:<br>        if op == &quot;Retrieval&quot;:<br>            hits = graph_retrieve(kg, a[&quot;s&quot;], a[&quot;p&quot;], a[&quot;filters&quot;])<br>            if len(hits) &lt; threshold:                  # GraphRetrieval miss -&gt; fallback<br>                hits = hybrid_search(a[&quot;s&quot;], a[&quot;filters&quot;])<br>            env[a[&quot;o&quot;].split(&quot;:&quot;)[0]] = hits<br>        elif op == &quot;Math&quot;:                             # deterministic, not generated<br>            env[a[&quot;var&quot;]] = a[&quot;fn&quot;](*(env[x] for x in a[&quot;args&quot;]))<br>        elif op == &quot;Output&quot;:<br>            return {x: env[x] for x in a[&quot;args&quot;]}</pre><p>The important line is the Math branch. When a question asks how many, how much, or which is earlier, the plan hands a set to a function instead of asking the model to count over text, which is precisely the “knowledge logic” weakness the KAG paper attributes to next-token prediction.</p><h3>The outer loop and the alignment layer</h3><p>Around the single-plan executor sits Algorithm 1 of the paper. LFPlanner decomposes the current query into logical forms. The Reasoner executes each one and appends the sub-query, its retrievals and its answer to a history. Memory consolidates that history. A Judge decides whether the original question is answered. If not, SupplyQuery writes a follow-up question and the loop runs again, up to <em>n</em> rounds. This is the reflection mechanism taken from ReSP, and it lets the system recover from a plan that retrieved the wrong intermediate entity. Knowledge alignment runs underneath both indexing and querying. The same synonym, hypernym and inclusion reasoning that tidied the graph at build time maps the user’s wording onto indexed concepts at query time, so that a Retrieval call on a colloquial term can still land on the canonical node.</p><h3>What the paper reports</h3><p>On multi-hop QA benchmarks, KAG with the logical-form solver using hybrid retrieval and up to three reflection rounds (LFSH_ref3, on the DeepSeek-V2 API) reports F1 of 76.2 on HotpotQA, 76.2 on 2WikiMultiHopQA and 48.7 on MuSiQue. The strongest baseline in the same table, IRCoT with HippoRAG on DeepSeek-V2, reports 63.7, 57.1 and 36.5. In Ant Group’s e-government Q&amp;A deployment, evaluated on 492 questions, KAG reports precision 91.6 and recall 71.8 against 66.5 and 52.6 for a naive RAG baseline. These are the authors’ own results. The e-government set is internal, and the benchmark comparison relies on baselines run in their setup, so read them as strong evidence that the design works on its intended problems, not as an independent replication.</p><h3>The bill, in the paper’s own words</h3><p>The paper is unusually explicit about cost. Its timing analysis runs 1,000 questions per dataset with 20 concurrent tasks and up to three iterations. The simplest variant, a chunk retriever with reflection (CR_ref3), was the fastest and LFSH_ref3 the slowest: CR_ref3 outperformed it in speed by 149%, 101% and 134% on the three datasets. The limitations section adds that the framework “requires multiple LLM calls during the construction and solving phases,” and that because decomposition outputs both sub-questions and logical functions, planning generates approximately twice as many tokens as plain decomposition. Planning is also a single point of failure. The paper’s own example is a “who is older” question, which should be decomposed into comparing birth dates, because asking for the age of people who have died returns age at death and gives the wrong comparison. A plan that is syntactically valid but semantically wrong executes perfectly and returns a confident error. Add OpenIE noise in the graph the plan runs against, and the overall picture is clear. The solver buys auditability and exact computation with latency, tokens and a planner that has to be right.</p><p>That is a sensible trade for questions where a wrong number or a missed rule is expensive, and an expensive one for lookups that a retriever, or a preloaded cache as in <em>Retrieval Is a Failure Mode: The Systems Case Behind Cache-Augmented Generation</em>, would answer directly. The final piece in this series, <em>RAG, CAG, KAG: A Decision Model by Corpus, Volatility and Query Logic</em>, turns these trade-offs into a routing decision.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6266f417deb0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cuando similitud no es relevancia: por qué Ant Group construyó KAG]]></title>
            <link>https://nurhayatyurtaslan.medium.com/cuando-similitud-no-es-relevancia-por-qu%C3%A9-ant-group-construy%C3%B3-kag-5b64de1efedf?source=rss-c026048cd122------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b64de1efedf</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[aprendizaje-automático]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Nurhayat Yurtaslan]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 18:01:02 GMT</pubDate>
            <atom:updated>2026-10-28T18:01:02.226Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5wf6MelNZLUdfe7dwUfosA.jpeg" /></figure><p>La similitud vectorial mide lo cerca que están dos textos en un espacio de embeddings. Las preguntas profesionales suelen depender de otra cosa: de si algo <em>es un tipo de</em> otra cosa, si la <em>contiene</em>, si la <em>causa</em>, si ocurrió <em>antes</em> o si <em>supera</em> un umbral fijado por una norma. Esas relaciones tienen dirección, tipo y a veces aritmética, y una puntuación de coseno no conserva ninguna. La generación aumentada por conocimiento (KAG, <em>Knowledge Augmented Generation</em>), desarrollada por el equipo de grafos de conocimiento de Ant Group, saca esas relaciones del embedding y las lleva a un grafo explícito respaldado por un esquema, sin soltar en ningún momento el vínculo entre cada elemento del grafo y el texto que lo sustenta. El diseño responde a errores de recuperación que ningún <em>reranking</em> corrige, porque nacen de lo que el índice es capaz de representar y no de lo bien que ordena.</p><p>Hasta aquí la serie ha recorrido un extremo del eje de la recuperación. <em>La recuperación es un modo de fallo: el argumento de sistemas detrás de la generación aumentada por caché</em> y los dos textos siguientes trataban CAG, que quita el recuperador cuando un corpus pequeño y estable cabe en el contexto efectivo. KAG está en el extremo opuesto. En lugar de eliminar la recuperación, le da más estructura de la que tiene RAG, y apunta a corpus más grandes, más regulados y más sujetos a reglas que cualquier ventana de contexto. El artículo, <a href="https://arxiv.org/abs/2409.13731"><em>KAG: Boosting LLMs in Professional Domains via Knowledge Augmented Generation</em> (Liang et al.)</a>, y la implementación abierta en <a href="https://github.com/OpenSPG/KAG">OpenSPG/KAG</a> describen cinco componentes. Este texto trata la representación y la indexación; <em>Formas lógicas como plan de ejecución: dentro del solver de KAG</em> se ocupa del solver.</p><h3>El fallo alrededor del que se diseñó KAG</h3><p>El planteamiento del artículo es concreto. Según los autores, RAG sufre «la brecha entre la similitud vectorial y la relevancia para el razonamiento» y una insensibilidad a la «lógica del conocimiento, como valores numéricos, relaciones temporales o reglas expertas». La sección sobre alineación del conocimiento lo desglosa en tres defectos de los índices construidos con extracción y búsqueda por similitud. El primero es la <em>desalineación de relaciones semánticas</em>: la respuesta correcta suele guardar una relación concreta con la pregunta (contiene, causa, es un) mientras que la similitud es «una medida semántica débil, sin propiedades ni dirección». El segundo es la <em>desalineación de granularidad</em>: la extracción abierta de información (OpenIE) produce muchos nodos sinónimos o casi duplicados, el grafo queda mal conectado y la recuperación es incompleta. El tercero es la <em>desalineación con la estructura del dominio</em>: conocimiento que debería estar conectado aparece fragmentado y el contenido recuperado carece del encuadre profesional que aplicaría un experto. El contexto explica el énfasis. Las aplicaciones objetivo de Ant Group eran preguntas sobre trámites de administración pública y sobre salud, donde una respuesta semánticamente cercana que pasa por alto una condición regional, un intervalo de fechas o una regla de elegibilidad es un error con consecuencias.</p><p>La recuperación basada en grafos ya era un área activa, y KAG se sitúa respecto a ella. <a href="https://arxiv.org/abs/2404.16130">GraphRAG (Edge et al.)</a> construye con un LLM un grafo de entidades y genera de antemano resúmenes por comunidades, pensado para preguntas globales sobre todo un corpus que el RAG simple no puede responder. <a href="https://arxiv.org/abs/2405.14831">HippoRAG (Gutiérrez et al.)</a> usa un grafo extraído y <em>Personalized PageRank</em> como índice de memoria a largo plazo para la recuperación multisalto, y logra con un solo paso de recuperación resultados iguales o mejores que con recuperación iterativa, a un coste mucho menor. Ambos tratan el grafo sobre todo como un mejor <em>índice de recuperación</em>. Lo que distingue a KAG es que el grafo es también un <em>sustrato de razonamiento</em> con esquema, propiedades tipadas y reglas, heredero del marco anterior del mismo equipo, <a href="https://spg.openkg.cn/en-US">SPG</a> (<em>Semantic-enhanced Programmable Graph</em>).</p><h3>LLMFriSPG: un único sistema de tipos para tres clases de conocimiento</h3><p>La capa de representación, LLMFriSPG, es la respuesta del artículo a un dilema antiguo. Los grafos de conocimiento estrictos y curados por expertos son precisos y admiten reglas lógicas, pero son caros de construir y siempre están incompletos. La extracción sin esquema es barata y amplia, pero ruidosa. En lugar de elegir, KAG mantiene ambas dentro de un mismo sistema de tipos y las enlaza con el texto original. Toma prestada la jerarquía datos-información-conocimiento y define tres capas, representadas en la Fig. 1. KG_cs, la <em>capa de conocimiento</em>, contiene conocimiento de dominio que cumple las restricciones del esquema y que ha sido «resumido, integrado y evaluado». KG_fr, la <em>capa de información de grafo</em>, contiene entidades y relaciones obtenidas por extracción. RC, la <em>capa de fragmentos originales</em>, guarda los fragmentos del documento tras una segmentación semántica. Un mismo tipo de entidad puede llevar propiedades definidas por el esquema, propiedades añadidas sobre la marcha durante la extracción y propiedades internas del sistema, entre ellas supporting_chunks, description, summary y belongTo. Las capas forman una curva explícita de coste frente a cobertura. La superior ofrece precisión y rigor lógico pero depende de trabajo manual; la inferior lo cubre todo pero no tiene estructura; la intermedia queda entre ambas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Deqp5cbeuHUwymy3rs5dNA.jpeg" /></figure><p><em>Fig. 1. Las tres capas de LLMFriSPG. Cada escalón hacia arriba gana precisión y rigor lógico a costa de cobertura y esfuerzo de construcción; la indexación mutua permite rastrear cualquier hecho estructurado hasta los fragmentos que lo sostienen.</em></p><h3>Construir el índice: fragmentación, extracción y alineación</h3><p>La indexación funciona como un pipeline en el que cada etapa existe por un fallo concreto de la anterior. Primero viene la <em>fragmentación semántica</em>. En lugar de cortar cada cierto número de tokens, KAG divide los documentos según su jerarquía estructural y la lógica de sus párrafos, de modo que cada fragmento respeta los límites de longitud del modelo y tiene coherencia temática. Los fragmentos se guardan como instancias de un tipo de entidad Chunk, con identificadores compuestos por artículo, párrafo y posición, para que el texto contiguo siga siendo contiguo en el espacio de identificadores. Después viene la extracción. Un LLM, de propósito general o el modelo afinado del propio equipo, extrae fragmento a fragmento entidades, luego eventos, luego relaciones entre entidades y, al final, enlaza cada instancia con su clase. Así se puebla KG_fr. Como OpenIE introduce ruido en dominios profesionales, el artículo añade la <em>inyección de conocimiento de dominio</em>. Los conceptos y términos del dominio se guardan antes en el grafo, una primera pasada de extracción sirve para recuperar conceptos candidatos por búsqueda vectorial y esos candidatos se inyectan en un segundo prompt de extracción, de modo que el resultado se ajusta al vocabulario del dominio. Cuando los documentos siguen una estructura fija (prospectos de medicamentos, informes de pruebas médicas, procedimientos administrativos), la <em>extracción restringida por esquema</em> sustituye a la extracción abierta en esos campos. En el marco abierto, los esquemas se declaran en un formato de texto compacto. Este es un esquema ilustrativo de servicios públicos escrito con la sintaxis de los archivos .schema de ejemplo del repositorio, con nombres visibles en español entre paréntesis donde los ejemplos originales los ponen en chino:</p><pre>namespace GovService<br><br>AdminRegion(Región administrativa): EntityType<br>    properties:<br>        desc(Descripción): Text<br>            index: Text<br><br>ServiceCategory(Categoría de servicio): ConceptType<br>    hypernymPredicate: isA<br><br>Document(Documento requerido): EntityType<br>    properties:<br>        desc(Descripción): Text<br>            index: TextAndVector<br><br>ServiceItem(Trámite público): EntityType<br>    properties:<br>        desc(Descripción): Text<br>            index: TextAndVector<br>        category(Categoría): ServiceCategory<br>        location(Ubicación): AdminRegion<br>    relations:<br>        requires(Requiere): Document<br>        handledBy(Gestionado por): AdminRegion</pre><p>Lo importante de la declaración no es la sintaxis, sino que «requiere» pasa a ser una arista tipada y dirigida de un trámite a un documento, que puede consultarse con una restricción sobre location. Una búsqueda por similitud tendría que deducir esa relación por proximidad superficial en cada consulta.</p><h3>Indexación mutua: por qué el grafo nunca va solo</h3><p>La idea más práctica del artículo es la <em>indexación mutua</em> entre grafo y texto. Cada instancia de KG_cs y KG_fr enlaza, a través de supporting_chunks, con los fragmentos de los que procede, y los fragmentos son a su vez nodos del grafo. Eso permite navegar en los dos sentidos. Desde un fragmento se llega a las entidades y relaciones que menciona y, a través de ellas, a fragmentos relacionados de otros documentos. Desde un hecho estructurado siempre se puede volver a la redacción original. El artículo enumera cuatro estructuras de datos básicas: un esquema compartido de tipos generales como Persona, Organización o Evento; un grafo de instancias; los fragmentos de texto como tipo de entidad especial; y un grafo de conceptos, con conceptos de grano fino y sus relaciones, que impulsa la alineación. En ese grafo de conceptos está la solución al problema de granularidad. Durante la indexación, el razonamiento semántico sobre sinonimia, hiperonimia e inclusión normaliza las instancias, las enlaza con conceptos y completa relaciones ausentes, de modo que las múltiples formas superficiales que produce OpenIE se reducen a nodos conectados. En el momento de la consulta, la misma alineación salva la distancia entre cómo pregunta el usuario y cómo está indexado el conocimiento. El almacenamiento sigue a la estructura: un grafo de propiedades etiquetadas guarda instancias, conceptos y enlaces, y un índice vectorial sirve el texto de fragmentos y propiedades que todavía necesita coincidencia aproximada.</p><h3>Por qué es una decisión de sistemas y no un truco de modelado</h3><p>Visto como ingeniería, KAG traslada coste del momento de la consulta al de la construcción, igual que CAG, pero en dirección contraria en cuanto a estructura. CAG gasta un prellenado del tamaño del corpus para eliminar el recuperador. KAG gasta llamadas de extracción al LLM sobre cada fragmento, además del diseño del esquema y la curación de conceptos, para que la recuperación sea precisa y el razonamiento sea ejecutable. La factura es real, y el artículo la reconoce en sus limitaciones: el marco «requiere múltiples llamadas al LLM en las fases de construcción y resolución», y el ruido de OpenIE es un problema permanente que la inyección de dominio solo reduce. El intercambio compensa cuando las preguntas que debe responder el sistema dependen de relaciones, números, fechas y reglas, y cuando equivocarse sale lo bastante caro como para justificar la construcción. Los resultados de despliegue que publica Ant Group, como la precisión y la exhaustividad en preguntas sobre administración pública, se tratan en el siguiente texto junto con el solver que los produce, y deben leerse como lo que son: la evaluación de los propios autores sobre sus propios datos. Cuando las preguntas son sobre todo consultas directas, o el corpus es lo bastante pequeño para CAG, toda esta maquinaria es sobrecoste. Dónde encaja cada opción es el tema de <em>RAG, CAG, KAG: un modelo de decisión según corpus, volatilidad y lógica de la consulta</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b64de1efedf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When Similarity Is Not Relevance: Why Ant Group Built KAG]]></title>
            <link>https://nurhayatyurtaslan.medium.com/when-similarity-is-not-relevance-why-ant-group-built-kag-9c657161e672?source=rss-c026048cd122------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c657161e672</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Nurhayat Yurtaslan]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 13:01:03 GMT</pubDate>
            <atom:updated>2026-10-28T13:01:03.734Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5wf6MelNZLUdfe7dwUfosA.jpeg" /></figure><p>Vector similarity measures how close two pieces of text are in an embedding space. Professional questions usually depend on something else: whether one thing <em>is a kind of</em> another, <em>contains</em> it, <em>causes</em> it, happened <em>before</em> it, or <em>exceeds</em> a threshold that a rule sets. Those relations have direction, type and sometimes arithmetic, and a cosine score carries none of them. Knowledge Augmented Generation (KAG), built by Ant Group’s knowledge-graph team, moves those relations out of the embedding and into an explicit schema-backed graph, while keeping every graph element tied to the source text that supports it. The design is a response to retrieval errors that no amount of reranking fixes, because the errors come from what the index can represent, not from how well it is ranked.</p><p>This series has so far looked at one end of the retrieval axis. <em>Retrieval Is a Failure Mode: The Systems Case Behind Cache-Augmented Generation</em> and the two pieces after it covered CAG, which removes the retriever when a small, stable corpus fits inside effective context. KAG sits at the other end. Instead of deleting retrieval, it gives retrieval more structure than RAG has, and it is aimed at corpora that are larger, more regulated and more rule-bound than any context window. The paper, <a href="https://arxiv.org/abs/2409.13731"><em>KAG: Boosting LLMs in Professional Domains via Knowledge Augmented Generation</em> (Liang et al.)</a>, and the open-source implementation in <a href="https://github.com/OpenSPG/KAG">OpenSPG/KAG</a> describe five components. This piece covers the representation and indexing side. <em>Logical Forms as an Execution Plan: Inside the KAG Solver</em> covers the solver.</p><h3>The failure KAG was built around</h3><p>The paper’s problem statement is specific. RAG, it argues, suffers from “the gap between vector similarity and the relevance of knowledge reasoning” and from insensitivity to “knowledge logic, such as numerical values, temporal relations, expert rules.” Its section on knowledge alignment breaks this into three defects of indexes built from extraction and similarity search. First, <em>misaligned semantic relations</em>: the right answer often stands in a specific relation to the query, such as contains, causes or isA, while similarity is “a weak semantic measure that lacks properties and direction.” Second, <em>misaligned granularity</em>: open information extraction (OpenIE) produces many synonymous or near-duplicate nodes, so the graph is poorly connected and recall is incomplete. Third, <em>misalignment with the domain’s structure</em>: knowledge that should be connected ends up fragmented, and retrieved content lacks the professional framing an expert would apply. The setting explains the emphasis. Ant Group’s target applications were government-service and health Q&amp;A, where an answer that is semantically close but misses a regional condition, a date range or an eligibility rule is wrong in a way that matters.</p><p>Graph-based retrieval was already an active area, and KAG positions itself relative to it. <a href="https://arxiv.org/abs/2404.16130">GraphRAG (Edge et al.)</a> builds an entity graph with an LLM and pregenerates community summaries, aimed at global sense-making questions over a whole corpus that plain RAG cannot answer. <a href="https://arxiv.org/abs/2405.14831">HippoRAG (Gutiérrez et al.)</a> uses an extracted knowledge graph with Personalized PageRank as a long-term-memory index for multi-hop retrieval, and reports single-step retrieval that matches or beats iterative retrieval at much lower cost. Both treat the graph mainly as a better <em>retrieval index</em>. KAG’s difference is that the graph is also a <em>reasoning substrate</em> with a schema, typed properties and rules. The authors place it in the lineage of their earlier Semantic-enhanced Programmable Graph framework, <a href="https://spg.openkg.cn/en-US">SPG</a>.</p><h3>LLMFriSPG: one type system for three kinds of knowledge</h3><p>The representation layer, LLMFriSPG, is the paper’s answer to an old trade-off. Strict, expert-curated knowledge graphs are accurate and support logical rules, but they are expensive to build and always incomplete. Schema-free extraction is cheap and broad, but noisy. Rather than choose, KAG keeps both inside one type system and links them to raw text. The paper borrows the data-information-knowledge hierarchy and defines three layers, shown in Fig. 1. KG_cs, the <em>knowledge layer</em>, holds domain knowledge that complies with schema constraints and has been “summarized, integrated, and evaluated.” KG_fr, the <em>graph information layer</em>, holds entities and relations obtained through information extraction. RC, the <em>raw chunks layer</em>, holds the original document chunks after semantic segmentation. The same entity type can carry schema-defined properties, ad-hoc properties added during extraction, and built-in system properties. The built-in ones include supporting_chunks, description, summary and belongTo. The layering is an explicit cost–coverage curve. The top layer has high precision and logical rigor but depends on manual work. The bottom layer covers everything but carries no structure. The middle layer trades between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ae6boP3YvWpc3toKQTejCQ.jpeg" /></figure><p><em>Fig. 1. The three layers of LLMFriSPG. Each step up buys precision and logical rigor at the cost of coverage and construction effort; mutual indexing keeps every structured fact traceable to the chunks beneath it.</em></p><h3>Building the index: chunking, extraction, alignment</h3><p>Indexing runs as a pipeline, and every stage exists because of a specific failure in the stage before it. <em>Semantic chunking</em> comes first. Instead of cutting at a fixed token count, KAG splits documents along their structural hierarchy and paragraph logic, so that each chunk stays within the model’s length limits and is thematically coherent. Chunks are stored as instances of a Chunk entity type, with IDs composed from article, paragraph and position, so that adjacent text stays adjacent in ID space. Extraction comes next. An LLM, either general-purpose or the team’s fine-tuned model, extracts entities, then events, then relations between the entities, chunk by chunk, and finally links each instance to its class. This populates KG_fr. Because OpenIE in professional domains introduces noise, the paper adds <em>domain knowledge injection</em>. Domain concepts and terms are stored in the graph first. A first extraction pass is used to retrieve candidate concepts by vector search, and those candidates are injected into a second extraction prompt, so that the output aligns with the domain’s vocabulary. Where documents follow a fixed structure, such as drug instructions, examination reports or government procedures, <em>schema-constrained extraction</em> replaces open extraction for those fields. Schemas in the open-source framework are declared in a compact text format. Here is an illustrative government-services schema written in the syntax of the repository’s example .schema files, with English display names in parentheses where the shipped examples use Chinese ones:</p><pre>namespace GovService<br><br>AdminRegion(Administrative region): EntityType<br>    properties:<br>        desc(Description): Text<br>            index: Text<br><br>ServiceCategory(Service category): ConceptType<br>    hypernymPredicate: isA<br><br>Document(Required document): EntityType<br>    properties:<br>        desc(Description): Text<br>            index: TextAndVector<br><br>ServiceItem(Public service item): EntityType<br>    properties:<br>        desc(Description): Text<br>            index: TextAndVector<br>        category(Category): ServiceCategory<br>        location(Location): AdminRegion<br>    relations:<br>        requires(Requires): Document<br>        handledBy(Handled by): AdminRegion</pre><p>The point of the declaration is not the syntax. It is that “requires” is now a typed, directed edge from a service to a document, which can be queried with a constraint on location. A similarity search would have had to infer that relation from surface proximity every time.</p><h3>Mutual indexing: why the graph never stands alone</h3><p>The most practical idea in the paper is <em>mutual indexing</em> between graph and text. Every instance in KG_cs and KG_fr links to the chunks it was derived from through its supporting_chunks, and chunks are themselves nodes in the graph. That gives two-way navigation. From a chunk you can reach the entities and relations it mentions, and from there related chunks in other documents. From a structured fact you can always return to the original wording. The paper lists four core data structures: a shared schema of coarse types such as Person, Organization or Event, an instance graph, text chunks as a special entity type, and a concept graph of fine-grained concepts and their relations, which drives alignment. The concept graph carries the fix for the granularity problem. During indexing, semantic reasoning over synonym, hypernym and inclusion relations standardises instances, links them to concepts and completes missing relations, so that the many surface forms OpenIE produces collapse into connected nodes. During query time, the same alignment bridges the gap between a user’s phrasing and the indexed form. Storage follows the structure: a labelled-property graph holds instances, concepts and their links, and a vector index serves the chunk and property text that still needs fuzzy matching.</p><h3>Why this is a systems decision, not a modelling trick</h3><p>Seen as engineering, KAG moves cost from query time to build time, much as CAG does, but in the opposite direction on structure. CAG spends a corpus-sized prefill to remove the retriever. KAG spends LLM extraction calls over every chunk, plus schema design and concept curation, to make retrieval precise and reasoning executable. The bill is real and the paper acknowledges it in its limitations: the framework “requires multiple LLM calls during the construction and solving phases,” and OpenIE noise is a standing problem that domain injection only reduces. The trade pays off when the questions the system must answer turn on relations, numbers, time and rules, and when getting them wrong is costly enough to justify the build. Ant Group’s reported deployment results, such as precision and recall on government Q&amp;A, are covered in the next piece together with the solver that produces them, and they should be read as what they are: the authors’ own evaluation, on their own data. When the questions are mostly lookups, or the corpus is small enough for CAG, this machinery is overhead. Where each option belongs is the subject of <em>RAG, CAG, KAG: A Decision Model by Corpus, Volatility and Query Logic</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c657161e672" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caché de prefijos en producción: de la CAG del paper a los motores de inferencia]]></title>
            <link>https://nurhayatyurtaslan.medium.com/cach%C3%A9-de-prefijos-en-producci%C3%B3n-de-la-cag-del-paper-a-los-motores-de-inferencia-16cc27c83819?source=rss-c026048cd122------2</link>
            <guid isPermaLink="false">https://medium.com/p/16cc27c83819</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[aprendizaje-automático]]></category>
            <dc:creator><![CDATA[Nurhayat Yurtaslan]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 18:01:01 GMT</pubDate>
            <atom:updated>2026-10-26T18:01:01.594Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cBTpbc-RRSUoPdZboUqwxQ.jpeg" /></figure><p>La primitiva de la que depende la generación aumentada por caché, calcular una vez la caché clave-valor de un prefijo fijo y reutilizarla para muchas continuaciones, ya viene integrada en los motores de inferencia modernos y en las API comerciales con el nombre de caché de prefijos (<em>prefix caching</em>). Llevar CAG a producción no consiste, por tanto, en reimplementar el bucle de cachear y truncar del artículo, sino en tomar tres decisiones de ingeniería que el artículo no necesita tomar: cómo se indexa el estado en caché, cómo se desaloja cuando falta memoria y cómo se organizan los prompts para que la parte cara sea de verdad un prefijo compartido.</p><p>La versión de investigación de <a href="https://arxiv.org/abs/2412.15605">CAG (Chan et al., 2024)</a>, comentada en <em>La recuperación es un modo de fallo: el argumento de sistemas detrás de la generación aumentada por caché</em>, ejecuta un modelo, mantiene un único DynamicCache y atiende las consultas una tras otra, recortando la caché hasta la longitud del corpus después de cada respuesta. Es una demostración correcta y un servidor pobre: hay una sola copia residente, las peticiones se serializan y la vida de la caché depende de un proceso de Python. <em>La ventana de contexto que tienes y la que puedes usar: los límites de CAG</em> explicaba por qué importa: para Llama 3.1 8B, una caché de 85k tokens ocupa unos 10 GiB en 16 bits, así que copiarla por petición no es viable, y atender a muchos usuarios exige que el motor comparta una única caché física entre secuencias concurrentes. Los motores de inferencia llegaron a esa capacidad por motivos propios, y por eso sus decisiones de diseño son el lugar donde mirar.</p><h3>Por qué los motores de inferencia necesitaban compartir estado KV de todos modos</h3><p>El primer problema fue la fragmentación de memoria, no CAG. El <a href="https://arxiv.org/abs/2309.06180">artículo de vLLM de Kwon et al.</a> parte de que la caché KV de cada petición es grande, crece y decrece de forma dinámica, y que reservarla como una región contigua por petición desperdicia memoria por fragmentación y duplicación, lo que a su vez limita el tamaño de lote. PagedAttention toma prestada la memoria virtual de los sistemas operativos: la caché se divide en bloques de tamaño fijo, cada secuencia tiene una tabla de bloques que traduce posiciones lógicas a bloques físicos y los bloques pueden compartirse entre secuencias con copia en escritura. El artículo informa de un rendimiento entre 2 y 4 veces mayor que el de los sistemas comparados, con la misma latencia. Si los bloques ya pueden compartirse, compartirlos <em>entre peticiones</em> que empiezan por los mismos tokens es un paso pequeño. La <a href="https://docs.vllm.ai/en/latest/features/automatic_prefix_caching.html">caché automática de prefijos de vLLM</a> hace exactamente eso, y su documentación describe sin rodeos la carga de trabajo de CAG: un documento largo, como un manual o un informe anual, consultado una y otra vez con preguntas distintas, procesado una sola vez y reutilizado por todas las peticiones posteriores.</p><p>El esquema de claves es donde se nota el pensamiento de sistemas. Las <a href="https://docs.vllm.ai/en/latest/design/prefix_caching.html">notas de diseño de vLLM</a> describen un enfoque basado en hashes. Cada bloque KV completo se identifica con un hash que combina el hash del bloque padre, los tokens del bloque y claves adicionales como identificadores de adaptadores LoRA, hashes de entradas multimodales o una sal de caché que aísla a los distintos inquilinos. Solo se cachean bloques completos, y las versiones actuales usan SHA-256 por defecto para descartar colisiones. Como cada hash incluye el del padre, un bloque solo es reutilizable si <em>todo lo anterior</em> es idéntico: la invariante de la caché KV del artículo de CAG, convertida en estructura de datos. <a href="https://arxiv.org/abs/2312.07104">SGLang (Zheng et al.)</a> llega al mismo resultado con otra estructura. RadixAttention guarda los prefijos cacheados en un árbol radix, busca para cada petición entrante el prefijo almacenado más largo y desaloja hojas con una política LRU, lo que abarata compartir en cargas ramificadas como prompts con ejemplos, chats de varios turnos o bucles de agentes. SGLang informa de hasta 6,4 veces más rendimiento en cargas que incluyen pipelines de recuperación. La Fig. 1 muestra la estructura que, en la práctica, mantienen ambos motores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8PcGH5khCHHKfZCogEsgjg.jpeg" /></figure><p><em>Fig. 1. Prefijos compartidos como árbol radix. Todo lo que queda a la izquierda de una bifurcación se calcula una vez y se reutiliza; un cambio en cualquier punto del camino (aquí, una nueva versión de la plantilla) abre una rama nueva que paga su propio prellenado.</em></p><h3>El bucle del artículo, reescrito como configuración</h3><p>Con un motor que hace caché de prefijos, el patrón CAG se convierte en una disciplina de construcción de prompts más un parámetro. El corpus va en un prefijo fijo, idéntico byte a byte entre peticiones, y solo varía el sufijo. La primera petición paga el prellenado; las siguientes encuentran en caché los bloques de todo el corpus y solo calculan los tokens de su propia consulta:</p><pre>from vllm import LLM, SamplingParams<br><br>CORPUS = open(&quot;manual.txt&quot;).read()           # estable, versionado, nunca se edita en sitio<br>PREFIJO = (&quot;Responde solo a partir del manual siguiente.\n\n&quot;<br>           f&quot;&lt;manual version=&#39;2026-10-01&#39;&gt;\n{CORPUS}\n&lt;/manual&gt;\n\n&quot;)<br><br>llm = LLM(model=&quot;meta-llama/Llama-3.1-8B-Instruct&quot;,<br>          enable_prefix_caching=True,          # reutilización de bloques KV por hash<br>          max_model_len=32768)                 # dimensionar al contexto efectivo, no al nominal<br>params = SamplingParams(temperature=0.0, max_tokens=256)<br><br>llm.generate([PREFIJO + &quot;Pregunta: ¿Cuál es el plazo de devolución?\nRespuesta:&quot;], params)  # calienta la caché<br>preguntas = [&quot;¿Quién aprueba un viaje fuera de presupuesto?&quot;, &quot;¿Cómo se incorpora a un contratista?&quot;]<br>salidas = llm.generate([PREFIJO + f&quot;Pregunta: {q}\nRespuesta:&quot; for q in preguntas], params)</pre><p>No hay paso de reinicio, porque el motor nunca modifica los bloques compartidos. Cada secuencia añade sus propios bloques detrás de los compartidos y se liberan al terminar la petición. La concurrencia sale gratis, porque muchas secuencias apuntan a los mismos bloques físicos del corpus. max_model_len es el punto donde el argumento del contexto efectivo del texto anterior se convierte en configuración. En las versiones recientes de vLLM la caché de prefijos viene activada por defecto, así que el parámetro explícito documenta la intención más que cambiar el comportamiento.</p><p>Las API alojadas exponen el mismo mecanismo con un contrato explícito. El <a href="https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching"><em>prompt caching</em> de Anthropic</a> cachea el prefijo completo (herramientas, después sistema y después mensajes, en ese orden) hasta un bloque marcado con cache_control. Tiene una vida por defecto de cinco minutos que se renueva con cada uso, con una opción de una hora a mayor coste, y las lecturas de caché se facturan a una fracción del precio normal de entrada. La regla de orden es otra vez la invariante del árbol radix, escrita como documentación de API. Si cambia la definición de una herramienta, se invalida todo lo posterior, incluido un corpus colocado en el prompt de sistema.</p><h3>La disposición del prompt es la decisión de diseño</h3><p>Como la reutilización exige un prefijo idéntico, la decisión de producción con más consecuencias es qué va primero. Lo más estable debe ir antes: las instrucciones de sistema, luego el corpus en un orden determinista y con etiqueta de versión, después lo que varía por sesión y, al final, la consulta. Los fallos habituales son prosaicos. Una marca de tiempo o un identificador de petición en el prompt de sistema hace que cada prefijo sea único y la tasa de aciertos cae a cero. Serializar los documentos sin orden fijo (el orden de iteración de un diccionario, una consulta a base de datos sin ORDER BY) baraja el corpus entre despliegues. Una edición de la plantilla al principio invalida sin avisar una caché de corpus que nadie ha tocado. La tokenización endurece aún más los límites, porque la unidad cacheada es un bloque completo de tokens y no un rango de caracteres, así que un cambio de espacios en una frontera basta para provocar un fallo. Son problemas de observabilidad tanto como de diseño: un panel de servicio debería mostrar la tasa de aciertos de la caché de prefijos por ruta, y una caída brusca tras un despliegue es la señal más clara de que se ha roto una invariante de disposición.</p><p>El desalojo es la otra mitad. Un prefijo de corpus al estilo CAG solo tiene valor mientras sigue residente, y con LRU compite con historiales de conversación y con prefijos de otros inquilinos. Los motores lo gestionan combinando reservas de bloques, descarga a memoria del host o a niveles más lentos y sales por inquilino. En la práctica, un corpus compartido grande suele servirse desde un despliegue dedicado, o al menos desde una ruta dedicada, para que el tráfico ajeno no lo expulse.</p><h3>Más allá de los prefijos estrictos: TurboRAG y CacheBlend</h3><p>La caché de prefijos solo ayuda cuando el texto reutilizable está delante. El RAG clásico rompe esa condición: los fragmentos recuperados cambian en cada consulta y llegan en distinto orden, así que el estado KV de cada fragmento depende de lo que lo precede en ese prompt concreto. Dos líneas de trabajo atacan justo este caso y marcan el espacio híbrido entre CAG y RAG. <a href="https://arxiv.org/abs/2410.07590">TurboRAG</a> precalcula y almacena fuera de línea la caché KV de cada documento y carga directamente las cachés recuperadas en el prellenado. Resuelve el desajuste de posiciones y de máscara de atención que eso provoca ajustando el tratamiento posicional y afinando el modelo, e informa de reducciones del tiempo hasta el primer token de hasta 9,4 veces (8,6 de media) frente al RAG convencional, con calidad comparable. <a href="https://arxiv.org/abs/2405.16444">CacheBlend</a> no toca el modelo. Reutiliza cachés de fragmentos precalculadas formen o no un prefijo, y vuelve a calcular de forma selectiva los valores KV de un pequeño subconjunto de tokens para recuperar la atención cruzada entre fragmentos que se pierde al precalcularlos por separado, solapando ese recálculo con la carga de las cachés desde almacenamiento más lento. Ambos conservan el recuperador y eliminan la mayor parte de su coste de prellenado, la otra mitad de la latencia por consulta que la Fig. 1 del primer texto atribuía a RAG.</p><h3>Qué cambia en la decisión entre RAG y CAG</h3><p>La caché de prefijos en producción desplaza la pregunta: ya no es «¿implemento CAG?», sino «¿tiene mi carga forma de prefijo?». Cuando muchas peticiones comparten un prefijo largo y estable, el motor ya ofrece el perfil de latencia de CAG, y los límites que quedan son los del artículo: contexto efectivo, memoria KV e invalidación. Cuando el contenido compartido varía en cada consulta, la reutilización de KV por fragmentos reduce la diferencia de coste sin renunciar a la recuperación. Ninguna de las dos ayuda cuando la dificultad no es la longitud, sino las relaciones, los números y las reglas. Ese es el problema que abordan los dos textos siguientes, empezando por <em>Cuando similitud no es relevancia: por qué Ant Group construyó KAG</em>, antes de que <em>RAG, CAG, KAG: un modelo de decisión según corpus, volatilidad y lógica de la consulta</em> vuelva a reunir las tres opciones.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16cc27c83819" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>