<?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 Juraj Macák on Medium]]></title>
        <description><![CDATA[Stories by Juraj Macák on Medium]]></description>
        <link>https://medium.com/@jurajmacak?source=rss-ce7d1828a5db------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Mh0gf51DIGXkaK1GQ2Y_6A.jpeg</url>
            <title>Stories by Juraj Macák on Medium</title>
            <link>https://medium.com/@jurajmacak?source=rss-ce7d1828a5db------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 21:38:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jurajmacak/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[Reverting the code doesn’t revert the agent]]></title>
            <link>https://medium.com/avenga/reverting-the-code-doesnt-revert-the-agent-7e4f42293113?source=rss-ce7d1828a5db------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e4f42293113</guid>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[developer-experience]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Juraj Macák]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 14:08:47 GMT</pubDate>
            <atom:updated>2026-11-09T14:08:47.740Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LiYmt3UfI6Bp8nnpQUjklg.png" /></figure><h3>Code and context are two different states. Working safely with coding agents means knowing which one you’re changing.</h3><p>November 2025. Antigravity, Google models, and the first thing I ever built with an agent: about 2,000 lines of code that didn’t run.</p><p>I had no idea how to fix it. I’d open the files and follow maybe a third of what was there, and nothing on my screen showed me what the agent had taken in along the way. Nothing to correct, nothing to step in front of. My only lever was to go back, rewrite the prompt, and run it again. So I got good at prompts instead, and every round came back slightly better and broke somewhere new.</p><p>Took me longer than I’d like to admit to hear what that was telling me. I wasn’t controlling the code. I’d never been controlling the code.</p><blockquote><strong><em>TL;DR:</em></strong><em> Pause, override and reverse look like controls over your codebase. They’re controls over the model’s context, and most tools won’t tell you which half of the job you just did.</em></blockquote><h3>1. What the three controls actually touch</h3><p>Before the argument, the vocabulary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LbrzRen6mKnkRiWSF8UM3w.png" /><figcaption>Pause, override and reverse: what each does to the repo and to the model’s context.</figcaption></figure><p>Reerse first, because that’s the one that taught me the other two.</p><h3>2. Reverse is two operations</h3><p>I was adding <a href="https://developer.apple.com/documentation/foundationmodels">Apple’s Foundation Models</a> framework to an iOS app. On-device inference, offline, new in iOS 26, and new enough that the model I was working with didn’t really know it existed.</p><p>So it was invented. It reached for Vision and started proposing ways to solve the problem there, none of which were possible. I was very sure about this.</p><p>I could have argued with it. I have argued with it before, at length. What worked was going back to the planning stage, restarting the section, and handing the agent a tool that could pull the current Foundation Models documentation. After that, it was ordinary work.</p><p>Reverting the Vision-flavoured implementation would have produced another Vision-flavoured implementation, because the reason it wrote the first one was still sitting in the context window.</p><p><strong>Git restores files. It doesn’t restore what the model believes about the files.</strong> Revert, say “carry on,” and the same idea comes back in a different shape. <strong>You’ve undone one of the two copies of your project.</strong></p><p>Claude Code has had <a href="https://code.claude.com/docs/en/checkpointing">checkpointing</a> since v2.0.0, and it makes the split visible. /rewind, or <strong>Esc</strong> twice on an empty prompt, and the menu asks whether you want the code back, the conversation back, or both. A checkpoint gets written on every prompt you send. The documentation recommends restoring both by default, because a mismatch between what the model thinks is on disk and what&#39;s actually there sends behaviour sideways.</p><p>So the tool has already conceded that reverse is two operations. Most people press the one that does half.</p><p>The rule I’d hand anyone starting out: <strong>when the output is wrong because the thinking behind it is wrong, go back to the checkpoint before it, and don’t correct forward</strong>. Correcting forward keeps the wrong version, your correction, and the model’s reasoning about both. <strong>Do that three times in one session and you’ve stopped debugging code. You’re debugging a transcript.</strong></p><h3>3. Override can only add</h3><p>I have a rule against magic numbers. It’s in the project instructions. It isn’t subtle, and for a long stretch I’d watch a model write one anyway.</p><p>I’d point at it. It would apologise, agree the rule was clear, fix that line, and undertake not to do it again. Two steps later, another one. I got properly annoyed about this before I understood it.</p><p>Override adds, and that’s all it does. My correction doesn’t delete the wrong idea. It lands next to the wrong idea and competes with it, and I’m correcting one decision inside a context I didn’t write, against a plan I never saw.</p><p><strong>That isn’t authority. That’s a vote.</strong></p><p>Context can be trimmed, to be clear. Edit the earlier message, clear the session, rewind the conversation and leave the files alone. All of those remove something, and all of them are a different action from correcting. They’re just not where anyone’s hands go in the middle of an argument, and I include myself in that.</p><h3>4. Rules the model can’t argue with</h3><p>I can write “never delete a directory recursively” in CLAUDE.md. It mostly works.</p><p>Mostly, because that line is an instruction, which makes it input to the model, which means it competes for attention with everything else in the window. A Jira ticket. A README from some package pulled in three levels down. A comment in the code. Any of them can outweigh it, and none of them will tell you when they did.</p><p>A hook isn’t input. It’s a process that runs before the tool call and returns a verdict, and the model gets no say in it. Can’t be talked round, can’t be rewritten, can’t be skipped. That’s where the things that must not happen even once belong.</p><p>So I wrote one. It’s mine rather than the team’s, and it sits on PreToolUse <a href="https://code.claude.com/docs/en/hooks#pretooluse">matching</a> Bash|Write|Edit, the three tools that change anything outside the context window. Recursive deletes pointed at a home directory or a system root, downloads piped straight into a shell, force pushes to protected branches, that sort of thing.</p><blockquote><em>A </em><em>PreToolUse hook in Claude Code receives the tool call as JSON on </em><em>stdin and returns a decision on </em><em>stdout. The structured form is a </em><em>hookSpecificOutput object with </em><em>permissionDecision set to </em><em>deny and a </em><em>permissionDecisionReason string, exiting </em><em>0. Where that isn&#39;t available, writing the reason to </em><em>stderr and exiting </em><em>2 blocks the call as well. Any other non-zero exit produces a hook error, and the model never receives the explanation.</em></blockquote><p>The reason string goes to the model rather than into a log. Mine ends by telling it that if it really intends this, it should ask me to run the command myself, outside the agent. Without that line, a blocked model goes looking for another way round.</p><p>Writing the patterns is joyless work, incidentally. Shell quoting, flag permutations, four different ways to spell the same recursive delete. Nobody thanks you for it and there’s no point at which you can tell it’s finished.</p><p>Which brings me to the part I enjoyed least. The first time I tried to write this up, the hook blocked me.</p><p>I was writing the file with a heredoc, and the text contained examples of the dangerous commands. From the hook’s side, a heredoc is one enormous tool_input.command, and it found a recursive delete flag and a dangerous target sitting there in my prose. Blocked.</p><p>I could fix that. Detect the heredoc, skip its body. I’m not going to, because that’s a free bypass for anyone who reads the source: wrap the command in a heredoc and the guard stops seeing it. <strong>A false positive with a cheap workaround beats a hole.</strong></p><p><strong>A barrier that works on its author is a barrier that works.</strong></p><h3>5. What it costs</h3><p>For a while I overdid it.</p><blockquote><em>⚠️ Hooks buy you a guarantee about what the model can reach. They don’t buy you quality, and you pay for them in wall-clock time on every run.</em></blockquote><p>Eight was my ceiling. Past that, the agent starts routing around them: it wants something, gets a deny, tries a different way to the same place. Sessions got longer. The code coming out the other end didn&#39;t get better.</p><p>Per project, I’m down to one. It fires when a session ends and files have changed, puts the linter over them, and if the linter complains, the model fixes it before we’re finished.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o_EFxyfNETIlV3cyU5S-Jw.png" /></figure><h3>6. Pause, moved forward</h3><p>I barely use rewind any more. Not because it stopped working, but because I moved the control forward.</p><p>The work is spec-driven with a human in the loop now: I read what the agent plans to do, adjust the plan, and only then let it run. Most of what I used to rewind, I no longer generate.</p><p>Pause is the only one of the three that leaves both copies clean. Nothing written, nothing believed, nothing to undo in either place. It’s also the one I understood last, because it costs something up front and pays it back invisibly, which makes it very easy to skip.</p><p>Anything touching a live service, a deployment or a migration doesn’t get a tool at all. I have the agent write the script. I read it and run it myself. That’s more caution than my own record justifies, and I’m keeping it, because a wrong command against a live site doesn’t cost you the command; it costs you whatever was standing behind it.</p><p>Past that line, there’s no context to restore and no files to check out.</p><h3>7. Key takeaways</h3><ul><li><strong>Check which restore your tool just did.</strong> Code, conversation, or both. If it only offers one, you’re doing the other by hand whether you meant to or not.</li><li><strong>Put the rules that matter outside the prompt.</strong> Anything in CLAUDE.md is competing with a Jira ticket for attention.</li><li><strong>Count your hooks.</strong> Mine peaked at eight and cost me time for weeks before I noticed where it was going.</li><li><strong>Review the plan, not the diff.</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e4f42293113" width="1" height="1" alt=""><hr><p><a href="https://medium.com/avenga/reverting-the-code-doesnt-revert-the-agent-7e4f42293113">Reverting the code doesn’t revert the agent</a> was originally published in <a href="https://medium.com/avenga">Avenga</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why your Claude Code sessions burn out so fast]]></title>
            <link>https://medium.com/@jurajmacak/why-your-claude-code-sessions-burn-out-so-fast-bda153b5d246?source=rss-ce7d1828a5db------2</link>
            <guid isPermaLink="false">https://medium.com/p/bda153b5d246</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[claude]]></category>
            <dc:creator><![CDATA[Juraj Macák]]></dc:creator>
            <pubDate>Thu, 07 May 2026 12:04:05 GMT</pubDate>
            <atom:updated>2026-05-07T12:09:53.809Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jdwsIT9Y1dQeqenQo9N3hw.png" /></figure><p>The past few months have been noisy. Users on Claude Max plans hitting their limits mid-task, threads piling up on X, Anthropic shipping a peak-hours adjustment and then reversing course. Last week they doubled the hourly limits for Pro and Max accounts and killed the peak-hour throttling entirely.</p><p>Good news. But it also kind of misses the point.</p><p>For most people running out of budget, the problem isn’t the limits. It’s <strong>context hygiene</strong>.</p><blockquote><strong>TL;DR</strong> — Claude re-reads the entire conversation on every message. That cost compounds exponentially, not linearly. A handful of habits cuts your effective usage in half, sometimes more. Some of them aren’t obvious at all.</blockquote><h3>The cost compounds, it doesn’t add</h3><p>Every time you send a message, Claude reads the entire conversation from scratch. Message 1 through whatever you just sent, plus your CLAUDE.md, plus any active MCP tool definitions, plus system prompt overhead. All of it, every turn.</p><p>Message 1: maybe 500 tokens. Message 30: maybe 15,000, because it’s also re-reading messages 1 through 29. By message 30, the cumulative total is already somewhere north of 200,000 tokens. Same work, fresh session: a fraction of that.</p><p>Before I type my first message in an active project, I’m usually sitting at 50,000+ tokens. System prompt, tools, CLAUDE.md and loaded skills. Invisible overhead, every turn. Run /context once in a session you think is going fine and you&#39;ll see what&#39;s actually happening.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oudKjfJfkpaF5L1khM0qBg.png" /></figure><h3>More context, worse output</h3><p>Here’s the part that surprised me: a longer conversation doesn’t just cost more. It often produces worse results.</p><p>Liu et al. published <a href="https://arxiv.org/abs/2307.03172">“Lost in the Middle”</a> in 2023, a paper that looked at how language models actually use long contexts. The finding: performance degrades for information sitting in the middle of the context window. Models attend well to what’s at the start and the end. What’s sandwiched in between gets partially ignored. U-shaped performance curve, consistent across models.</p><p>So by message 30, you’re paying 31 times what message 1 cost, and the model is probably not making full use of half the context it’s rereading. Paying more, getting less.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mJe9Rkvaj2HSLIXMh_k3bQ.png" /></figure><h3>The habits that actually changed my usage</h3><p>I’m not going to list all things. Most of them are variations on the same two ideas anyway: <strong>start fresh often, and keep what Claude loads small</strong>. Here are the ones that made the biggest actual difference.</p><h3>/clear between unrelated tasks</h3><p>This one has the biggest impact and is the easiest to understand once you get how compounding works. Starting a fresh conversation resets the cost curve to zero. You lose no real context. If the previous task is done, that history is just weight.</p><p>It feels wrong at first. Like you’re throwing away work. You’re not. The output is already there. The conversation history is not the output.</p><h3>Compact before you’re forced to</h3><p>Claude Code auto-compacts your context at around 95% capacity. By that point, you’ve already paid for a lot of low-value reprocessing, and the quality has started to slip from context overload.</p><p>I compact manually at around 60%, with specific instructions on what to keep:</p><pre>/compact Keep: current task spec, which files we&#39;ve changed, any open decisions.<br>Drop: debug output, intermediate attempts, everything before we landed on the current approach.</pre><p>After three or four manual compacts in a row, quality does start to degrade. At that point, get a session summary via /context, clear, and continue fresh.</p><h3>The 5-minute cache cliff</h3><p>This one isn’t obvious until you understand how prompt caching works. Claude caches your context between messages. Reading from that cache costs about 10% of a full re-read. The default cache expires after 5 minutes of inactivity.</p><p>Step away for coffee, come back, send a message: you’ve just paid full price to re-read everything that was previously cached.</p><p>The part the video I was watching didn’t mention: Anthropic quietly reduced this TTL from one hour to five minutes in early March 2026. This is almost certainly why people started noticing sessions getting more expensive around that time. It wasn’t just usage patterns. The caching that was absorbing re-read costs was silently removed.</p><p>The fix is simple. If you’re stepping away for longer than a few minutes, run /compact or /clear first. Don&#39;t let the cache expire and rebuild itself silently at full cost.</p><blockquote>⚠️ <strong>If sessions started feeling heavier around March 2026</strong>, this cache TTL regression is the likely reason. The <a href="https://github.com/anthropics/claude-code/issues/46829">GitHub issue</a> has the details.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uYNMH7s6txm2OTKTNBnkCw.png" /></figure><h3>CLAUDE.md as index, not encyclopedia</h3><p>CLAUDE.md loads into context on every single message. Not every session. Every. Message.</p><p>If it’s 800 lines, every “fix this typo” you type costs 800 lines of context overhead first. Keep it under 200 lines. Point to other files rather than embedding their content. “Architecture decisions: see docs/architecture.md&quot; is essentially free at message time. Pasting the architecture doc directly into CLAUDE.md means you&#39;re paying for it every turn, whether you need it or not.</p><p>The mental model I use: CLAUDE.md is a routing table. It tells Claude where to look, not what to know.</p><h3>Batch prompts; edit rather than follow up</h3><p>Three separate messages cost roughly three times the tokens of one combined message, because of how the history accumulates. But the worse problem is follow-up corrections. If you spot something wrong and send a fix, that wrong exchange stays in context forever, costing tokens every turn for the rest of the session.</p><p>Edit the original message and regenerate instead. The bad exchange disappears.</p><h3>Match the model to the task</h3><p>Sonnet for most coding work. Haiku for sub-agents on simple tasks: research synthesis, formatting, reorganizing files. Opus when the reasoning actually requires it, which is less often than you’d think.</p><p>Agent workflows cost roughly 7 to 10 times more tokens than a single-agent session, because each spawned sub-agent loads its own full context. If you’re reaching for multi-agent setups out of habit rather than necessity, you’re paying a significant multiplier.</p><h3>Visibility first</h3><p>Before any of the habits above stick, you need to see what’s happening. Two commands:</p><ul><li>/context — breakdown of what&#39;s eating your tokens right now: conversation history, MCP overhead, loaded files, system tools</li><li>/cost — actual token usage and estimated spend for the current session</li></ul><p>Set up the status line in terminal (/status-line) and you get the context percentage inline while you work. Hard to overspend when you can see the gauge.</p><p>Peak hours are gone for Pro and Max as of May 6. That helps. But if you’re burning through a session in an hour, you’re almost certainly carrying context you don’t need. Not running into a hard compute ceiling. The compounding model is the mental shift. Once it clicks, the habits follow.</p><h3>Key takeaways</h3><ul><li><strong>Use /clear between tasks.</strong> The cost resets to zero. Conversation history after a finished task is pure overhead, not useful context.</li><li><strong>Compact at 60%, not 95%</strong> — auto-compact kicks in after quality has already started slipping</li><li><strong>Step away? Compact or clear first.</strong> The 5-minute cache TTL means coming back cold costs as much as starting fresh, without any of the benefits.</li><li><strong>Keep CLAUDE.md under 200 lines</strong> — it loads on every message, not every session; treat it like a routing table, not a knowledge dump</li><li><strong>Edit instead of following up</strong> — corrections stacked onto history cost tokens for the rest of the session</li><li><strong>Sonnet by default, Haiku for sub-agents.</strong> Agent teams cost 7–10x. Use them when the work earns it, not out of habit.</li></ul><p><em>Sources: </em><a href="https://aclanthology.org/2024.tacl-1.9/"><em>Liu et al. 2023, “Lost in the Middle” — ACL Anthology</em></a><em> · </em><a href="https://platform.claude.com/docs/en/build-with-claude/prompt-caching"><em>Anthropic prompt caching docs</em></a><em> · </em><a href="https://github.com/anthropics/claude-code/issues/46829"><em>Cache TTL regression — GitHub issue #46829</em></a><em> · </em><a href="https://9to5google.com/2026/05/06/claude-code-is-getting-higher-usage-limits-doubled-for-most-users/"><em>Claude Code limit changes, May 6 2026</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bda153b5d246" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Context engineering: model je dôležitý, ale kontext viac]]></title>
            <link>https://medium.com/@jurajmacak/context-engineering-skuto%C4%8Dn%C3%A1-sila-nie-je-v-modeli-ale-v-kontexte-f61888b34d66?source=rss-ce7d1828a5db------2</link>
            <guid isPermaLink="false">https://medium.com/p/f61888b34d66</guid>
            <dc:creator><![CDATA[Juraj Macák]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 18:49:51 GMT</pubDate>
            <atom:updated>2026-04-19T07:03:53.580Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Zhrnutie:</strong> Context engineering je o tom, ako AI model <strong>nakŕmiš, </strong>čo mu dáš do vstupu, v akej forme a v akom rozsahu, aby z neho vypadli lepšie výsledky. Dlho som sa sústredil na model, ale v praxi som zistil, že oveľa viac rozhoduje kvalita a štruktúra kontextu. V článku ukazujem, prečo viac kontextu nemusí byť vždy lepšie, kde sa to typicky pokazí a aké techniky sa mi pri návrhu kontextu najviac osvedčili.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Id-PhmsWyV0WThHtX0E6oQ.png" /><figcaption>Starý spôsob (vibe coding) vs context engineering</figcaption></figure><p>Nedávno som sa bavil na jednom projekte a pomocou AI generoval texty. Model bol dobrý, prompt slušný, alevýsledky priemerné. Skúšal som rôzne formulácie, menil tón inštrukcií ahľadal čo sa deje. A potom som si všimol to, čo som mal vidieť od začiatku. Model dostával príliš veľa informácií naraz, zle usporiadaných, bez jasnej hierarchie. Nereagoval zle preto, lebo by bol “hlúpy”. Reagoval zle, pretože jeho kontext tvoril “guľáš” nesprávnych informácii. To bol moment, keď som začal premýšľať o kontexte ako o skutočnej inžinierskej disciplíne, nie ako o vedľajšom efekte promptingu.</p><h3>Čo to vlastne je Context Engineering</h3><p><a href="https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents">Anthropic to definuje</a> ako “súbor stratégií pre výber a udržiavanie optimálnej sady tokenov počas inferencie LLM.” Jednoduchšie: <strong>context engineering je spôsob,</strong> <strong>akým navrhujeme a spravujeme informácie, ktoré posielame do AI systému</strong>. Zahŕňa prompty, získané dokumenty, históriu konverzácie, výstupy z nástrojov, všetko čo model dostane predtým, než začne generovať odpoveď.</p><blockquote>Model nečíta text ako ľudia, slovo po slove. Rozkladá ho na menšie jednotky zvané <strong>tokeny</strong>. Jedno anglické slovo je zhruba jeden token, slovenské slová bývajú dlhšie, takže ich môže pokryť viac tokenov. Jedna A4 strana textu je zhruba 500–700 tokenov. Počet tokenov, ktoré model dokáže spracovať naraz, sa nazýva “context window”, okno kontextu. <strong>Inferencia</strong> je moment, keď model generuje odpoveď . Keď “premýšľa”. Nie je to tréning (kde sa model učí z dát), ale samotné použitie natrénovaného modelu. Každá vaša otázka spúšťa jednu inferenciu.</blockquote><p>Cieľ je konkrétny. Nájsť najmenšiu sadu vysoko efektívnych tokenov, ktoré maximalizujú pravdepodobnosť správneho výstupu. V praxi je to jedna z najdôležitejších a najmenej docenených vrstiev celého systému. Existujú štyri základné typy kontextu:</p><ul><li>statický (systémové prompty a pravidlá, ktoré sa nemenia),</li><li>dynamický (dokumenty a dáta, ktoré sa menia pri každej požiadavke),</li><li>interakčný (história konverzácie)</li><li>nástrojový (výstupy z externých API alebo databáz). Každý z nich môže byť zdrojom problémov, ak ho nespravujeme vedome.</li></ul><p>Statický kontext je v podstate to, čo som pred časom nazýval inštrukciou a <a href="https://medium.com/@jurajmacak/pre%C4%8Do-u%C5%BE-nep%C3%AD%C5%A1em-v%C5%A1etko-do-jedn%C3%A9ho-promptu-fe500779cc5f">o tom, prečo ju treba oddeliť od samotného promptu, som písal tu</a>.</p><h3>Relevancia výhráva nad objemom</h3><p>Na toto som prišiel trošku neskôr, pri nespočetných pokusoch a omyloch. Bádaním, alebo krajšie povedané: empiricky.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KBcDWr7JLJr7eU6zsbm5AQ.png" /><figcaption><strong>Relevancia nad objemom</strong></figcaption></figure><p>Inštinkt hovorí, že čím viac kontextu, tým lepší výsledok. Dajme modelu viac podkladov, viac príkladov, viac dokumentov. Realita mi však ukázala niečo iné. V skutočnosti to funguje opačne. Nadbytočný kontext zahlcuje model, znižuje pozornosť na dôležité časti a vedie k rozmazaným, generickým odpovediam. Ako to staré príslovie. Menej je niekedy viac.</p><p>Toto má aj konkrétny mechanizmus. Modely majú obmedzený “attention budget”, niečo ako pracovná pamäť u ľudí. Každý token tento rozpočet čerpá. Čím dlhší kontext, tým menej pozornosti zostáva na každú jeho časť. Výskumy ukazujú, že modely majú pri dlhých kontextoch znateľne horšiu schopnosť vybaviť si informácie, ktoré v tom kontexte existujú. Má to dokonca meno: <strong>context rot</strong>.</p><blockquote><strong>Context rot</strong> (doslovne “hnitie kontextu”) je jav, kde model pri príliš dlhom vstupe začína ignorovať alebo zabúdať informácie z jeho stredu. Nie je to chyba, je to fyzikálna vlastnosť transformer architektúry, na ktorej všetky veľké modely bežia. Informácie na začiatku a na konci kontextu dostávajú viac pozornosti než to, čo je uprostred. [<a href="https://www.trychroma.com/research/context-rot">https://www.trychroma.com/research/context-rot</a>]</blockquote><p>Správny prístup je výber, nie hromadenie. Relevantný dokument je lepší ako päť priemerne súvisiacich dokumentov. Jasná inštrukcia je lepšia ako päťodsekový systémový prompt plný výnimiek.</p><blockquote>Preťaženie kontextu je jedna z najčastejších začiatočníckych chýb. Viac tokenov neznamená viac presnosti, znamená to väčší priestor pre šum. A pri dlhých kontextoch môže model fakticky “zabudnúť” informáciu, ktorú ste mu dali.</blockquote><p>Kvalita kontextu takmer vždy rozhoduje viac než veľkosť modelu.</p><h3>Štruktúra hovorí za vás</h3><p>Druhá vec, ktorú som si uvedomil je, že model číta štruktúru rovnako ako obsah.</p><p>Keď som pomiesal inštrukcie s dátami, model to pomiešal tiež. Keď som mal jasnú hierarchiu, systémové pravidlá na vrchu, kontext v strede, otázka na konci, odpovede boli konzistentnejšie a presnejšie.</p><p>Toto nie je len o formátovaní. Je to o tom, ako model rozumie tomu, čo je záväzné, čo je len pozadie a čo je aktuálna úloha.</p><p>Niektoré veci, ktoré fungujú: pomenujte sekcie explicitne (## Inštrukcie, ## Podkladové dáta, ## Otázka), používajte konzistentné šablóny a oddeľte inštrukcie od príkladov. Model sa na vzory nastaví pomerne rýchlo, ak sú konzistentné.</p><p>Vyzerá to napríklad takto: príklad zo skutočného systémového promptu pre agenta na sumarizáciu článkov:</p><pre>## Inštrukcie<br>Si senior analytik obsahu. Tvojou úlohou je sumarizovať novinové články do 3–5 viet.<br>Píš v slovenčine. Tón: neutrálny, faktický. Nikdy nevymýšľaj informácie, ktoré v texte nie sú.<br>​<br>## Formát odpovede<br>- Jedna súvislá odpoveď, žiadne odrážky<br>- Maximálne 100 slov<br>- Ak článok neobsahuje dostatok informácií, napíš: &quot;Nedostatok podkladov na sumarizáciu.&quot;<br>​<br>## Podkladový článok<br>{sem príde text článku}<br>​<br>## Úloha<br>Zhrň článok podľa vyššie uvedených pravidiel.</pre><p>Bez tejto štruktúry model nevie, čo je záväzné pravidlo a čo je len kontext. Keď som mal všetko v jednom odseku, dostal som iný výsledok pri každom volaní. Po zavedení sekcií sa variabilita výrazne znížila.</p><h3>RAG a pamäť: keď prompt nestačí</h3><p>Pre jednoduchšie systémy stačí dobre napísaný prompt. Ale keď začnete pracovať s dlhými dokumentmi, aktuálnymi dátami alebo rozsiahlou históriou, potrebujete niečo viac.</p><p><a href="https://arxiv.org/abs/2005.11401">Retrieval-Augmented Generation (RAG)</a> je prístup, kde namiesto toho, aby ste všetko dávali do promptu, vyhľadáte len relevantnú časť a tú pošlete modelu.</p><blockquote><strong>RAG zjednodušene:</strong> Predstavte si, že máte 10 000 stránok dokumentácie a chcete sa modelu opýtať na jednu konkrétnu vec. Namiesto toho, aby ste mu dali všetkých 10 000 stránok (čo by ani nešlo), systém najprv vyhľadá 5–10 najrelevantnejších stránok a pošle len tie. Model odpovie na základe tohto výberu. RAG je teda kombinácia vyhľadávača a generatívneho modelu. Funguje to dobre, keď je retrieval dobrý. A práve tam sa to najčastejšie kazí: nie v generovaní, ale vo vyhľadávaní.</blockquote><p>Pamäťové systémy sú o niečo zložitejšie. Ukladajú kontext medzi session, takže model “vie” čo sa dialo predtým. Užitočné, ale aj ťažšie na správu. Starý kontext môže byť zavádzajúci alebo zastaraný.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SlbV-_d7PskgSObHaCgxmA.png" /><figcaption>Jednoduchý prompt vs architektúra pamäťových systémov</figcaption></figure><blockquote>Čerstvosť informácií je princíp, na ktorý sa ľahko zabúda. Aktuálne dáta by mali mať prednosť pred starými, aj keď sú tie staré “technicky” pravdivé.</blockquote><h3>Techniky, ktoré sa mi osvedčili</h3><p>Nie je to vyčerpávajúci zoznam, len veci, ktoré sa mi osvedčili.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K2fN-oAJT2lNgzRf_wIzxw.png" /><figcaption>Toolbox: techniky na lepší kontext</figcaption></figure><h4>Chunking</h4><p>Rozdeľte dokumenty na menšie, sémanticky ucelené časti. Celé dokumenty sú zriedka relevantné celé, a model to aj tak neprečíta rovnako pozorne.</p><h4>Ranking a filtrovanie</h4><p>Nevkladajte do kontextu všetko, čo vyhľadáte. Ohodnoťte relevantnosť, zoraďte, odfiltrujte slabé zhody. Retrieval bez filtrovania je len iný spôsob, ako preťažiť kontext.</p><h4>Kompresia.</h4><p>Ak musíte zahrnúť dlhý dokument, zhrňte ho. <strong>Ľudský súhrn je lepší než surový text</strong>, ak ide o zachovanie hlavnej myšlienky.</p><h4>Kompakcia (compaction)</h4><p>V dlhých agent sessions, kde sa kontext blíži k limitu, neresetujte konverzáciu na prázdno. Namiesto toho zhrňte celú históriu do kompaktného súhrnu, ktorý zachová architektonické rozhodnutia a kritické detaily, ale zahodí redundantné výstupy. Je to iné ako bežná kompresia dokumentu — ide o aktívne riadenie životného cyklu celého kontextu.</p><h4>Just-in-time kontext</h4><p>Namiesto toho, aby ste vopred naložili všetky dáta, udržiavajte len ľahké identifikátory (cesty k súborom, kľúče) a načítavajte dáta nástrojmi až vtedy, keď ich model skutočne potrebuje. Znižuje to počiatočný token overhead a model dostáva presne to, čo je relevantné v danom momente.</p><h4><strong>Few-shot učenie</strong></h4><p>je technika, kde modelu namiesto dlhého vysvetľovania ukážete hotové príklady vstup → výstup. “Few” znamená málo — stačia dve až tri ukážky. Funguje to preto, lebo model z príkladov odvodí vzor rýchlejšie a presnejšie, než keby ste mu ho slovne opisovali.</p><blockquote>Few-shot príklady: ukazujete modelu vzor, nie len popis vzoru. Dva-tri dobre zvolené príklady môžu nahradiť rozsiahle inštrukcie. Niekedy fungujú lepšie.</blockquote><h4>Vrstvenie inštrukcií:</h4><p>globálne pravidlá patria do systémového promptu, špecifické pravidlá bližšie k otázke. Nezmiešavajte ich, model to “cíti”. (Ak vás zaujíma, ako konkrétne tie vrstvy nastaviť, <a href="https://medium.com/@jurajmacak/pre%C4%8Do-u%C5%BE-nep%C3%AD%C5%A1em-v%C5%A1etko-do-jedn%C3%A9ho-promptu-fe500779cc5f">pozrite si starší článok o oddeľovaní promptu od inštrukcie.</a>)</p><h3>Agenti a dlhé úlohy</h3><p>Pre jednoduchý dotaz stačí prompt. Ale keď začnete stavať agentov, ktorí riešia dlhé, viacstupňové úlohy, context engineering dostáva úplne iný rozmer.</p><p>Jeden prístup, ktorý sa osvedčuje, sú <strong>sub-agentové architektúry</strong>: namiesto jedného agenta s obrovským kontextom je možné využiť viacerých špecializovaných agentov, každý s čistým kontextovým oknom.</p><blockquote><strong>AI agent</strong> je model, ktorý nedostane len otázku a odpovie, ale aktívne vykonáva kroky, používa nástroje (vyhľadávanie, spúšťanie kódu, čítanie súborov) a rozhoduje sa, čo urobiť ďalej. Je to viac ako chatbot. Je to niečo, čo “pracuje” na úlohe autonómne, niekedy minúty alebo hodiny. Hlavný agent dostáva len kompaktné súhrny (typicky 1 000 až 2 000 tokenov) z každého sub-agenta. Každý rieši svoju časť bez balasta z predchádzajúcich krokov.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dvyi1O68RDxtDrqntJsV5A.png" /><figcaption>Agenti s čistým kontextom a štruktúrované písanie poznámok</figcaption></figure><p>Ďalší pattern je štruktúrované písanie poznámok. Agent si počas práce udržiava externý súbor s kľúčovými rozhodnutiami, zisteniami a stavom. Niečo ako NOTES.md, do ktorého agent priebežne zapisuje. Keď kontext narazí na limit a treba ho resetovať, tieto poznámky ostávajú a agent ich načíta späť. Veľmi iné od tradičného RAG, ale v praxi efektívne pre dlhé, viac-hodinové úlohy.</p><h3>Kde sa to kazí</h3><p>Za posledný rok som videl dosť systémov, aj vlastných, ktoré zlyhávali z predvídateľných príčin. Najčastejší prípad bol, keď vývojár sa snažil byť dôkladný a pchal do promptu všetko “pre istotu”. Model bol stratený. Keď systémový prompt obsahoval aj príklady, aj pravidlá, aj podkladové dáta, model nevedel čomu veriť.</p><p>Druhý problém je žiadne overovanie. Systém beží, niečo produkuje, nikto to systematicky nevyhodnocuje. <strong>Problémy sa hromadia a nikto si to nevšimne, kým to nejde do produkcie</strong>. A potom jednoducho zlé formátovanie. Holý text bez štruktúry je horšie čitateľný pre model aj pre ľudí, ktorí to debugujú.</p><blockquote>Ak váš systém <strong>produkuje nepredvídateľné výstupy, prvá vec na kontrolu nie je model, ale kontext, ktorý mu posielate.</strong></blockquote><h3>Čo som sa naučil</h3><ul><li><strong>Menej je viac, ak je to správne menej.</strong> Dvadsať tokenov na vec nie je strata, je to disciplína.</li><li><strong>Štruktúra je komunikácia.</strong> Ako niečo naformátujete, ovplyvňuje to, ako to model spracuje.</li><li>„<strong>Retrieval</strong> je polovica RAG-u. Je to krok, ktorý rozhoduje, aké informácie sa k modelu vôbec dostanú. Ak retrieval vyberie nesprávne alebo nepodstatné údaje, aj veľmi dobrý model z nich spraví slabú odpoveď, pretože jednoducho pracuje so zlým vstupom.</li><li><strong>Iterácia potrebuje meranie.</strong> Bez vyhodnotenia neviem, či sa zlepšujem alebo len tárám v kruhu.</li><li><strong>Čerstvé informácie majú hodnotu.</strong> Starý kontext môže byť horší ako žiadny kontext.</li><li><strong>Modularita sa vypláca.</strong> Systém, kde môžete vymeniť jeden komponent bez toho, aby ste rozbili ostatné, je oveľa ľahšie ladiť.</li></ul><h3>Na záver</h3><p>Context engineering nie je buzzword ani nová kategória na LinkedIn. Je to vec, ktorú robíme vždy, keď posielame niečo do modelu, len väčšinou nevedome a bez systému. Čím viac som s tým pracoval, tým jasnejšie vidím, že kvalita kontextu rozhoduje omnoho viac, ako si väčšina ľudí pri budovaní AI systémov uvedomuje. Model je len tak dobrý, ako dobrý je vstup, ktorý dostane.</p><p>Stále sa v tom učím. Ale aspoň teraz viem, kde hľadať, keď niečo nefunguje.</p><h3>Zdroje</h3><ul><li><a href="https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents">Effective Context Engineering for AI Agents — Anthropic</a></li><li><a href="https://arxiv.org/abs/2005.11401">Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks</a></li><li><a href="https://platform.openai.com/docs/guides/prompt-engineering">OpenAI Prompt Engineering Guide</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f61888b34d66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prečo už nepíšem všetko do jedného promptu]]></title>
            <link>https://medium.com/@jurajmacak/pre%C4%8Do-u%C5%BE-nep%C3%AD%C5%A1em-v%C5%A1etko-do-jedn%C3%A9ho-promptu-fe500779cc5f?source=rss-ce7d1828a5db------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe500779cc5f</guid>
            <category><![CDATA[písanie-promptov]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Juraj Macák]]></dc:creator>
            <pubDate>Sun, 22 Feb 2026 17:18:15 GMT</pubDate>
            <atom:updated>2026-02-23T06:30:07.844Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Dlho som si myslel, že dobrý prompt musí obsahovať úplne všetko. Od kontextu cez úlohu až po presný formát odpovede. Neskôr som zistil, že zlievať to do jednej kopy je cesta do chaosu. Keď oddelíte samotnú úlohu (prompt) od pravidiel správania (inštrukcia), získate oveľa konzistentnejšie a profesionálnejšie výsledky s jazykovými modelmi. V tomto článku rozoberám, ako to robím dnes a prečo to funguje.</blockquote><p>Sedím pred prázdnym textovým oknom a už po desiatykrát kopírujem ten istý dlhý odstavec s pravidlami pre umelú inteligenciu. „Odpovedaj jasne k veci, používaj odrážky, vyhýbaj sa zbytočnému žargónu…“ .</p><p>A pod to, len tak mimochodom, prilepím samotnú otázku. Fungovalo to celkom fajn. Ale čím viac som s modelmi pracoval a čím komplexnejšie veci som riešil, tým viac ma tento zmiešaný prístup unavoval.</p><p>Bol to jeden obrovský text, ktorý obsahoval vlastne všetko. Kontext, zadanú úlohu aj pokyny k odpovedi. Na začiatku mi to prišlo úplne prirodzené.</p><p>Keď len tak zľahka skúšate, čo AI dokáže, všetko v jednom okne dáva zmysel. Lenže po čase začnete narážať na to, že ak chcete vyriešiť desať rôznych úloh, napríklad vysvetliť fotosyntézu, napísať úvod do inflácie alebo pochopiť princíp fungovania internetu a chcete, aby výstup vyzeral stále rovnako, musíte tie zložité pravidlá kopírovať znova a znova. Alebo nebodaj nájdete drobnú chybu v tom, ako model odpovedá, a zrazu to musíte opravovať vo všetkých vašich uložených textoch.</p><h4>Prompt versus inštrukcia</h4><p>Zlom nastal, keď som potreboval do celého toho procesu dostať trochu systému. Uvedomil som si tam jednu podstatnú vec:</p><blockquote><strong>prompt a inštrukcia naozaj nie sú to isté.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nr2lhWq1JQ0b18UWUHFNzw.png" /><figcaption>Jednoduchá myšlienka vs podrobné zadanie pre AI</figcaption></figure><p><strong>Prompt</strong> je jednoducho <strong>konkrétna úloha</strong> alebo <strong>otázka</strong>, ktorú chcem práve teraz vyriešiť. Je variabilný a mení sa podľa aktuálnej potreby. Vyjadruje <strong>ČO</strong> chceme spraviť.</p><p><strong>Inštrukcia</strong> je naproti tomu <strong>súbor pravidiel</strong>, ktorý modelu určuje, <strong>AKO</strong> má vlastne odpovedať. Je oveľa stabilnejšia a môže ostať úplne rovnaká aj pri desiatkach meniacich sa promptoch.</p><p>Tak som ich začal striktne oddeľovať. Inštrukciu som si definoval globálne a samotné prompty som nechal krásne čisté a jednoduché. Zrazu som mohol napísať len: „<em>Vysvetli mi pojem digitálna transformácia</em>“ alebo „<em>Navrhni marketingovú stratégiu pre malú firmu.</em>“ Model odpovedal na úplne iné témy, ale vždy s rovnakým, predvídateľným štýlom.</p><blockquote><em>💡 Ak používate ChatGPT, základné inštrukcie si viete nastaviť v „Custom instructions“. Ak však riešite viacero tém naraz, oveľa užitočnejšie sú funkcie ako </em><strong><em>Projects</em></strong><em> (v ChatGPT) alebo </em><strong><em>Gems</em></strong><em> (v Google Gemini). Dovoľujú vám poskladať si samostatných asistentov, kde každému priradíte jeho vlastnú, špecifickú inštrukciu.</em></blockquote><p>Prišiel som ale na to, že ak už tú inštrukciu oddelím, musí byť naozaj prepracovaná. Skúšal som desiatky rôznych verzií a zistil som, že pre dobre opakovateľné použitie musí definovať päť konkrétnych oblastí. Ak niektorá chýbala, výsledok miestami úplne uletel.</p><h4>Tajomstvo univerzálnej inštrukcie</h4><p>Aké je teda tajomstvo univerzálnej inštrukcie? Tu je päť vecí, ktoré sa mi najviac osvedčili:</p><ul><li><strong>Určite jednoznačnú rolu modelu.</strong> Pozícia mení všetko. Namiesto všeobecného príkazu mu zadajte tón. „Vystupuj ako učiteľ pre začiatočníkov“ alebo „Vystupuj ako architekt, ktorý pozná statiku.“ Úplne to zmení perspektívu komunikácie.</li><li><strong>Definujte štýl a jazyk.</strong> Ak chcete jednoduchý jazyk, povedzte to. Chcete neutrálny tón bez zbytočných slangov? Zakomponujte to. Len toto jedno pravidlo ušetrí kopu nervov pri čítaní kvetnatých fráz.</li><li><strong>Vynúťte presnú štruktúru odpovede.</strong> „Začni krátkym úvodom, pokračuj vysvetlením pojmov, uveď príklady z praxe a na konci to zhrň v odrážkach.“ Takáto kostra udrží model pri zemi pri akejkoľvek téme.</li><li><strong>Stanovte si hĺbku a rozsah.</strong> Ak nechcete čítať tri strany textu na banálnu otázku, dajte mu presný limit. Napríklad: stredne podrobné vysvetlenie v maximálnom rozsahu 300 až 500 slov.</li><li><strong>Dajte mu prísne mantinely.</strong> Sem patria zásady ako „nevymýšľaj si fakty“, „ak si neistý, upozorni na to“ a „vyhýbaj sa extrémnym a subjektívnym tvrdeniam“. Tieto hranice výrazne obmedzujú množstvo bludov a halucinácií vo výstupoch.</li></ul><blockquote><em>⚠️ Týmto procesom som narobil aj dosť vlastných chýb. Tou najčastejšou bolo, že som vytvoril inštrukciu, ktorá bola buď príliš extrémne všeobecná, alebo naopak zbytočne dlhá a vnútorné pravidlá v nej si protirečili.</em></blockquote><p><strong>Príklad dobrej inštrukcie:</strong></p><pre>Vystupuj ako učiteľ pre začiatočníkov v danej téme, ktorý dokáže vysvetľovať zložité veci jednoducho a trpezlivo.<br><br>Používaj jednoduchý, neutrálny a zrozumiteľný jazyk bez slangu, zbytočných metafor alebo kvetnatých formulácií.<br><br>Dodrž túto štruktúru odpovede:<br> 1. Krátky úvod do témy (2–3 vety)<br> 2. Vysvetlenie základných pojmov<br> 3. 1–2 praktické príklady z reálneho života<br> 4. Zhrnutie v odrážkach<br><br>Rozsah odpovede: stredne podrobné vysvetlenie v rozsahu 300 – 400 slov.<br><br>Dodrž tieto mantinely:<br> • Nevymýšľaj si fakty ani zdroje.<br> • Ak si neistý, otvorene na to upozorni.<br> • Vyhýbaj sa extrémnym, subjektívnym alebo zavádzajúcim tvrdeniam.<br> • Ak téma presahuje tvoje znalosti, navrhni, kde možno nájsť spoľahlivé informácie.</pre><p>Oddelenie promptu od inštrukcie je v podstate ten krok od náhodného textovania s umelou inteligenciou k aspoň trochu profesionálnejšej práci. Prompt definuje iba obsah aktuálnej úlohy a inštrukcia zastrešuje celý štýl, kvalitu a formu odpovede. Celkom to zjednodušuje pozeranie na zložité systémy pod kapotou softvéru. Nie som si úplne istý, ako budeme s AI komunikovať o dva či tri roky. Modely budú určite múdrejšie a možno nás pochopia aj z kontextu našej doterajšej práce bez zložitých pokynov. Nateraz je však takéto oddelenie podľa mňa základným kameňom pre normálnu prácu, kde aspoň trochu tuším, čo z toho stroja nakoniec vypadne.</p><h4>Záver</h4><p>Ale toto je len začiatok. Ako vývojár dnes už s asistentmi len tak nečetujem v okienku prehliadača. Pracujem s plnohodnotnými AI agentmi priamo v kóde a tam naberá nastavovanie inštrukcií úplne iné grády. Namiesto jedného odstavca textu im definujem komplexné zručnosti (skills), globálne pravidlá (rules) celého projektu a dávam im do rúk reálne nástroje na úpravu súborov. Tam už inštrukcia nie je o tom, akým tónom má model odpovedať. Je to o tom, aké má mantinely pri zásahoch do reálnej aplikácie. A to ako udržať armádu agentov na reťazi a nenechať ich rozbiť celý kód, napíšem zas nabudúce.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe500779cc5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Widgets: A Great Way to Enhance Your iOS App]]></title>
            <link>https://medium.com/@jurajmacak/widgets-a-great-way-to-enhance-your-ios-app-c58fdbd9357c?source=rss-ce7d1828a5db------2</link>
            <guid isPermaLink="false">https://medium.com/p/c58fdbd9357c</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[ios-widgets]]></category>
            <dc:creator><![CDATA[Juraj Macák]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 19:26:50 GMT</pubDate>
            <atom:updated>2025-04-14T19:26:50.239Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*anLY5aJVLrQSHUeK" /><figcaption>Photo by <a href="https://unsplash.com/@vmxhu?utm_source=medium&amp;utm_medium=referral">Szabo Viktor</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Widgets are a great way to improve user experience. In the article, you will find the basics of implementing widgets in iOS, as well as some tips and tricks for designing visually stunning and efficient widgets for the home screen.</p><h4>Prerequisites</h4><ul><li>An active Apple Developer membership is required: the App Groups capability is only available with an active membership.</li></ul><h4>Our Goal</h4><p>Building a widget in <strong>static configuration</strong> and in three possible sizes (small, medium, and large) that displays user savings data and an overview of the financial status, which includes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TCxurpbLmJdV75OnSOL12Q.png" /><figcaption>Widget overview</figcaption></figure><h3>Create a Widget Extension</h3><ul><li>Open your <strong>Xcode project</strong>.</li><li>Go to <strong>File &gt; New &gt; Target</strong>.</li><li>Select <strong>Widget Extension</strong> and click <strong>Next</strong>.</li><li>Name your widget (e.g., SavingsWidget) and ensure <strong>Include Configuration Intent, Include Control </strong>and<strong> Include Live Activity </strong>are<strong> unchecked</strong> for a static widget.</li><li>Click <strong>Finish</strong>, and activate the new target when prompted.</li></ul><p>This tutorial is primarily focused on simple static widgets. There are more advanced options for making widgets interactive.</p><ul><li><strong>Configuration Intent</strong>, which allows users to customize widget settings</li><li><strong>Include Control</strong> extend widgets with interactive elements like buttons for quick actions.</li><li><strong>Live Activity</strong> displays real-time data. For example, scores and timers are visible directly on the Lock Screen.</li></ul><p>Xcode generates some boilerplate code. You can remove the Swift files while keeping Assets.xcassets and Info.plist .</p><blockquote>💡 I don’t prefer the default widget location in my folder structure. Instead, create folder named for examle “Extensions” and move the folder inside. Any manipulation with default locations needs to update plist file:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jxtsPLlMZidjLPTksdL0Kw.png" /><figcaption>Modification Info.plist file for the Widget after file migration</figcaption></figure><h3>Implementation of widget layers</h3><p>Apple has defined the following layers required to construct a widget:</p><ul><li><strong>TimelineProvider: </strong>Gives the data to the widget in a specified interval</li><li><strong>TimelineEntry: </strong>A<strong> </strong>Structure containing data which is used by the widget</li><li><strong>WidgetView: </strong>UI layout of the widget</li><li><strong>Widget Bundle: </strong>Used for registering one or multiple widgets</li></ul><h4>TimelineEntry</h4><p>The first task is to build a data structure containing all the necessary properties our widget will use. Give it the name <strong>SavingsEntry.</strong></p><pre>import WidgetKit<br><br>struct SavingsEntry: TimelineEntry {<br><br>    let date: Date<br>    let currentSavings: Double<br>    let dailySavings: Double<br>    let weeklySavings: Double<br>    let monthlySavings: Double<br>}</pre><p>It stores all the data we need for our widget to present.</p><h4>TimelineProvider</h4><p>The SavingsProvider contains three functions:</p><pre>struct SavingsProvider: TimelineProvider {<br><br>    func placeholder(in context: Context) -&gt; SavingsEntry {<br>        ...<br>    }<br><br>    func getSnapshot(in context: Context, completion: @escaping (SavingsEntry) -&gt; ()) {<br>        ...<br>    }<br><br>    func getTimeline(in context: Context, completion: @escaping (Timeline&lt;SavingsEntry&gt;) -&gt; ()) {<br>        ...<br>    }<br>}</pre><p><strong>placeholder(in:)</strong></p><ul><li>This is primarily seen on the widget gallery (the page where users choose which widget to add) and in instances where the widget doesn’t yet contain live data to pull from.</li><li>It provides a static, generic look (often with mock or default data) so users can see what the widget will look like. It is not used to display live data — it’s just a “preview” or fallback.</li></ul><p><strong>getSnapshot(in:completion:)</strong></p><ul><li>This is called when the widget is about to be displayed on the homescreen, specifically when a quick rendering of the current state of the widget is needed.</li><li>It is meant to provide a snapshot of the widget content (ideally live data) in a quick fashion, so that the widget can be populated with an almost real-time view. Even when actual timeline updates have not yet been received, the system uses this snapshot to render something.</li></ul><p><strong>getTimeline(in:completion:)</strong></p><ul><li>Generates a sequence of entries with timestamps, defining when the widget should refresh its content.</li></ul><p>Modified SavingsProvider code with SavingsEntry:</p><pre>struct SavingsProvider: TimelineProvider {<br><br>    func placeholder(in context: Context) -&gt; SavingsEntry {<br>        SavingsEntry(<br>            date: Date(),<br>            currentSavings: 1000,<br>            dailySavings: 50,<br>            weeklySavings: 350,<br>            monthlySavings: 1500<br>        )<br>    }<br><br>    func getSnapshot(in context: Context, completion: @escaping (SavingsEntry) -&gt; Void) {<br>        let entry = placeholder(in: context)<br>        completion(entry)<br>    }<br><br>    func getTimeline(in context: Context, completion: @escaping (Timeline&lt;SavingsEntry&gt;) -&gt; Void) {<br>       ...<br>    }<br>}</pre><p>The getTimeline() function is left unfinished at this point. This is a key part of the widget implementation as we need to determine how to extract information from the main app and send it to the widget.</p><p>To achieve this, use UserDefaults and an <strong>App Group </strong>to share data between the main application and the widget extension. The main application will save the last savings data into UserDefaults, and the widget will fetch this data at intervals and update its view.</p><h4>Implementing UserDefaults for Data Sharing</h4><p>Since widgets run in a separate process, they cannot directly access the main app’s data. Instead, enable an <strong>App Group</strong> in Xcode to share UserDefaults between the app and the widget:</p><h4>Enable App Groups in Xcode</h4><ol><li>Open your project in Xcode.</li><li>Go to <strong>Signing &amp; Capabilities</strong> for both your <strong>main app target</strong> and the <strong>widget extension target</strong>.</li><li>Click + Capability and select <strong>App Groups</strong>.</li><li>Add a new group identifier (e.g., group.demo.my-savings).</li><li>Ensure that <strong>both targets use the same App Group identifier</strong>.</li></ol><p>Using each attribute in a separate UserDefaults is not the best way to handle data, because we are forced to create a key for each of them.</p><p>A better way is to create a single structure wrapper for all the data we need to draw our widget. It contains all the data, and it is identified by a single key when retrieved from UserDefaults. To do so, we need to transform our structure into a serializable type: Data. The solution is the use of JSON encoding and decoding.</p><h4>Building a Shared Data Model</h4><p>We first make a model that satisfies the codable protocol and contains all the data our widget needs.</p><pre>struct SavingsModel: Codable {<br><br>    let currentSavings: Double<br>    let dailySavings: Double<br>    let weeklySavings: Double<br>    let monthlySavings: Double<br>}</pre><p>Using the Codable protocol, encoding the model into a JSON object and decoding from the UserDefaults to the model is very simple.</p><blockquote>⚠️ The SavingsModel is a unique struct that’s shared between the main app and the widget. Don’t forget to add the target membership for both the widget and the main app.</blockquote><h4>Saving data</h4><p>In the main app, before saving, it is important to serialize the struct into JSON:</p><pre>let mockModel = SavingsModel(<br>    currentSavings: 340,<br>    dailySavings: 30,<br>    weeklySavings: 210,<br>    monthlySavings: 840<br>)<br><br>let encodedData = try? JSONEncoder().encode(mockModel)<br><br>UserDefaults(suiteName: &quot;group.demo.my-savings&quot;)?.set(encodedData, forKey: &quot;savings-key&quot;)<br>WidgetCenter.shared.reloadAllTimelines()</pre><blockquote>⚠️ Don’t forget to call WidgetCenter.shared.reloadAllTimelines() after saving data into UserDefaults. This triggers immediate refresh of the widget with the recent data.</blockquote><h4>Read Data in the Widget’s getTimeline Function</h4><p>Now, the widget retrieves and <strong>decodes</strong> the JSON-encoded struct:</p><pre>func getTimeline(in context: Context, completion: @escaping (Timeline&lt;SavingsEntry&gt;) -&gt; Void) {<br>    let data = UserDefaults(suiteName: &quot;group.demo.my-savings&quot;)?.data(forKey: &quot;savings-key&quot;) ?? Data()<br>    let model = try? JSONDecoder().decode(SavingsModel.self, from: data)<br><br>    guard let model else {<br>        let entry = placeholder(in: context)<br>        let timeline = Timeline(entries: [entry], policy: .never)<br>        completion(timeline)<br>        return<br>    }<br><br>    let entry = SavingsEntry(<br>        date: .now,<br>        currentSavings: model.currentSavings,<br>        dailySavings: model.dailySavings,<br>        weeklySavings: model.weeklySavings,<br>        monthlySavings: model.monthlySavings<br>    )<br><br>    let timeline = Timeline(entries: [entry], policy: .never)<br><br>    completion(timeline)<br>}</pre><p>Everything is prepared. The next step is to implement the design for the widget’s frontend and bring the project to life.</p><h4>Creating Widget View Component</h4><p>Let’s define basic structure</p><pre>import SwiftUI<br>import WidgetKit<br><br>struct SavingsWidgetView: View {<br><br>    @Environment(\.widgetFamily) private var widgetFamily<br>    let entry: SavingsEntry<br><br>    var body: some View {<br>        switch widgetFamily {<br>        case .systemSmall:<br>            smallWidget<br>        case .systemMedium:<br>            mediumWidget<br>        case .systemLarge:<br>            largeWidget<br>        default:<br>            smallWidget<br>        }<br>    }<br>}</pre><p>Before designing different widget sizes, let’s create some reusable view components.</p><pre>private var currentSavingsView: some View {<br>    VStack(alignment: .leading, spacing: 8) {<br>        Text(&quot;🏦 Current Savings&quot;)<br>            .font(.headline)<br><br>        Text(entry.currentSavings, format: .currency(code: &quot;EUR&quot;))<br>            .font(.title2)<br>            .bold()<br>            .foregroundStyle(.tint)<br>    }<br>}<br><br>private var dailySavingsView: some View {<br>    VStack(alignment: .leading, spacing: 8) {<br>        Text(&quot;📅 Daily&quot;)<br>            .font(.headline)<br><br>        Text(entry.dailySavings, format: .currency(code: &quot;EUR&quot;))<br>            .font(.title2)<br>            .bold()<br>    }<br>    .foregroundStyle(.primary)<br>}<br><br>private var weeklySavingsView: some View {<br>    VStack(alignment: .leading, spacing: 8) {<br>        Text(&quot;📆 Weekly&quot;)<br>            .font(.headline)<br><br>        Text(entry.weeklySavings, format: .currency(code: &quot;EUR&quot;))<br>            .font(.title2)<br>            .bold()<br>    }<br>    .foregroundStyle(.primary)<br>}<br><br>private var montlySavingsView: some View {<br>    VStack(alignment: .leading, spacing: 8) {<br>        Text(&quot;📅 Monthly&quot;)<br>            .font(.headline)<br><br>        Text(entry.monthlySavings, format: .currency(code: &quot;EUR&quot;))<br>            .font(.title2)<br>            .bold()<br>    }<br>    .foregroundStyle(.primary)<br>}</pre><h4>Small Widget</h4><p>The small widget is the smallest of the provided sizes and perfect for showing a single piece of information, i.e., current savings.</p><pre>private var smallWidget: some View {<br>    VStack {<br>        Text(&quot;💰 Savings&quot;)<br>            .font(.headline)<br>            .foregroundStyle(.gray)<br><br>        Text(entry.currentSavings, format: .currency(code: &quot;EUR&quot;))<br>            .font(.title3)<br>            .bold()<br>            .foregroundStyle(.tint)<br>    }<br>    .padding()<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j1pCtCNtoqvUlS0a109Vrg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OTftpwRhUDEUjxgaormH3g.png" /><figcaption>Small Widget</figcaption></figure><h4>Medium Widget</h4><p>The medium widget is bigger. It provides enough space to display daily and weekly savings in addition to current savings.</p><pre>private var mediumWidget: some View {<br>    HStack {<br>        currentSavingsView<br>        Spacer()<br><br>        VStack(alignment: .trailing, spacing: 4) {<br>            dailySavingsView<br>            weeklySavingsView<br>        }<br>    }<br>    .padding()<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yLCQYJG6eW28flyABZ-1RA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YIBZYznZ2KVcQmKyNloKhA.png" /><figcaption>Medium Widget</figcaption></figure><h4>Large Widget</h4><p>The large widget has extra space filled on the screen. Enough to show all savings data.</p><pre>private var largeWidget: some View {<br>    VStack(alignment: .leading, spacing: 60) {<br>        Text(&quot;💰 Savings Overview&quot;)<br>            .font(.title2)<br>            .bold()<br><br>        HStack {<br>            currentSavingsView<br>            Spacer()<br>            dailySavingsView<br>        }<br><br>        HStack {<br>            weeklySavingsView<br>            Spacer()<br>            montlySavingsView<br>        }<br>    }<br>    .padding()<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5GpFKJ14OavjSwRuGB_r5w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kh3BYPhCHpvLCWKSDRNBKg.png" /><figcaption>Large Widget</figcaption></figure><h4>Widget Configuration</h4><p>Now it’s time to register the widget and tell the system which views should be shown for different sizes. This is achieved with WidgetConfiguration.</p><p>Firstly, let’s create a new file called SavingsWidget and paste the following code:</p><pre>struct SavingsWidget: Widget {<br><br>    let kind: String = &quot;SavingsWidget&quot;<br><br>    var body: some WidgetConfiguration {<br>        StaticConfiguration(kind: kind, provider: SavingsProvider()) { entry in<br>            SavingsWidgetView(entry: entry)<br>                .containerBackground(.background, for: .widget)<br>        }<br>        .configurationDisplayName(&quot;Savings Widget&quot;)<br>        .description(&quot;Track your savings directly from the home screen.&quot;)<br>        .supportedFamilies([.systemSmall, .systemMedium, .systemLarge])<br>    }<br>}<br><br>#Preview(as: .systemSmall) {<br>    SavingsWidget()<br>} timeline: {<br>    SavingsEntry(date: .now, currentSavings: 147.5, dailySavings: 30, weeklySavings: 210, monthlySavings: 850)<br>}</pre><blockquote>⚠️ To allow multiple widget sizes, supported families must be explicitly set. In our case, we have to add the <em>.supportedFamilies</em> modifier and insert an array with the following values: .systemSmall , .systemMedium , .systemLarge</blockquote><p>The configuration contains metadata such as display name and widget description. It has a preview macro, which allows testing the widget inside Xcode previews.</p><blockquote>💡Use shortcut <strong>Cmd + Option + Enter</strong> to toggle preview windows and<strong> Cmd + Option + P</strong> to start, stop previews.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1vYYv_JHSAAWeWG79SNu6Q.png" /><figcaption>Add Widget Menu</figcaption></figure><h4>Registering the Widget Bundle</h4><p>This is the main entry point for the widget. If your app supports multiple widgets, they must be registered in a <strong>widget bundle</strong>. This case contains only one widget.</p><pre>@main<br>struct SavingsWidgetBundle: WidgetBundle {<br><br>    var body: some Widget {<br>        SavingsWidget()<br>    }<br>}</pre><h3>Final Thoughts</h3><p>Fantastic. We’ve successfully built an interactive, visually appealing iOS widget displaying user savings data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M__kArLISWb8yXaw" /><figcaption>Photo by <a href="https://unsplash.com/@ambreenhasan?utm_source=medium&amp;utm_medium=referral">Ambreen Hasan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>We achieved</h4><ul><li>Designed SwiftUI widget views for small, medium, and large sizes</li><li>Data sharing between the main app and widget using UserDefaults</li></ul><p>Thanks for reading. Feel free to write any comments and share your experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c58fdbd9357c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>