<?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 Tomasz Salacinski on Medium]]></title>
        <description><![CDATA[Stories by Tomasz Salacinski on Medium]]></description>
        <link>https://medium.com/@ishish222?source=rss-28d477675631------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*C8fW5D6ae8f_KJ2U.png</url>
            <title>Stories by Tomasz Salacinski on Medium</title>
            <link>https://medium.com/@ishish222?source=rss-28d477675631------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:25:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ishish222/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[Decomposability in AI Workflows — What It Is and Why You Want It]]></title>
            <link>https://medium.com/@ishish222/decomposability-in-ai-workflows-what-it-is-and-why-you-want-it-c12c9a939565?source=rss-28d477675631------2</link>
            <guid isPermaLink="false">https://medium.com/p/c12c9a939565</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Tomasz Salacinski]]></dc:creator>
            <pubDate>Thu, 25 Jun 2026 18:17:15 GMT</pubDate>
            <atom:updated>2026-07-03T07:38:59.487Z</atom:updated>
            <content:encoded><![CDATA[<h3>The monolith collapses</h3><p>So let’s build an agentic workflow that handles our monthly IRS reporting. We could keep a human operator in the loop — that’s the easy version — but the one worth building, the one you can actually sell, is fully autonomous. So that’s where we’ll go.</p><p>Based on my own operator-driven workflow for monthly accounting, I assume we’re talking e.g.:</p><ol><li>Accounting evidence collection (bank statements, purchase &amp; sales documents)</li><li>OCR of the above</li><li>Matching transactions based on values, currency, dates, labels</li><li>Reconciliation, tax calculation</li><li>Reporting declaration</li></ol><p>For any given step, the previous step must succeed, this is an invariant. So we need to cover all corner cases in individual steps, such as:</p><ul><li>a missing document</li><li>a document is unreadable</li><li>we’re unable to match a position from a bank statement</li></ul><p>In my operator-driven workflow, this is my responsibility as an operator (<a href="https://medium.com/@ishish222/the-shared-responsibility-model-for-multi-agent-systems-361ae015ceed">responsibility ON the system</a>) to work this out. But we’re considering more autonomy, right? In a fully autonomous workflow, it’s the responsibility of the agents to resolve all potential issues (<a href="https://medium.com/@ishish222/the-shared-responsibility-model-for-multi-agent-systems-361ae015ceed">responsibility IN the system</a>).</p><p>Ok, now we need to make sure the system generalizes well for all of our customers. Let’s assume one customer had a problem with some hand-written documents, another one has bank statements in some non-standard format. How should we make the system generalize well for all customers? We iterate over the context, improve handling of one corner case. Then the second.</p><p>Ok, now we want to process the actual batch of documents. There’s 200 of them. The agent meticulously processes each position on the statement, but the processed ones stay in the context. Each next ReAct iteration costs more than the previous one. Now we’re nearing the end, but all of the optimizations that are now living in the context are actually compromising the standard processing at later stages.</p><p>Also, looking at the thinking process, it seems that improvements on position matching are interfering with OCR corner cases. Or the other way around?</p><p>At the workflow almost done at 99% we’re almost down on our knees praying, because boy this is ONE expensive IRS report! We hope that nothing hiccups on this one last step. The stakes are high, but… It fails!</p><p>There’s not much we can do here now, all the work so far is lost. We wish we could travel in time and force a re-run on this last ReAct inference. Wait, we could do that! If we’d checkpointed the workflow! But, the context is too swollen. Each checkpoint means serializing that entire bloated context to the database — heavy enough that there’s no way it scales to hundreds of concurrent users.</p><p>So we’re left with our 99% complete failed workflow. Turns out, even a smart 10M token context model can become cognitively overloaded. But it’s not a model problem, nor is it the problem with any particular part of context in itself. The problem is that we’re building one context doing five different things.</p><h3>The monolith is decomposed</h3><p>What we lacked in the IRS reporting system was decomposability. And it’s not even about decomposability of a problem. Almost every complex problem is decomposable. And decomposing them conceptually is in many cases almost free. An accountant probably couldn’t rephrase the IRS reporting without decomposing it along the seams.</p><p>What’s not free is a decomposable agentic system.</p><blockquote>An agentic system is decomposable if it can be split into several finer agentic systems, each of which can be developed, run, and evaluated in isolation — with its own context — and which together still achieve the goal of the original system.</blockquote><p>Decomposability is a spectrum, not a switch. The question is never “can it be split?” — the seams almost always exist — but “how cleanly does each unit hold its own context when you cut?”</p><p>So on the spectrum we have simple monolithic agents and skills-oriented workflows toward the less-decomposable end, and invokable subagents, agents-over-MCP (a tool like “browser_login” whose work is actually carried out by another agent in its own isolated context — the protocol is incidental; the isolated agent behind it is what counts), A2A toward the more-decomposable end. My favourite are invokable subagents: done right, the hierarchy nests as deep as the problem needs while preserving streamability, durability, pausability, and resumability at every level. This isn’t theoretical for me — <a href="https://sedivio.com/navigator-en/">our OWASP A01 (broken access control) suite</a> is built exactly this way: an orchestrator coordinating a hierarchy of specialist agents, with the workflow’s state still streaming and checkpointing cleanly no matter how deep the tree goes.</p><p>Here’s a quick way to tell where your own system actually sits. Take any unit you think you’ve carved out, and ask:</p><ul><li><strong>Goal</strong> — can you say what this unit is for in one sentence, without pointing at any of the others?</li><li><strong>Boundary</strong> — are its inputs and outputs explicit, or is it quietly inheriting the whole history upstream?</li><li><strong>Failure</strong> — can it fail on its own and hand a clean error back up, without the rest of the system needing to know its internals?</li><li><strong>Replay</strong> — can you run it in isolation, from fixtures, and get a meaningful result?</li></ul><p>If any of those is a “no,” that seam isn’t really a seam yet — it’s a label on a monolith.</p><h3>So why do you actually want it?</h3><p>Everything decomposability buys you comes down to one thing in that definition: <strong>each unit holds its own context</strong>. And that’s also why this isn’t just “modularity” with a new name on it. Classic modularity isolates <em>code</em> — who can call what, who owns which data. What you’re isolating here is something else: <em>context</em> — the slice of state you actually compile into the prompt on each step, and the part that quietly piles up and drags the model down as it grows.</p><p>I want to be exact about this, because the two get mixed up all the time: context isn’t the same as state. Your system can carry all the state it wants; what has to stay lean is the context you hand the model. The monolith’s mistake is letting the whole history slosh into the context, so it spills past every boundary you tried to put between the steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XcVQKDQ_BPZ147A6u2q2bQ.png" /></figure><p>None of this is new, by the way. Isolating state and not just code is the whole idea behind the actor model, shared-nothing architectures, stateless services that push their state out to the edges. What’s different here is the new thing sitting on top of state: <em>context</em>. And unlike a row in a database, a bloated context doesn’t just cost you memory, it makes every next decision worse. That’s not just my experience either. “Lost in the Middle” (<a href="https://arxiv.org/abs/2307.03172">Liu et al., 2023</a>), Chroma’s “Context Rot” report (<a href="https://www.trychroma.com/research/context-rot">2025</a>), and “NoLiMa” (<a href="https://arxiv.org/abs/2502.05167">Modarressi et al., 2025</a>) all show models degrading as the input grows, well before the window is anywhere near full. NoLiMa is an interesting one — it removes the word overlap between the question and the answer, so the model can’t get by on keyword matching, and performance still drops off as the context grows.</p><p>So let’s replay the IRS workflow, this time as five finer agentic systems — collection, OCR, matching, reconciliation, reporting — each with its own context, each handed a task and handing back an artifact. Watch what stops hurting.</p><p><strong>Cost and focus.</strong> The reconciliation unit never sees the 200 raw positions OCR chewed through — it just gets the artifact. So the context stays small, each inference stays cheap, and the model isn’t trying to juggle five jobs at once. That 10M-token model that still got overloaded? That was never about the size of the window. It was about one context doing five things. Give each job its own context and there’s nothing left to overload.</p><p><strong>Improvements stop colliding.</strong> That thing where tuning position-matching quietly broke the OCR corner cases? Can’t happen across an isolated boundary. Matching lives in its own unit now, so you tune it against its own inputs and outputs and OCR never feels it. The generalization-vs-specialization fight that used to be one impossible knob is now several separate ones.</p><p><strong>You can finally benchmark it.</strong> This is the one I care about most. In the monolith, just ask: what are the inputs and outputs of “the reconciliation step”? There’s no honest answer — every later step sits on the whole history before it, so to benchmark reconciliation you’d have to reconstruct, and vary, the entire run that led up to it. Once reconciliation is its own unit, it has a real signature: artifacts in, artifact out. You give it a fixture set, you replay it, you score that unit on its own. This is exactly how we work on the A01 suite — each specialist agent has its own fixtures, so I can rewrite one agent’s prompt or swap its model and score just that agent, without silently regressing the rest.</p><p><strong>The trajectories are clean enough to train on.</strong> It’s the same problem again, with higher stakes. If you want to fine-tune the reconciliation unit, you need examples of reconciliation decisions — not reconciliation decisions tangled up with whatever happened during collection and matching on that particular run. The monolith only ever gives you the tangled kind. The unit gives you clean ones: this input, this decision, this output. Your training set stops being polluted with context that has nothing to do with the task.</p><p><strong>The workflow becomes durable.</strong> That report that died at 99%, with no way back, because checkpointing a swollen context was too heavy to scale? Lean units mean lean state. Each unit’s context is small, so checkpoints are cheap, so time-travel actually works — you roll back to the last accepted artifact and re-run one unit, not the whole 15-dollar workflow.</p><p><strong>And batch processing gets cheap.</strong> Say a unit has to grind through 200 positions. Because its context is clean and single-purpose, memory management is mechanical: keep the SYSTEM prompt and the most recent messages, trim the rest. Progress doesn’t live in the trimmed history — it lives in a TODO-list the unit is gated on. So the context stays roughly constant no matter how many items you process. This is just how you do sequential batch processing with LLMs, and it’s only doable because the unit holds one job and nothing else.</p><p>Try the same trim in the monolith and you can’t even tell what’s safe to drop — the recent messages of one job are sitting on top of four others you might still need. This is how our SQLi units run: a subagent testing one endpoint goes through a lot of try-fail iterations, but we hold its context at SYSTEM plus the latest attempts and let the TODO-list track what’s already been tried. Probing the thousandth endpoint costs about what the first one did.</p><p>So really, none of these are separate wins. They’re all the same thing — keeping each unit’s context isolated — just showing up in different ways.</p><h3>What it costs, and when not to bother</h3><p>So far I’ve made decomposability sound free. It isn’t — and pretending it is would be the same naïveté I’m arguing against.</p><p>The obvious cost is orchestration. Once you have units, something has to invoke them, hand them tasks, and collect what they return — and that machinery is real code, with real cost and real latency. A monolith has none of it: one context, one loop, done. Every seam you cut adds a coordination point, and if you go too deep you end up spending more on coordination than you ever save on focus. That’s the other reason decomposability is a spectrum — there’s a wrong end of it too.</p><p>The less obvious cost — and the one that actually hurts — is the interaction between the units. You’d think the hard part would be artifacts coming back malformed. It mostly isn’t — models are trained for structured output now, so a schema and a retry handle that. The expensive part is everything around the artifact — designing how the hierarchy actually talks to itself:</p><ul><li><strong>Formulating tasks</strong> precisely enough that a unit can act on one in isolation, with no shared history to lean on.</li><li><strong>Gating artifacts</strong> — deciding whether one is allowed to pass downstream. The gate can be deterministic (does the TODO-list check out?), a judgment call (is this good enough to depend on?), or a mix of both.</li><li><strong>Distributing responsibility</strong> across the hierarchy so each unit owns the right slice and nothing falls between the cracks.</li><li><strong>Handling exceptional conditions</strong> — how a unit raises one, and how far up the tree it escalates.</li><li><strong>Controlling iteration budgets</strong> so one sub-tree can’t burn the whole run chasing a single corner case.</li></ul><p>If that list looks familiar, it should — <a href="https://medium.com/@ishish222/the-shared-responsibility-model-for-multi-agent-systems-361ae015ceed">responsibility</a>, exceptional conditions, and <a href="https://medium.com/@ishish222/dont-let-agents-set-their-own-budgets-d6cec086f7ab">budgets</a> are exactly what the earlier pieces in this series are about. And that’s not a coincidence. These are the problems decomposition forces you to solve out in the open: the seams make them visible instead of letting them hide, unsolved, somewhere inside one big context. Decomposition doesn’t create these costs — it just stops you pretending they’re not there. And paying them, deliberately, at every boundary, is most of the actual engineering.</p><p>And sometimes it’s just overkill. A short, single-purpose agent doesn’t need a hierarchy. A prototype you’ll throw away next week doesn’t need benchmarkable units. A low-stakes one-shot task doesn’t need checkpoints and time-travel. Decomposition earns its keep when the workflow is long-running, expensive, multi-stage, and actually has to work in production — when the failures from the opening start to bite. Below that line, all the orchestration is just overhead. The trick is knowing where that line is, and not reaching for a hierarchy on reflex.</p><h3>So decompose first</h3><p>So decomposability isn’t one more best practice on the pile — it’s the thing the others stand on. You don’t get honest evaluation, or affordable durability, or trajectories clean enough to train on, by chasing each one directly. You get them by cutting the system at its seams and letting everything else follow.</p><p>And that’s also why this is the work, not a diagram. The seams in the <em>problem</em> are nearly free — any accountant decomposes IRS reporting without even thinking about it. A decomposable <em>system</em> is not free: it’s most of what I’ve actually done for the last three years, taking agentic systems that were one swelling context and splitting them into hierarchies that each run, fail, and get measured on their own. The payoff isn’t theoretical — but then, neither is the cost.</p><p>It’s also the quiet precondition under everything else I’ve written here. Those shared-responsibility boundaries — who’s responsible OF, IN, and ON the system — are only enforceable if the system has boundaries in the first place. Exceptional-condition handling only stays sane when each unit owns its own failures, instead of one context catching all of them at once. Iteration budgets only mean something when there’s an actual unit to attach a budget to. Decomposability is the keystone all of those were quietly resting on the whole time.</p><p>So when do you reach for it? My answer is: <em>before</em> you reach for autonomy. The reflex, when an agentic system underperforms, is to give it more freedom: more tools, more room to figure things out on its own. I think that’s usually backwards. Decompose first. Add autonomy only inside the units that can actually hold it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c12c9a939565" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Better Agent Will Always Win the Budget Argument]]></title>
            <link>https://medium.com/@ishish222/dont-let-agents-set-their-own-budgets-d6cec086f7ab?source=rss-28d477675631------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6cec086f7ab</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Tomasz Salacinski]]></dc:creator>
            <pubDate>Sun, 31 May 2026 12:05:19 GMT</pubDate>
            <atom:updated>2026-06-01T10:11:16.266Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@ishish222/the-shared-responsibility-model-for-multi-agent-systems-361ae015ceed">foundational piece</a> I argued that most multi-agent failures are responsibility-placement failures: someone moved a decision to the wrong layer, and nobody noticed until production. This piece is about one decision that is almost always placed wrong — the iteration budget — told through the system that taught it to me: a multi-agent autonomous penetration tester. Budget isn’t only something that runs out. It’s something <em>someone has to decide</em>. And the whole story of this piece is the long, embarrassing process of discovering who that someone is — and, more importantly, who it can never be.</p><p>There are two failure modes here, and they pull in opposite directions. On one side, <strong>unbounded resource consumption</strong>: agents that loop, that perfect a sub-task no one asked them to perfect, that quietly burn tokens until someone notices the bill. On the other side, <strong>budget exhaustion</strong>: agents cut off mid-task, dropping work they were supposed to finish. These are not independent bugs. They’re the two ditches on either side of one road. Every naive fix for one of them steers you straight into the other.</p><p>I drove into both. Twice.</p><p>—</p><p>The first ditch announced itself through an evaluation agent.</p><p>It was responsible for triaging every finding from a run — assigning severity, mapping each to OWASP, CWE, ATT&amp;CK. Routine, mechanical, important. Its TODO list was however long the findings list was: sometimes ten items, sometimes a hundred. Its iteration budget was a flat number.</p><p>On a long run it tagged the first batch cleanly, hit the cap, and was forced to report. The findings past the cap were simply… not in the report. Not flagged as skipped. Not raised as incomplete. Gone.</p><p>This is the worse of the two failure modes, and it’s worse for one reason: it’s <em>silent</em>. A looping agent is at least visibly misbehaving — you can see the tokens drain. An agent that stops early and reports confidently looks exactly like an agent that finished. The output had the shape of success. From the orchestrator’s seat, the run was clean. From the operator’s seat, the report was done. From the system’s seat, a third of the findings had ceased to exist.</p><p>—</p><p>The fix for <em>that</em> was obvious, and it’s the reason the cap existed in the first place.</p><p>Before the caps, we had the other ditch: agents that looped, agents that over-invested in trivial sub-goals, the constant background risk of a runaway that — multiplied across a service running for thousands of users — turns into a real and frightening number on an invoice. So we put a ceiling on iterations. A developer-set ceiling: a decision made about the system, from outside it. The agents were told how many iterations they had left.</p><p>The cap worked. It stopped the looping. And it caused the evaluation-agent failure above, because a flat ceiling knows nothing about how much work a given task actually contains.</p><p>That’s the seesaw in one move. The cap was not stupid — it solved the failure mode it was built for. It was just <em>crude</em>: a single number, blind to scope. The placement was right; the design was primitive. Hold onto that distinction, because it matters later: the answer is not to abandon developer-set budgets. It’s to stop pretending one number fits every task.</p><p>—</p><p>So we did the intuitive thing. We moved the decision <em>inside</em> the system.</p><p>Specialists got a tool to request more budget when they were running low. Orchestrators got a tool to grant or deny. A small market: the agent that knows it needs more raises its hand; the supervisor that owns the bigger picture decides. It felt like exactly the right amount of delegated judgment.</p><p>We ran it. We were immediately back in the first ditch — unbounded consumption — because every request was granted.</p><p>The shallow reason is the one I named last time: the orchestrators had no budget of their own. Nothing was scarce to them, so they had no basis on which to refuse. An approver with nothing to protect is not an approver. It’s a relay.</p><p>But the shallow reason isn’t the interesting one.</p><p>—</p><p>The interesting reason is that the specialists were <em>good</em>.</p><p>They wrote genuinely excellent justifications. “I’ve identified seven more injection points that require validation; truncating now would leave the assessment incomplete and could miss a critical finding.” All true. All compelling. And always granted — not because the orchestrator was careless, but because the case was <em>good</em>, and there was nothing on the other side of the scale.</p><p>This is the moment the whole problem turned over for me. We did not have a tuning problem. We had a <strong>conflict of interest</strong>.</p><p>Look at what each layer actually wants. The agent’s goal is to do its task perfectly. The orchestrator’s goal is for the task to be done well enough and the workflow to complete. The system owner’s goal is a balance between quality and cost. None of these is wrong. They are all legitimate. And they do not agree — because “doing the job well” <em>means something different at every level</em>.</p><p>The agent asking for more budget is not misbehaving. It is doing precisely what it was built to do: pursue its task to completion. More budget genuinely serves <em>its</em> goal. The cost of that budget lands on someone else entirely — the owner. <strong>The party that benefits from the resource is not the party that pays for it.</strong> That is the definition of a conflict of interest, and no amount of prompt-tuning dissolves it.</p><p>And here is the part that should make you uncomfortable, because it ran against my instinct: this gets <em>worse</em> as the agents get <em>better</em>. A more capable agent writes a more persuasive request. Capability, in a self-advocating agent, is just competence at winning the argument. You cannot fix a structural conflict of interest by improving the conflicted party. You make it sharper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mlvp4N6ubjpMVIF18FBi-w.jpeg" /></figure><p>I think of it as a hammer that hung one portrait above the fireplace and billed a hundred thousand tokens for it. The portrait is perfectly level. The hammer did its job flawlessly. That is the whole problem — the hammer has no concept of what the portrait was worth.</p><p>—</p><p>Once you see it as a conflict of interest, the question we’d been asking — <em>hard cap or negotiable budget?</em> — turns out to be the wrong question. That’s a question about <strong>mechanism</strong>. The real question is about <strong>placement</strong>: who is allowed to hold this authority at all?</p><p>And the negotiation experiment had already answered it, in the negative. <em>Not the agent.</em></p><p>In the vocabulary of the <a href="https://medium.com/@ishish222/the-shared-responsibility-model-for-multi-agent-systems-361ae015ceed">foundational piece</a>, the negotiation experiment was a <strong>push-down</strong>: a responsibility that belongs to the developer (OF) got shoved into the agent layer (IN). The piece names push-down as a pathology — this was the production receipt for it. (And, as the fix will show, it quietly usurped the operator’s seat too.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*n8lJLNeRwDAt4Q5OAm1lPw.png" /><figcaption>Responsibility for budget split between the system layers</figcaption></figure><p>There’s a subtler trap hiding here, and it’s worth naming because it’s where the smart fix goes to die. The reflex of a good engineer at this point is: <em>fine — bake cost-awareness into the agent’s objective. Make it care about the budget too.</em> It doesn’t work, and it doesn’t work for an instructive reason. The <em>weight</em> on the quality-versus-cost tradeoff is not a constant. It’s the owner’s call, and it changes with the situation — a cheap exploratory scan and a billed production engagement want different balances. Fold that tradeoff into the agent’s objective and you haven’t resolved the conflict; you’ve <em>hidden</em> it, inside a blend ratio that only the owner is entitled to set. The unsettled question is still unsettled. It’s just invisible now.</p><p>So stop thinking about it as alignment. You are not trying to make every layer want the same thing — they legitimately don’t, and they shouldn’t. You are trying to <strong>arbitrate</strong> a permanent tension between several correct goals. Alignment assumes one true objective that everyone should converge on. There isn’t one. There’s a standing disagreement that has to be <em>governed</em>, not dissolved.</p><p>There’s a second hard fact stacked on top of the first. Budget estimation is genuinely, irreducibly difficult. Any pentester will tell you every metric is broken: number of pages over-counts dynamically generated content and under-counts a single-page app; lines of code mislead and often aren’t even available. Nobody can compute the right number in advance — not the developer, not the agent, not the operator.</p><p>Two facts now box in the solution. The agent can’t hold the authority (conflict of interest). And nobody can compute the number (irreducible hardness). What’s left isn’t a preference. It’s the only thing standing after you remove the impossible.</p><p>—</p><p>What we settled on isn’t one mechanism. It’s a deliberate distribution of one responsibility across the layers that are allowed to hold pieces of it.</p><p><strong>Per-agent defaults, set by the developer (OF the system).</strong> Each agent gets a budget baseline derived from what we understand about that agent and from historical production data. This is the best prior — and the test-versus-production distinction lives here, as a multiplier on the baseline, not as a separate machine.</p><p><strong>Deterministic per-item scaling for TODO agents (OF the system).</strong> Where an agent’s work is a list, budget scales with the length of that list, computed when the task is assigned. Not a constant — a function of the actual workload. This is what would have saved the evaluation agent.</p><p><strong>Override knobs for the operator (ON the system).</strong> The backoffice operator can fine-tune individual budgets and overrule the developer’s defaults at runtime. Crucially, those overrides feed back: an override is both an immediate unblock <em>and</em> a signal that the default was wrong, which sharpens the next default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*n8lJLNeRwDAt4Q5OAm1lPw.png" /><figcaption>Layers of the systems hold split parts of budget responsibiliy</figcaption></figure><p><strong>An unresumable exception when the conflict is real.</strong> When the budget and the task genuinely cannot be reconciled, the agent raises a structured exception — a typed, propagated signal that the work can’t be completed as scoped — rather than silently truncating. Honest failure, propagated — never a confident, incomplete report. (This structured-exception channel is a subject in its own right; I treat it fully in Handling Exceptional Conditions in Agent Hierarchies (in progress).)</p><p>Notice what is <em>not </em>on that list. The agent has no authority over its own budget. None. That absence is the entire point.</p><p>But — and this is the line I want to be precise about — the agent is not kept in the dark. It still <em>sees</em> its budget at every step: used, remaining, fraction of the TODO complete. It still <em>acts</em> on that knowledge: finish the in-progress item before starting a new one, escalate early rather than at the wall. <strong>Awareness belongs to the agent. Authority does not.</strong> The agent may know its budget and behave well within it. It may not decide what that budget is.</p><p>And if you’re wondering why the operator is allowed to hold authority when the agent isn’t — it’s the same test, and the operator passes it. The operator doesn’t <em>benefit</em> from inflating an agent’s budget. They’re not the petitioning party; they’re accountable, they have context no single agent has, and they pay attention to the bill. They are exactly the unconflicted party the agent can never be.</p><p>Read as a whole, the fix is just the push-down reversed — budget authority pulled back up to the developer’s defaults (OF) and out to the operator’s knobs (ON), with the agent layer (IN) holding none of it.</p><p>—</p><p>Step back and the real lesson isn’t any one of those four mechanisms. It’s a change of goal.</p><p>We stopped trying to compute the correct budget. We started building for the budget being wrong. A best-effort prior, a human who can correct it in flight, and an honest way to fail when correction isn’t enough. Most teams pour their effort into a better estimate. The estimate will be wrong anyway. The leverage is in the correction paths and the escape hatch — the parts that decide what happens <em>after</em> the number turns out to be wrong, which it always does.</p><p>—</p><p>A few things that outlive the specifics:</p><ul><li>A party that benefits from a resource cannot be the one who approves its use.</li><li>An approver with nothing to protect is not an approver. They’re a relay.</li><li>Awareness belongs to the agent; authority does not.</li><li>When you can’t estimate reliably, invest in correction and escape paths — not in a better single number.</li></ul><p>—</p><p>The headline holds, and it gets more true, not less, as the models improve: don’t let agents set their own budgets. Not because they’re untrustworthy — the opposite. Because they’re conscientious, persuasive, and structurally on the wrong side of the bill.</p><p><em>This is part of a series on failure modes in multi-agent systems. It rests on the framework in </em><a href="https://medium.com/@ishish222/the-shared-responsibility-model-for-multi-agent-systems-361ae015ceed"><em>The Shared Responsibility Model for Multi-Agent Systems</em></a><em>; a companion piece, Handling Exceptional Conditions in Agent Hierarchies (in progress), develops the structured-exception channel used here as the escape valve.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6cec086f7ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Shared Responsibility Model for Multi-Agent Systems]]></title>
            <link>https://medium.com/@ishish222/the-shared-responsibility-model-for-multi-agent-systems-361ae015ceed?source=rss-28d477675631------2</link>
            <guid isPermaLink="false">https://medium.com/p/361ae015ceed</guid>
            <category><![CDATA[agentic-ai-architecture]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Tomasz Salacinski]]></dc:creator>
            <pubDate>Wed, 27 May 2026 18:12:52 GMT</pubDate>
            <atom:updated>2026-05-31T11:24:16.811Z</atom:updated>
            <content:encoded><![CDATA[<p>I keep coming back to one specific post-mortem.</p><p>We had built an autonomous multi-agent system whose main purpose was to carry out security testing tasks. It was a hierarchy of orchestrators and specialists, each responsible for a different piece of the analysis.</p><p>One of them got stuck. It was the agent with a strict sequence of goals, namely:</p><p>1. To collect available information on CI/CD of target<br>2. To collect available information on existing security controls<br>3. To map the gaps between threats and controls<br>4. Register gaps as vulnerabilities</p><p>The agent has been handed over a set of tools to interact with the operator and the information and data presented (go over designs, documentation, etc.).</p><p>The thing is, in initial stress testing, the operator deliberately refused to provide the documentation the agent needed in the first step. The agent couldn’t complete its task, couldn’t skip it, and had no way to communicate why it was blocked. It looped.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*xmqUv1K6CCnG44WoEkGQxw.jpeg" /></figure><p>My first instinct was to give the agent more autonomy. Let it decide what to skip. It felt right — trust the model, get out of its way. But the agent didn’t need more autonomy. It needed a structured channel to say “I can’t continue because X.” These are different things. Confusing them made the system worse, not better.</p><p>Before I understood <em>why</em> the first fix was wrong, I had to answer a question I hadn’t yet named: whose job was it to handle that situation? The agent’s? The developer’s? The operator’s?</p><p>The agents <em>can</em> try and work around obstacles. But <em>should</em> they?</p><p>—</p><p>I have seen the question of depositing responsibility recurring in DevSecOps / security projects. Be it the shared responsibility model in cloud-provisioned infrastructure or platforms or a multi-layered blockchain network. The necessity of defining the responsibility scopes is itself well recognised by the security community. But it seems to me that we’re missing it in multi-agent systems vocabulary.</p><p>Guardrails are part of the answer — they constrain what agents are permitted to do. But they say nothing about what happens when an agent hits a genuine obstacle: a missing input, a broken tool, an exhausted budget.</p><p>The AWS shared responsibility model gave the cloud industry a vocabulary for exactly this kind of confusion. “Security OF the cloud” is AWS’s job. “Security IN the cloud” is yours. The model isn’t a list of rules — it’s a way of saying: <em>this argument you’re having is a responsibility boundary argument</em>. Name the boundary and the argument becomes productive.</p><p>Multi-agent systems need the same vocabulary. Almost every “the agent did something stupid” post-mortem I’ve seen is a boundary argument in disguise. Someone moved a responsibility to the wrong layer and nobody noticed until production.</p><p>Here’s how I think about the layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*VHr9zq2irBs9qTp23-FAIg.png" /></figure><p><strong>The developer is responsible for the system OF the agents</strong></p><p>The developer owns the system structure, the tool surface and what happens when tools fail, the exception schema, the resource/iteration budget management architecture, what “test mode” means versus “production mode,” and the rules that give orchestrators a basis for saying no.</p><p>The principle: <em>if a failure mode is known and recurring, it’s the developer’s job to make handling it structural</em>. Not the agent’s problem to improvise around at runtime. Structural.</p><p>The smell: the same class of failure appears in two different post-mortems, and both times the fix was “we told the agent to be more careful.”</p><p><strong>The agent is responsible for behavior IN the system</strong></p><p>The agent owns runtime decisions within the contract the developer designed — when to retry, when to raise a structured exception, when to report partial results, how to honor a forced sequence or a resource budget.</p><p>The principle: <em>the agent does not own the system structure</em>. “Should this contract be different?” is not a question the agent should answer at runtime. That belongs one layer up.</p><p>The smell: you granted the agent autonomy to work around a recurring obstacle. Its improvised behavior in production became the de facto spec for how that obstacle should be handled — something nobody reviewed or approved.</p><p>The operator owns genuinely irreducible obstacles — the things that cannot be resolved within the system as designed. A session (in context of web application testing) that’s already locked by another user. An input that was never provided. A judgment call that requires human context the system doesn’t have.</p><p>In one of security testing target systems, there was a hard constraint: one active session per user. If someone was already logged in when the agent tried to proceed, there was nothing within the agent’s scope that they could do to resolve this. The correct response was deliberate handover — surface the situation with full context and ask the operator to resolve it. Not retry. Not improvise. Hand over.</p><p>The principle: <em>operator handover is a first-class outcome, not a failure mode</em>. A well-designed system routes to the operator deliberately, at the right moment, with full context. An under-designed one routes there accidentally, after something has already gone wrong.</p><p>The smell: the operator is getting paged for the same problem every week. That recurring page is developer-layer debt being paid at the operator level.</p><p>—</p><h3><strong>Four ways teams get this wrong</strong></h3><p><strong>Responsibility push-down by developer<br></strong>The developer leaves a known failure mode unstructured, hoping the agent figures it out. The agent improvises under pressure. The incident report says “the model hallucinated.” What actually happened: an unspecified decision got made by the layer least equipped to make it deliberately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*epTsGWKURoSwFlWCBlJr4A.png" /></figure><p>This is responsibility OF the system misplaced as responsibility IN the system.</p><p><strong>Responsibility push-down by operator<br></strong>The operator (often the customer) doesn’t deliver something only they can deliver: a missing input, an approval, access to a system the agent can’t reach. The team’s instinct: “let’s make the agent smarter so it can handle this case.” But no amount of intelligence compensates for an operator’s irreducible role — there’s no contract the developer could write that resolves the problem. The fix is the handover, not the workaround.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*zBg7kyue087Vno43Nffm8g.png" /></figure><p>This is responsibility ON the system misplaced as responsibility IN the system.</p><p><strong>Responsibility push-up<br></strong>The agent escalates routine work to the operator because no structured channel exists to handle it. The operator becomes a bottleneck for things that should be automated. The team’s read: “we need better tooling.” The actual problem: the contract is missing a clause.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*eLctkA2F30KWUti8NwQZAA.png" /></figure><p>This is responsibility IN the system misplaced as responsibility ON the system.</p><p><strong>Boundary drift<br></strong>The same responsibility lives at all three layers, inconsistently. The developer encoded one rule. The system prompt has a slightly different version. The operator’s runbook has a third. Nobody knows which is authoritative until something breaks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*csDL6nqASVfsAh8CYZbv2Q.png" /></figure><p>This is responsibility scattered across OF, IN and ON the system.</p><p><strong>Responsibility push-down by operator, </strong>mixed with<strong> push-down by developer </strong>is what happened in my post-mortem. The forced sequence was correct. What was wrong was the absence of a structured exception mechanism to address operator’s push-down — a developer-layer artifact. The agent didn’t need more freedom. It needed a better contract.</p><p>—</p><p><strong>Where the analogy breaks — and why that makes it more useful</strong></p><p>In AWS’s model, the boundary is enforced by APIs. You can’t accidentally operate in AWS’s responsibility zone — the interface won’t permit it. The developer/agent/operator boundary doesn’t work that way. There is no fixed contract that works for every process. It’s up to architects to define and refine them, and for developers - to enforce them.</p><p>This means hierarchy architecture-layer work carries <em>more</em> weight in multi-agent systems than in cloud, not less. The contracts need to be logical and clearly formulated, the contract execution should be observable and responsibility issues be detected.</p><p>Every failure mode left unstructured at the developer layer will eventually be improvised at the agent layer — unpredictably, at the worst possible time.</p><p>—</p><p>The cloud industry learned this the hard way, then gave it a name, and the name made the argument productive. Multi-agent systems are early enough that most teams are still reinventing the lesson per project. You don’t have to.</p><p>The issue of responsibility definitions is of course has much more complexity than this article form would allow to capture. For example, we didn’t touch on the depositing responsibilities between specific agent roles — e.g., when subordinate should escalate to the manager?</p><p><em>This is the foundational piece in a series on failure modes in multi-agent systems. The pieces that follow apply this framework to specific production failures — among them iteration budget management and exception handling in agent hierarchies.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=361ae015ceed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Spider Outside My Window: Implanting Memories in Chatbots]]></title>
            <link>https://medium.com/@ishish222/a-spider-outside-my-window-implanting-memories-in-chatbots-56a7e0ef0e77?source=rss-28d477675631------2</link>
            <guid isPermaLink="false">https://medium.com/p/56a7e0ef0e77</guid>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[psychology]]></category>
            <dc:creator><![CDATA[Tomasz Salacinski]]></dc:creator>
            <pubDate>Wed, 06 Aug 2025 12:40:55 GMT</pubDate>
            <atom:updated>2025-08-07T20:50:44.447Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>More human than human!</blockquote><blockquote>- Dr Eldon Tyrell, founder of the Tyrell Corporation in Blade Runner (1982)</blockquote><p>Please note, that’s not “more intelligent”, “more knowledgeable” or “stronger”, but “more human”. Is that even possible? Well, no, but it is ambitious!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o73capzd0Ppt5H624FTmzA.jpeg" /><figcaption>Dr. Eldon Tyrell</figcaption></figure><p>The Omote Project is my attempt to build on Dr Tyrell’s ambitions with the help of an LLM’s augmented generation. His groundbreaking creation, Rachael (an advanced Nexus 6 or 7 model) was a replicant, but unaware of it (for the sake of this article, I’m putting aside all philosophical/ethical considerations). He achieved it by implanting his niece’s memories in the android. Thanks to those, Rachael was able to construct all of the components of “being human”: a gallery of identities (strong and weak ones), her goals, fears, anxieties and vulnerability that would later make Deckard fall in love with her.</p><p>Now consider our contemporary chatbots: when you last talked to your favourite chatbot, was there any chance you could have mistaken it for a human? I don’t think so. There are too many differences, many of them probably acknowledged by the bots themselves. They don’t respond in an emotional manner and they feel impersonal, like some kind of a “sum total of humans” (which, in a way, they are). They seem too perfect to be a person. They can say something like “That’s very exciting!” or “That sounds like a terrible situation”, but that doesn’t come close to being emotional.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*27Nx-PQSfgTYVKDMrcYSpw.jpeg" /><figcaption>Rachael during the Voight-Kampff test</figcaption></figure><p>When thinking about how Rachael’s humanity is superior to our trusty chatbots’, and trying to put my finger on the specific differences, I often come back to our internal state and how important it is to all this. How it is split in two parts: the fleeting part, such as moods, emotions, our sustenance needs and the lasting part: our experience, knowledge, hopes, fears and much more. And the interplay between these two.</p><p>A bit unexpectedly, Japanese sound symbols come to mind. These are very close cousins to what in most European languages would be called onomatopoeia, but not exactly. Sound symbols convey not only the sound itself (like woof woof/hau hau) but also the speaker’s internal state. キラキラ (kira-kira) captures the sparkle of jewellery; フワフワ (fuwa-fuwa) the plush lightness of something fluffy. One of my favourites is ドキドキ (doki-doki), which means to hear the beating of one’s own heart. We can experience this both in scary and exciting situations, for example, when we are about to propose to our partner or when we are being chased by a stray dog.</p><p>What this internal state of ドキドキ communicates is much more complex than “That’s exciting”. It’s a feeling that our entire world can change in a matter of seconds: we can see the desired reward or the risk we so badly want to avoid just within reach. Our mind tunnels, blocking out unnecessary detail, our throat tightens, we stutter and scramble. No, a simple “that’s exciting” doesn’t cut it.</p><p>There is so much complexity packed into a mere sentence or our reaction in a conversation. There’s a setting to consider — are we in an office or a war zone, only slightly thirsty or extremely so? What do we fear or hope for? What about our identities? Do we want to be perceived as “artists” because our parents might’ve praised that in us when we were young? Or maybe our peers ridiculed us as “dummies” and we’ll do anything to avoid being perceived as such? Many of these are our own interpretations of the past or projections we may be running towards or away from. They’re all in our heads, but they inform our reactions in a very real way.</p><p>In the Omote framework I try to harness the potential of LLMs to create narratives by structuring the fleeting and lasting internal states and the interplay of these in the minds of fictional characters. Omote allows me to initially create a setting of choice (a “world”) and to use it to develop a fictional character with an internal state that’s grounded in the world.</p><p>As an example, let’s consider one of the characters I came up with. Minako is a 20 year old Ikebana artist set in a fictional post-nuclear war world. Take a look at the conversation I had with Minako as another character named Tsukumo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z9uTQPHFFG1G_vrtN6ym9Q.png" /></figure><p>The dialogue is a result of an LLM-backed generation augmented in a sequence of behind-the-scenes operations. The set and setting are this: the user runs into Minako at a sushi bar around 9pm and Minako is slightly hungry. At first she doesn’t recognize Tsukumo, but that begins to change as Tsukumo brings up a shared memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9x0EPcj3nIH1TP948t311g.png" /></figure><p>Minako’s reaction — recognising her acquaintance — is an immediate effect of an internal dialogue taking place in Minako’s emulated mind.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RhVkCrhXpIguxvexK4J9mQ.png" /></figure><p>Here, three departments decide on how to react. The Reliquary department is responsible for managing her personal memories, the Weeper’s Mill constructs emotions, and the Wardrobe manages Minako’s internalised identities, both the ones she pursues and the one she avoids. All three departments together assess various aspects of the situation and what the optimal reaction would be. Based on this, the executive department (The Warden) implements the decided-upon reaction while also taking into account her communication style (in this case, a large vocabulary and a tendency to use metaphors). The entire process is executed within a system composed of 7 AI agents:</p><ul><li>Wardrobe (manage identities)</li><li>Reliquary (personal memories)</li><li>Basilica ( a repository of known facts about a fictional world)</li><li>Bone Chorus (manages current needs, sleep, nutrition, social interactions)</li><li>Murmuring (manages sexuality)</li><li>Ventral Striatum (calculates rewards and risks)</li><li>Warden (the executive)</li></ul><p>The Warden is a key department in Minako’s mind. It is aware of the current situation and based on this understanding, on the high-level character description and their personal history, it selects the participants of internal dialogues. After the internal dialogue has finished (usually resulting in departments’ consensus but potentially — conflict), it deploys the reaction.</p><p>Taking one step back, the set and setting that are used for generating Minako’s character are crucial. This is the world that she is embedded in as a person. Given, say, a specific city and family history, Minako’s early and middle infancy could shape her perception of the world as a safe or unsafe place, which in turn can influence her openness to experience and extroversion at a later point in life.</p><p>This set and setting is in turn generated by a set of separate agents. One of them is responsible for writing the overall world history, another one — the create a specific country embedded in the overall world, and so on, until we reach an agent generating narrative for Minako’s family and Minako’s character itself.</p><p>When it comes to creating the character, the agent takes on the fragments of relevant world &amp; family history (relevant meaning a specific country, city and family) and proceeds to generate chapters of Minako’s personal history, one by one. So, for example, it starts with some randomized HEXACO parameters and a set of parameters related to sexual identity and sexuality. Given the subject matter, it goes through the relevant predefined stages of life during which various parameters related to the subject matter are generated and adjusted. Starting with the aforementioned infancy, through early and middle childhood, core memories related to parenting style, peer interactions etc. are formed, which will inform a sense of identity. The agent continues this until Minako reaches the desired age (20).</p><p>At this age the character is in possession of a set of personal memories, identities, goals, fears, a vocabulary of a certain capacity, some behavioral repertoire and language characteristics. In short, a small portion of all of those innumerable treasures — be it a memory of “a spider laying eggs outside of my window” or of “C beams glitter in the dark near the Tannhauser Gate” — that make us human and allow us to interact with other humans.</p><p>. . .</p><p>I’m still considering where to go with the Omote framework from here. The original idea was inspired by the game Disco Elysium and enriching user experience in gaming by creating rich Non-Playable Characters is one of potential directions. If you have creative ideas about where I should take it, feel free to reach out!</p><p>. . .</p><p>For the full demo dialogue please see the following recording:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FlCE_Yza4Z9U%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DlCE_Yza4Z9U&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FlCE_Yza4Z9U%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a18e7f4ff72ac229e8c674317bbf8487/href">https://medium.com/media/a18e7f4ff72ac229e8c674317bbf8487/href</a></iframe><p>For the Omote project I used the following tech stack:</p><ul><li>Python</li><li>Langchain / LangGraph</li><li>LangSmith for debugging agent trajectories</li><li>LangGraph platform for serverless agents</li><li>openrouter.ai as a model broker</li><li>Gradio for prototyping UX</li><li>AWS ECS for managing workloads</li><li>Docker, GH Actions, Terraform for the deployment pipeline</li></ul><p>…</p><p>Edited by <a href="https://www.lunifer.net/">Alexandra</a> <a href="https://blogtherapy.substack.com/">Ciufudean</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56a7e0ef0e77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Layered threat model for Web3 applications part 1— distribution of responsibility]]></title>
            <link>https://medium.com/@ishish222/layered-threat-model-for-web3-applications-part-1-distribution-of-responsibility-86ab91cb7f81?source=rss-28d477675631------2</link>
            <guid isPermaLink="false">https://medium.com/p/86ab91cb7f81</guid>
            <category><![CDATA[threat-modelling]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[it-security]]></category>
            <dc:creator><![CDATA[Tomasz Salacinski]]></dc:creator>
            <pubDate>Mon, 03 Jun 2024 22:14:11 GMT</pubDate>
            <atom:updated>2024-06-16T13:46:33.731Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone! I want to talk to you about something that is very exciting for me: threat modeling for web3 applications. But as usual, I’d like to start with a bit of an intro. If you don’t like intros, feel free to skip to section <strong>Damn Vulnerable Blockchain as a reference PoW blockchain</strong> which contains the details of the DVB implementation, or subsequent parts of this cycle.</p><p>The code for the DVB implementation that will be refered to in these articles can be accessed here: <a href="https://github.com/ishish222/damn_vulnerable_blockchain">https://github.com/ishish222/damn_vulnerable_blockchain</a>.</p><p><strong>WARNING: Please note that this implementation contains critical vulnerabilities and should not be used for production purposes</strong>.</p><h3>Trusting complex technologies</h3><p>Let’s say you’re travelling to a different country by plane. When the date of your travel finally arrives, when you arrive at the airport and enter the airplane, you trust the this device with a highly sensitive asset, i.e. your life. And this machine that will carry you and your co-passengers for the next couple of hours is an incredibly complicated device. There are millions of moving parts that need to play their role well enough to bring you all safely to your destination terminal. And there are thousands of things that can go wrong and, well, sometimes they do. But, surprisingly, the failure rate of such complex process is low when compared e.g. to failures in medicine/healthcare or in justice systems.</p><p>How do the airlines ensure that such complex process is secure?</p><p>Okay, I’m not an expert but here’s what I think: plane vendor makes sure that experts who oversee assembling of the plane have sufficient expertise. The experts are vetted, their background is being researched, their competence is certified. The parts are certified by vetted companies. The companies vetting the certifying companies are themselves audited. Roles in the process (pilot, navigator, air traffic controller, ground controller) are assigned to vetted experts. Companies who provide experts are audited. Passengers and their belongings are screened. Anomalies and incidents are thoroughly investigated by commissions assembled of experts. Reports are published, lessons learned are shared with community and continuous improvements are being made.</p><p>In other words, there are layers of processes, procedures, roles and equipment that rely on other layers. The responsibilities of each layer are being clarified and communicated. If a layer provider is not performing well enough, it’s being replaced by a different provider.</p><p>Airlines mastered this system.</p><h3>Trusting Ethereum</h3><p>We trust Web3 applications with highly sensitive assets as well. In risky and often hostile environment it’s only fair to expect of web3 solutions similar dedication in mitigating risks.</p><p>For me breaking down the entire technology stack of blockchain applications is a convenient way to decompose the threat model which otherwise would be very complex. It’s a very similar approach to decomposing the network stack into standard OSI model layers.</p><p>It seems to me that this approach to blockchain layers is getting traction especially because new modular nodes and L2 solutions are being created and the whole ecosystem would be too complex without this kind of decomposition.</p><p>Let’s go over the reference layers then.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZYPVZ1Vbda3oJRQMdfX7iw.png" /></figure><p>On top of the Ethereum stack we have the execution layer (EVM) that is responsible for ensuring that all transactions are executed according to smart contracts and governing standards. When the smart contract code lays out the rules for governing a DAO, I expect that these rules are followed in the network, i.e. changes are being voted on and accepted/rejected based on voting rules.</p><p>But in order to efficiently progress the transaction execution, we need processing nodes. If we want processing nodes to provide computing power to the network, we need to incentivize them somehow. We need native currency. If we want to have native currency, we need to make sure e.g. that spender has enough currency to transact and that one unit of currency cannot be spent twice by the spender. Therefore, we need transaction settlement layer that will make sure that outputs of a given transaction are equal to inputs of a given transaction. EVM relies on guarantees provided by the settlement layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*nCEl9i4P2MwTEx7OYJJ_Yw.png" /><figcaption>Source: celestia.org</figcaption></figure><p>Now the settlement need to have the transactions ordered. E.g. if Alice has 2 dollars and she attempts to spend 2 dollars in transaction A and 2 dollars in transaction B, the settlement layer needs to understand whether it should first accept transaction A and reject B for lack of sufficient currency or the other way around. So we need a layer that will sequence the transactions. And to agree on a sequence of transactions is no easy task in a trustless environment! We need efficient BFT consensus protocol provided by the consensus layer that will append blocks to our blockchain and have majority of nodes agree on the ordering.</p><p>Then we have the problem, how do we ensure that the consensus has the necessary data available? How are newly mined blocks being broadcasted across the network or transaction pool is synchronised? Again, consensus layer relies on the data availability layer to provide these guarantees.</p><p>And then we have the entire OSI network layer model with it’s traditional web2 threat model.</p><h3><strong>Damn Vulnerable Blockchain as a reference PoW blockchain</strong></h3><p>In my analyses of the threat models I wanted to rely on something specific so I created a very simple blockchain node. It’s far from perfect but it is sufficient for examining the layers in specific context. You can get the code here:</p><p><a href="https://github.com/ishish222/ishishnet">GitHub - ishish222/ishishnet: Small PoW blockchain node</a></p><h4>Data layer</h4><p>The node is written in Rust and is using libp2p’s Transports (TCP/noise/yamux) and NetworkBehaviors (mDNS/Gossipsub) to implement the data availability layer.</p><p>Constructing the swarm (data.rs):</p><pre>pub fn build_swarm(<br>) -&gt; Result&lt;(libp2p::Swarm&lt;DvbClientBehavior&gt;, IdentTopic), Box&lt;dyn Error&gt;&gt; {<br>    let mut swarm = libp2p::SwarmBuilder::with_new_identity()<br>        .with_tokio()<br>        .with_tcp(<br>            tcp::Config::default(),<br>            noise::Config::new,<br>            yamux::Config::default,<br>        )?<br>        .with_behaviour(|key| {<br>            // To content-address message, we can take the hash of message and use it as an ID.<br>            let message_id_fn = |message: &amp;gossipsub::Message| {<br>                let mut s = DefaultHasher::new();<br>                message.data.hash(&amp;mut s);<br>                gossipsub::MessageId::from(s.finish().to_string())<br>            };<br><br>            // Set a custom gossipsub configuration<br>            let gossipsub_config = gossipsub::ConfigBuilder::default()<br>                .heartbeat_interval(Duration::from_secs(10)) // This is set to aid debugging by not cluttering the log space<br>                .validation_mode(gossipsub::ValidationMode::Strict) // This sets the kind of message validation. The default is Strict (enforce message signing)<br>                .message_id_fn(message_id_fn) // content-address messages. No two messages of the same content will be propagated.<br>                .build()<br>                .map_err(|msg| io::Error::new(io::ErrorKind::Other, msg))?; // Temporary hack because `build` does not return a proper `std::error::Error`.<br><br>            // build a gossipsub network behaviour<br>            let gossipsub = gossipsub::Behaviour::new(<br>                gossipsub::MessageAuthenticity::Signed(key.clone()),<br>                gossipsub_config,<br>            )?;<br><br>            let mdns =<br>                mdns::tokio::Behaviour::new(mdns::Config::default(), key.public().to_peer_id())?;<br>            Ok(DvbClientBehavior { gossipsub, mdns })<br>        })?<br>        .with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(60)))<br>        .build();<br><br>    // Create a Gossipsub topic<br>    let topic = gossipsub::IdentTopic::new(DVB_TOPIC);<br><br>    // subscribes to our topic<br>    swarm.behaviour_mut().gossipsub.subscribe(&amp;topic)?;<br>    Ok((swarm, topic))<br>}</pre><h4>Consensus layer</h4><p>Consensus layer is implemented based on simple PoW, i.e. the most heavy chain is the correct one.</p><p>The weight of the chain in case of DVB is the length of a chain that passes the correctness tests. The tests currently include verification of the PoW solution and hashes pointing to the previous block.</p><p>The PoW solution difficulty is not decided by the network but simply passed as an argument to a node (for simplicity). PoW is looking for a nonce that will result in a block hash with a number of leading zeros.</p><p>Mining the PoW (consensus.rs):</p><pre>pub fn proof_of_work(<br>    mut block: DvbBlock, <br>    difficulty: usize<br>    ) -&gt; Result&lt;DvbBlock, DvbError&gt; {<br>    println!(&quot;proof_of_work::start&quot;);<br><br>    let mut nonce = rand::thread_rng().gen();<br>    loop {<br>        let mut hasher = Sha256::new();<br>        block.header.nonce = nonce;<br><br>        let data = serde_json::to_string(&amp;block)?;<br><br>        hasher.update(data);<br><br>        let hash: [u8; 32] = match hasher.finalize().try_into() {<br>            Ok(arr) =&gt; arr,<br>            Err(_) =&gt; return Err(DvbError::HashConversionFailed), <br>        };<br><br>        if hash.iter().take(difficulty).all(|&amp;b| b == 0) {<br>            block.header.cur_hash = hash;<br>            println!(&quot;proof_of_work::finish&quot;);<br>            return Ok(block);<br>        }<br>        nonce += 1;<br>    }<br>}</pre><p>If the node is mining and it mines a correct block, new block is appended to the local blockchain and the local blockchain is then broadcasted to the peers via the data layer.</p><p>When a peer receives a broadcast about a new blockchain, it performs the necessary checks (PoW solutions, correct hashes) and if the tests are passed, it accepts the blockchain as a local.</p><p>Processing received blockchain (consensus.rs):</p><pre>pub fn process_new_blockchain(<br>    new_blockchain: DvbBlockchain, <br>    current_blockchain: DvbBlockchain, <br>) -&gt; Result&lt;DvbBlockchain, Box&lt;dyn Error&gt;&gt; {<br><br>    println!(&quot;Got new blockchain: {new_blockchain:?}, verifying&quot;);<br><br>    if new_blockchain.blocks.len() &gt; current_blockchain.blocks.len()<br>    {<br>        println!(&quot;Received blockchain is heavier, verifying hashes&quot;);<br>        match DvbBlockchain::verify_chain(&amp;new_blockchain) {<br>            Ok(()) =&gt; {<br>                println!(&quot;Verification passed, accepting new blockchain as local&quot;);<br>                Ok(new_blockchain)<br>            }<br>            Err(e) =&gt; {<br>                println!(&quot;Blockchain verification failed {e:?}, ignoring&quot;);<br>                Ok(current_blockchain)<br>            }<br>        }<br>    } else {<br>        println!(&quot;Received blockchain is lighter, ignoring&quot;);<br>        Ok(current_blockchain)<br>    }<br>}</pre><h4>Settlement layer</h4><p>The settlement layer takes care of updating the balances of the accounts based on the miner rewards and transactions in mined blocks.</p><p>Currently newly retrieved and accepted blockchain is used to recreate the current state of the network from scratch (settlement.rs):</p><pre>pub fn progress_state(<br>    db: &amp;mut InMemoryDB, <br>    block: &amp;DvbBlock, <br>    transactions: &amp;mut Vec&lt;DvbTransaction&gt;<br>) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {<br>    /* reward coinbase */<br>    let coinbase = block.header.coinbase;<br><br>    increase_account(db, coinbase, 1)?;<br><br>    /* process transactions */<br>    for tx in block.content.iter() {<br>        process_transaction(db, tx)?;<br>        remove_transaction_from_pool(tx, transactions)?;<br>    }<br><br>    Ok(())<br>}</pre><p>The current implementation of DVB is missing the execution layer which I will add once I figure out the ins and outs of the <a href="https://github.com/bluealloy/revm">REVM</a> library. Therefore, for now transactions only contain transfers of dvb (the native currency) between the accounts:</p><pre>get_balance<br>Processing command: get_balance<br>Enter the name of the wallet [coinbase]<br><br>Balance of 0x93Ae5cf7A6eEa2F5D7144dd4E9Df025A692aAaD0: 7<br>get_balance <br>Processing command: get_balance<br>Enter the name of the wallet [coinbase]<br>0x68d9D11C0A4D67074b78B797e4AC5aB4a50D3408<br>Balance of 0x68d9D11C0A4D67074b78B797e4AC5aB4a50D3408: 3<br>send_dvb<br>Processing command: send_dvb<br>Enter the name of the source wallet [coinbase]<br><br>Enter the target wallet<br>0x68d9D11C0A4D67074b78B797e4AC5aB4a50D3408<br>How much dvb to send?<br>5<br>Sending 5 dvb from 0x93Ae5cf7A6eEa2F5D7144dd4E9Df025A692aAaD0 to 0x68d9D11C0A4D67074b78B797e4AC5aB4a50D3408<br>Sending line: &quot;TRA{\&quot;from\&quot;:\&quot;0x93ae5cf7a6eea2f5d7144dd4e9df025a692aaad0\&quot;,\&quot;to\&quot;:\&quot;0x68d9d11c0a4d67074b78b797e4ac5ab4a50d3408\&quot;,\&quot;amount\&quot;:5}&quot;<br>Transaction added to local pool<br>Current pool: [DvbTransaction { from: 0x93ae5cf7a6eea2f5d7144dd4e9df025a692aaad0, to: 0x68d9d11c0a4d67074b78b797e4ac5ab4a50d3408, amount: 5 }]</pre><h4>Execution layer</h4><p>Currently pending but will be probably implemented with REVM.</p><h4>Wallet manager</h4><p>The DVB implementation comes with a simple alloy-based wallet manager that allows you to create and manage your wallets. It’s pretty straightforward:</p><pre>$ target/debug/wallet create test<br>Home dir: &lt;$HOME&gt;/.dvb<br>Creating new wallet<br>Please enter a password for the wallet<br>&lt;password&gt;<br>Created wallet: 0x68d9D11C0A4D67074b78B797e4AC5aB4a50D3408 in keystore &lt;$HOME&gt;/.dvb/test</pre><h4>Other libraries used</h4><p>The serialization is done with <a href="https://github.com/serde-rs/serde">serde</a> and concurrency is implemented using the <a href="https://github.com/tokio-rs/tokio">Tokio</a> runtime. I heavily used primitives from the <a href="https://github.com/alloy-rs/alloy">Alloy</a> library and, as I already mentioned, <a href="https://github.com/bluealloy/revm">REVM</a> will be used for implementing the execution layer.</p><h3>Spinning up the node</h3><p>In order to run the network, you can simply build and spin up several local nodes (pass required PoW difficulty as a sole parameter):</p><pre>$ target/debug/node 2<br>Reading commands from stdin<br>Starting the local mining task<br>Local node is listening on /ip4/127.0.0.1/tcp/39447<br>Local node is listening on /ip4/192.168.1.2/tcp/39447</pre><p>The node will start other nodes joining the network and will broadcast relevant events. You can enter commands for the node via stdin. Currently implemented commands include:</p><ul><li><strong>start: </strong>start mining new blocks</li><li><strong>stop: </strong>stop mining new blocks</li><li><strong>open</strong>: open a wallet and set it as the mining coinbase</li><li><strong>get_balance</strong>: query the current network state for a balance of a given account</li><li><strong>send_dvb</strong>: create a transaction that sends a specified amount of dvb to a target account.</li><li><strong>print_pool</strong>: print the contents of the local transaction pool</li></ul><pre>start<br>Processing command: start<br>Building a block proposal<br>mining_task::Updating current_block<br>mining_task::Starting mining<br>Starting the mining for a new block<br>proof_of_work::start<br>proof_of_work::finish<br>mining_task: Mined block<br>Successfuly mined block: DvbBlock { header: DvbBlockHeader { coinbase: 0x68d9d11c0a4d67074b78b797e4ac5ab4a50d3408, number: 0, nonce: 14689956009786713665, difficulty: 2, cur_hash: [0, 0, 254, 204, 27, 221, 37, 126, 20, 156, 190, 13, 23, 125, 208, 159, 15, 31, 9, 5, 72, 128, 227, 158, 173, 144, 139, 244, 104, 192, 247, 34], prev_hash: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }, content: [] }<br>Updated balance for 0x68d9D11C0A4D67074b78B797e4AC5aB4a50D3408: AccountInfo { balance: 1, nonce: 0, code_hash: 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470, code: Some(LegacyAnalyzed(LegacyAnalyzedBytecode { bytecode: 0x00, original_len: 0, jump_table: JumpTable { map: &quot;00&quot; } })) }<br>Building a block proposal<br>mining_task::Updating current_block<br>Starting the mining for a new block<br>[...]</pre><h4>Summary</h4><p>In this article I wanted to introduce you to the concept of layers in blockchain networks. As the blockchain technology is very complex, we introduce the layering to decompose the threat model and analyze it layer by layer.</p><p>I also proposed an example Damn Vulnerable Blockchain blockchain as a reference model to discuss the threats and corresponding mitigating security controls at selected layers in a more concrete manner.</p><p>Stay tuned for subsequent parts where we’ll delve into the data layer and try to create a threat model to understand the risks and figure out mitigating security controls.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86ab91cb7f81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code Mentat — code analysis w/ Claude 3]]></title>
            <link>https://coinsbench.com/code-mentat-code-analysis-w-claude-3-4343b5c637dc?source=rss-28d477675631------2</link>
            <guid isPermaLink="false">https://medium.com/p/4343b5c637dc</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[it-security]]></category>
            <category><![CDATA[vscode-extension]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[web3]]></category>
            <dc:creator><![CDATA[Tomasz Salacinski]]></dc:creator>
            <pubDate>Thu, 18 Apr 2024 12:42:17 GMT</pubDate>
            <atom:updated>2024-04-22T14:50:21.262Z</atom:updated>
            <content:encoded><![CDATA[<h3>Code Mentat — code analysis w/ Claude 3</h3><p>Hello everyone! It’s your favourite rabbit here! I have another crazy idea that I want to test. This time I’m working on a VSCode plugin that would enable me to understand source code better and faster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s-nompeu2MsUf8HuUDo3PQ.png" /></figure><p>As usual, I’m sharing my code fot the Mentat plugin discussed here (It’s not the most elegant at the moment, please forgive me): <a href="https://github.com/ishish222/mentat">https://github.com/ishish222/mentat</a></p><p>Why do I need this? Well, in my experience one of potential security-related bottlenecks in a company is secure change management. As we all know, nowadays we’re trying to build and deliver features in a continuous manner. But when we have 20+, 50+, 100+ of skilled and creative developers working around the clock and producing new features it becomes difficult to keep things going smoothly and securely.</p><p>On one hand the Product Managers are struggling to keep up with their deadlines and deliver the features fast, but on the other hand there’s security team what is expected to make sure that they are thoroughly reviewed. And sometimes we become the bottleneck of the continuous delivery.</p><p>Automatic and semi-automatic SAST and DAST tools are a must, but they’re still not enough. W need better understanding than matching patterns, heuristics and low-hanging fruits. For example, we need to understand what sensitive assets are being introduced within the feature. Or how does the feature affect the likelihood of various scenarios. Does it introduce new ones. E.g. if we’re introducing multi-tenancy in our application, we should the the scenario of breaking tenant isolation. Whether all required security controls present and properly integrated.</p><p>To figure out answers to these questions, we need to understand functions, use-cases, architecture and business logic. I am hoping that LLMs can help us with that.</p><h4>Code generation vs. code understanding</h4><p>We have a lot of coding co-pilots available already. They have varied quality of produced content, but we have them. But code understanding is a task of an entirely different nature. Both processes involve working with programming languages. These languages live somewhere in-between structured data (instances of Abstract Syntax Tree classes) and natural language (the words are formed in sequences and the order of individual words carries meaning).</p><p>In code generation, based on the code that you start to write, the co-pilot usually suggests the continuation based on the meaning extracted from your prologue. In case of code understanding the task at hand is to read a snippet of code and understand its relevance within the wider context it’s been framed into. But! The snippet at hand is itself a context in which other parts of code are being framed into. In order to understand the given snippet, you need to understand all the snippets that are being used within it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*FXNOppJwHuLG3-iz9cLQdg.png" /><figcaption>To understand processing HTTP request header you need to understand strcmp!</figcaption></figure><p>In my reverse engineering days I’ve been heavily relying on trees of code snippets (well, in case of recurrent function calls they’re actually graphs, but let’s agree that 90% of time they’re trees). This approach doesn’t change much wether you use assembly or source. This is the ground idea behind implementing the Mentat plugin.</p><h4>Code understanding with LLMs</h4><p>So the first thing about LLMs is that they are good at extracting meaning from a sequence (consider ordering) of words, be it in natural language sentences or “pseudo”-natural programming language. They are also able to employ “knowledge” (represented by internal weights) when generating their responses. That’s already much more that any traditional algorithm can offer.</p><p>But, the issue with harnessing this potential is in the relationships between the snippets. In order to generate high-quality explanation, the model still needs to know the role of all the functions, objects and types that are used within the snippet. Someone can say hey rabbit, all the new models have huge context windows that can swallow entire repos! (currently I think Gemini 1.5 is leading the race with 1M token context window). But we need to remember that what we’re ultimately after is a high quality output. Meaning, the we need the model to follow complex instruction and generate and double check appropriate response. What’s the point of having even even 100M token context windows if the model returns output that is garbage? Or, if it returns responses that proceed to ignore 50% of the input? Because that’s what happens when we include instructions that are too complex.</p><p>Can you imagine the complexity of interrelationships between code snippets in an entire repository of the Linux kernel? Can we expect the models to handle it well if not broken down and decomposed? Well, my experience says no, at least I don’t know how to make them.</p><p>I am a big fan of decomposition and carefully structuring LLM’s prompts according to the prompt engineering practices. I found out that some well-thought improvements, though relatively small, like and appropriate in-context example, or following the recommended prompt structure can improve the output significantly. And, above all, decomposition. The approach applied in the Mentat plugin to achieve code understanding is based on decomposing a complex and demanding task of processing entire repo into smaller, well-structured tasks.</p><h4>Understanding Solidity contracts</h4><p>Let’s talk about Solidity contracts. I am often amazed how complex web3 dApps have become. Sometimes it makes it challenging to quickly (or even slowly) grasp the business logic behind them. The fact that the web3 foundational premises themselves are challenging some of our assumptions on how applications should work (assumptions we brought from the web2 realm) does add to the complexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cd9Oyjd4F49T_RizO4TLFA.png" /></figure><p>For some time I was trying to come up with a way to apply this tree-based decomposition technique to Solidity contracts. The dApps can often be represented by a network of contracts interacting with each other. Each of those contracts usually inherits some features from parent contracts. In order to manage all of these plus state variables plus interfaces plus structures, etc., etc. I started exploring the concepts of Language Server Protocol and symbol management in VSCode plugins framework. But I encountered some problems. Many plugins that provide some LSP services for Solidity are not as mature as their counterparts in Python or C. Also, symbols themselves don’t really capture the understanding decomposition entirely. They are close, but just a bit short.</p><p>Then while looking for potential solutions I encountered the solidity-workspace package and it’s contract flattening function. Flattening the contract is the process of capturing the contract itself and all of his dependencies in terms of inheritance in one sourcecode unit. Which prompted me to try a different approach. So, in the new approach I flatten the contract and the tree creation task that I burden the LLM with :).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FyiGevTyN4nA&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DyiGevTyN4nA&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FyiGevTyN4nA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6ce70874ae14d82144493cac469a723/href">https://medium.com/media/f6ce70874ae14d82144493cac469a723/href</a></iframe><h4>Implementation</h4><p>I think VSCode is a perfect framework for such functionality. Most developers are already familiar with it’s functionality and more or less familiar with the plugin architecture. It provides a rich set of re-usable interface controls, not to mention the Language Server Protocol and number of LSP plugins already implemented.</p><p>For creating a boilerplate of this plugin I used the <a href="https://yeoman.io/">Yeoman</a> and <a href="https://www.npmjs.com/package/generator-code">VS Code Extension Generator</a> that are being discussed <a href="https://code.visualstudio.com/api/get-started/your-first-extension">here</a>. I used Langchain’s nodejs version for handling the tasks around the prompt preparation, execution and parsing. For tracing I used Langsmith, as usual.</p><p>My current model of choice is Claude 3 as I have a lot of trust in it’s capability in handling long and complicated prompts <a href="https://medium.com/@ishish222/revolutionizing-risk-assessment-part-3-initial-prompt-and-tracing-eb103ad9042a">provided that the prompt itself is well structured</a>. I encountered contracts that I had trouble with while using ChatGPT4 but Claude 3 handled them perfectly.</p><p>Side note: I started using a <a href="https://github.com/ishish222/mentat/blob/main/src/openrouter.ts">wrapper</a> for <a href="https://openrouter.ai/">OpenRouter</a> to be able to switch between the models and test and compare their performance.</p><p>The ancient predecessor of my WebviewViewProvider extension is the <a href="https://github.com/barnesoir/chatgpt-vscode-plugin">vscode-chatgpt-plugin</a>. I make use of vscode.TreeDataProvider tamplate to implement the snippet tree.</p><h4>The process</h4><p>Ok so the first step is flattening the contract. In Solidity there‘s a practice of implementing one contract in one source code file, it’s not enforced AFAIK but to keep things simple let’s start with a single file.</p><pre>async function flatten(<br> document: vscode.TextDocument,<br>): Promise&lt;string | void&gt; {<br> const ws = new workspace.Workspace();<br> const current_document = document;<br><br> if (current_document) {<br>  try {<br>   await ws.add(current_document.uri.fsPath, { content: current_document.getText() });<br>   await ws.withParserReady();<br>   <br>   let sourceUnit = ws.get(current_document.uri.fsPath);<br>   if (!sourceUnit) {<br>    console.error(`ERROR: could not find parsed sourceUnit for file ${current_document.uri.fsPath}`)<br>    return undefined;<br>   }<br>   let flat = sourceUnit.flatten();<br>   console.log(&#39;Flattened source unit:&#39;); <br>   return flat;<br>  }<br>  catch (error) {<br>   console.error(`Error adding file to the workspace: ${error}`);<br>  }<br> }<br> else<br>  console.error(&#39;No active document found.&#39;);<br>}</pre><p>We process the with the solidity-workspace library and generate the flattened version of the contract(s) that include all inherited contracts that the library retrieves from different parts of the repo (forgot to mention, we need to have dependencies installed!).</p><p>Then we prepare the xml-formatted prompt for the model, fill out the parameters and submit to the model.</p><pre>let parse_flattened_system_xml_str = `<br>You are an expert in the field of Solidity contract development. You are tasked with analyzing a flattened contract. <br>You need to examine the contract and break it down into a map of its components. The components are:<br>- contracts<br>- state variables<br>- functions<br>- events<br>- modifiers<br>- types<br><br>These components are the building blocks of a Solidity contract. They are related to each other with &#39;needs&#39; relationships.<br>A component &#39;A&#39; needs another components &#39;B&#39; if understanding &#39;B&#39; is necessary to understand &#39;A&#39;.<br><br>You are given a code containing a flattened contract and you are expected to break it down into its components. Note: we need <br>all contracts mapped. <br><br>We need the response to be parsable as XML so we can&#39;t have any additional chatter in the response. If you want to comment, <br>fit it into the XML format.<br><br>Example execution:<br><br>&lt;examples&gt;<br>&lt;example num=&quot;1&quot;&gt;<br>${example_1_xml}<br>&lt;/example&gt;<br>&lt;/examples&gt;<br><br>Please follow these thinking steps:<br><br>&lt;thinking_steps&gt;<br>    &lt;step num=&quot;1&quot;&gt;Take a deep breath and focus&lt;/step&gt;<br>    &lt;step num=&quot;2&quot;&gt;Read the code carefully&lt;/step&gt;<br>    &lt;step num=&quot;3&quot;&gt;Identify the components&lt;/step&gt;<br>    &lt;step num=&quot;4&quot;&gt;Map the components&lt;/step&gt;<br>    &lt;step num=&quot;5&quot;&gt;Return the map in the requested format&lt;/step&gt;<br>&lt;/thinking_steps&gt;<br><br>Please return the component map in the following format:<br><br>&lt;output_format&gt;<br>\`\`\`<br>&lt;response&gt;<br>    &lt;thinking&gt;<br>        &lt;step num=&quot;1&quot;&gt;Thinking step 1&lt;/step&gt;<br>        &lt;step num=&quot;2&quot;&gt;Thinking step 2&lt;/step&gt;<br>        &lt;step num=&quot;3&quot;&gt;Thinking step 3&lt;/step&gt;<br>        &lt;step num=&quot;4&quot;&gt;Thinking step 4&lt;/step&gt;<br>        &lt;step num=&quot;5&quot;&gt;Thinking step 5&lt;/step&gt;<br>    &lt;/thinking&gt;<br>    &lt;components&gt;<br>        &lt;component&gt;<br>            &lt;name&gt;Name of component 1&lt;/name&gt;<br>            &lt;type&gt;Type of component 1&lt;/type&gt;<br>            &lt;needs&gt;<br>                &lt;need&gt;Name of needed component 1&lt;/need&gt;<br>                &lt;need&gt;Name of needed component 2&lt;/need&gt;<br>                // additional needs<br>            &lt;/needs&gt;<br>        &lt;/component&gt;<br>        &lt;component&gt;<br>            &lt;name&gt;Name of component 2&lt;/name&gt;<br>            &lt;type&gt;Type of component 2&lt;/type&gt;<br>            &lt;needs&gt;<br>                &lt;need&gt;Name of needed component 1&lt;/need&gt;<br>                &lt;need&gt;Name of needed component 2&lt;/need&gt;<br>                // additional needs<br>            &lt;/needs&gt;<br>        &lt;/component&gt;<br>        ... // continued list of components<br>    &lt;/components&gt;<br>&lt;/response&gt;<br>\`\`\`<br>&lt;/output_format&gt;<br>`;</pre><p>Once we retrieve the tree and convert it to the vscode.TreeDataProvider we can explore the structure and select components for explanation. With requesting the explanations of code snippets or objects it’s easier, we need to provide the model with similar prompt containing the flattened contract, the component in question and explanation of any “understanding dependencies”.</p><h4>Summary</h4><p>And that’s it for now folks! Hope that this post was interesting to you. Feel free to share your feedback and thoughts. In the meantime I’ll keep expanding the project (e.g. cache is a must have here!) and probably come up with some application ideas in the meantime. Currently I am thinking about adding LLM-based evaluation of MEV potential or simply looking for vulnerabilities that are not low-hanging fruits (business logic errors).</p><p>OR maybe it will teach me how to write better formatted code? :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4343b5c637dc" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/code-mentat-code-analysis-w-claude-3-4343b5c637dc">Code Mentat — code analysis w/ Claude 3</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Revolutionizing Risk Assessment — Part 3: Initial prompt and tracing]]></title>
            <link>https://medium.com/@ishish222/revolutionizing-risk-assessment-part-3-initial-prompt-and-tracing-eb103ad9042a?source=rss-28d477675631------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb103ad9042a</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[it-security]]></category>
            <category><![CDATA[risk-assessment]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[claude]]></category>
            <dc:creator><![CDATA[Tomasz Salacinski]]></dc:creator>
            <pubDate>Fri, 29 Mar 2024 20:49:06 GMT</pubDate>
            <atom:updated>2024-04-14T16:59:36.086Z</atom:updated>
            <content:encoded><![CDATA[<h3>Revolutionizing Risk Assessment — Part 3: Tracing and initial prompt engineering</h3><p>In the <a href="https://medium.com/@ishish222/revolutionizing-risk-assessment-part-2-boilerplate-application-5df41609bd39">previous episode</a> we created an interface and the context for interacting with the Claude 2.x LLM via AWS Bedrock. We performed an initial interaction with the model in order to create a joke about Julius Caesar. In the following episode we will create and refine the prompt for building the actual risk register.</p><p>You can find the code discussed in this episode here: <a href="https://github.com/ishish222/llm-risk-assessment">https://github.com/ishish222/llm-risk-assessment</a> (v.0.1.0)</p><p>We will start working with minimal versions of the Asset Inventory and Risk Scenario Register shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4TnX2M34aJrJtNgPdAGCuQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EvDuNLfueFaBl3hqvX-lJQ.png" /></figure><p>Go ahead and create these examples in Google Sheets or similar application and export them as CSV or use the CSV content below:</p><pre>asset_name,business_impact,description<br>Web Server Infrastructure,3,&quot;Hosts the company’s web application, serving as the primary point of interaction with users. Critical for service availability and directly impacts revenue and customer trust.&quot;<br>Customer Database,3,&quot;Contains sensitive customer information including personal data, payment details, and transaction history. Its integrity, confidentiality, and availability are paramount for compliance, trust, and operational continuity.&quot;<br>Logging and Monitoring Systems,2,&quot;Collects and analyzes logs from various systems for monitoring performance, detecting anomalies, and facilitating incident response. Critical for operational awareness and security.&quot;<br>Development and Testing Environments,1,Used by the development team for building and testing new features and updates before they are deployed to the production environment. Important for maintaining the pace of innovation while ensuring application stability and security.</pre><pre>risk_scenario_name,likelihood,description<br>DDoS Attack on Service Infrastructure,2,&quot;An attacker targets the company&#39;s service infrastructure with a Distributed Denial of Service (DDoS) attack, overwhelming the servers with traffic and making the service unavailable to legitimate users.&quot;<br>Data Breach Through Phishing Attack,3,An attacker successfully deceives an employee into revealing their credentials through a phishing email. The attacker gains unauthorized access to sensitive data stored on the company’s network.<br>Ransomware Infection,2,&quot;Malicious software encrypts critical data and systems, rendering them unusable. The attacker demands a ransom payment for the decryption key. This scenario can disrupt operations and lead to data loss if backups are also compromised.&quot;<br>Third-Party Service Failure,3,&quot;A critical third-party service provider experiences a failure or security breach, impacting the company’s ability to offer its digital service, either through direct service disruption or through a breach of data shared with the third party.&quot;</pre><p>Now, we want Claude to connect assets to scenarios and evaluate the risk according to a quantitative formula:</p><p>Risk = Business Impact + Likelihood</p><p>The resulting table should contain a list of risks. Let’s start with the following prompt:</p><pre>human_str = &quot;&quot;&quot;<br>Please connect the following assets:<br>{assets}<br>to the following scenarios:<br>{scenarios}<br>Please only connect scenarios that are relevant to the assets.<br>Please calculate the risk score for each connection based on formula: <br>Risk = Probability + Impact<br>Please output the result in the following format:<br>&lt;risks&gt;<br>  &lt;risk num=1&gt;<br>    &lt;asset&gt;Sample asset 1&lt;/asset&gt;<br>    &lt;scenario&gt;Sample scenario 1&lt;/scenario&gt;<br>    &lt;risk_score&gt;3&lt;/risk_score&gt;<br>  &lt;/risk&gt;<br>    &lt;asset&gt;Sample asset 2&lt;/asset&gt;<br>    &lt;scenario&gt;Sample scenario 2&lt;/scenario&gt;<br>    &lt;risk_score&gt;4&lt;/risk_score&gt;<br>  &lt;risk num=2&gt;<br>  &lt;/risk&gt;<br>    &lt;asset&gt;Sample asset 3&lt;/asset&gt;<br>    &lt;scenario&gt;Sample scenario 3&lt;/scenario&gt;<br>    &lt;risk_score&gt;1&lt;/risk_score&gt;<br>  &lt;risk num=3&gt;<br>  &lt;/risk&gt;<br>  ... // more risks<br>&lt;/risks&gt;<br>&quot;&quot;&quot;<br><br>prompt = ChatPromptTemplate.from_messages([<br>  (&quot;human&quot;, human_str)<br>  ])<br><br>chain = (prompt | llm | parser)<br>output = chain.invoke({<br>  &#39;assets&#39; : assets.to_xml(root_name=&#39;Assets&#39;, row_name=&#39;Asset&#39;), <br>  &#39;scenarios&#39; : scenarios.to_xml(root_name=&#39;Scenarios&#39;, row_name=&#39;Scenario&#39;)<br>  })</pre><p>When we execute the prompt by pressing the “Create Risk Register” button we get the following error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yDnUzuX3RL2ec44sQ25hCA.png" /></figure><p>In order to understand what went wrong it would be helpful to examine the interaction in Langchain. Let’s create a project, generate an API key and add necessary environment variables to the .env file (and properly export them, of course).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*KYEMemWdAm2xfU5ky9wIew.png" /></figure><p>After we execute the chain again we can now see access and explore recorded traces coming in the Langchain project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Njl1o5r0BtMzBJ8XNae7sg.png" /></figure><p>We can see that there is a problem with parsing the output by the XMLOutputParser. Let’s examine the Chat interaction to inspect verbatim representation of inputs and outputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N4wZ4S5nmkzGz3Q43UAI0w.png" /></figure><p>As you can see, Claude is returning the requested output but my guess is that the xml declaration on top of the model’s response is stopping the XML parser from properly parsing it back into a python object. Why is Claude adding this even if we didn’t ask it to? Due to lack of more specific examples, it’s following the pattern established by provided inputs that too include the xml declaration.</p><p>Let’s adjust:</p><pre>chain = (prompt | llm | parser)<br>output = chain.invoke({<br>  &#39;assets&#39; : assets.to_xml(root_name=&#39;Assets&#39;, row_name=&#39;Asset&#39;, xml_declaration=False), <br>  &#39;scenarios&#39; : scenarios.to_xml(root_name=&#39;Scenarios&#39;, row_name=&#39;Scenario&#39;, xml_declaration=False)<br>  })</pre><p>Then we’ll flatten the output to be able to use it for output DataFrame construction:</p><pre>flattened_data = []<br>for item in output[&#39;risks&#39;]:<br>    flattened_dict = {}<br>    for entry in item[&#39;risk&#39;]:<br>        flattened_dict.update(entry)<br>    flattened_data.append(flattened_dict)<br><br>return pd.DataFrame(flattened_data) </pre><p>Now with the sample inputs we get an example output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HIdI9nsXzan5OS-r16R_Hw.png" /></figure><p>Let’s verify if the values are following our requested formula:</p><p>Risk 1: 3 + 2 = 5 (correct)<br>Risk 2: 3 + 3 = 6 (correct)<br>Risk 3: 3 + 2 = 5 (correct)<br>Risk 4: 3 + 2 = 5 (correct)<br><strong>Risk 5: 3 + 3 = 5 (incorrect)</strong><br>Risk 6: 3 + 3 = 6 (correct)</p><p>So, what went wrong?</p><p>The answer is, while adding two natural numbers is easy for any traditional algorithm, it’s difficult for the LLM. Let’s remember what LLM is: a huge neural network which primary task at any step of text generation to calculate the most probable next token. This is far from efficient method for mathematical calculations.</p><p>We can solve this problem in a number of ways, e.g.:</p><ol><li>just have the LLM connect the assets with scenarios, calculate estimation separately with traditional algorithm</li><li>use LLM function calling technique for calculations</li><li>apply prompt engineering techniques to break down complex task into a number of smaller, easier ones</li></ol><p>We will focus on the last option for now. It might not provide an immediate solution to the issue but it will allow us exercise some techniques for improving the prompt engineering.</p><h4>Improving by applying prompt engineering techniques</h4><p>Let’s go back to the general recommended prompt structure for Claude 2.x that was already mentioned in part 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CNMJfdiBVAvuFHMkRXluSQ.png" /></figure><p>This is a part of a wider guide for prompt engineering for Claude 2.0. As I mentioned, in version 2.1 <a href="https://docs.anthropic.com/claude/docs/system-prompts">system</a> messages have been introduced. Quote: “A system prompt is a way to provide context, instructions, and guidelines to Claude before presenting it with a question or task”. This means that we should move everything except the conversation history and an immediate task description or request from the Human message into the System message.</p><p>Let’s start with task context, tone, background data, detailed task description and rules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SESu4BvyDGztSATGMKzomQ.png" /></figure><p>As you can see, I’ve left a placeholder for any additional rules that I might want to adjust later, at the application level by passing one additional prompt parameter.</p><p>Next, we’ll move on to describing the general context of the task at hand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NsiP8YyHPC4EJ_ndYgdelA.png" /></figure><p>As you can see, I mentioned examples but I left them out for now. This part requires a brief comment.</p><h4>In-context examples and their significance</h4><p>LLMs come in two general flavours: pre-trained and fine-tuned. Pre-trained models are being trained on a large body of available text in order to arrive at weights that allow them to “understand” the meaning of natural language input and to perform general language-related tasks such as:</p><ul><li>classifying text</li><li>generating new text that corresponds to the input</li><li>filling-out missing (masked) parts of the text</li><li>etc.</li></ul><p>Up to a certain point in the history of LLM (I’d say to the publication of the GPT-2 paper) these pre-trained models needed to be fine-tuned for specific tasks. That meant that we needed to prepare training data (example inputs and outputs of a specialised task) and then fine-tune the model to adjust the weights for the model to perform well in this specific field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eeIRpmWhLKZVD6RvhUzxcg.png" /></figure><p>But then:</p><p>“It wasn’t until the GPT-2 and GPT-3 papers that we realized a GPT model pre-trained on enough data with enough parameters was capable of performing any arbitrary task by itself, no fine-tuning needed.</p><p>Just prompt the model, perform autoregressive language modeling, and like voila, the model magically gives us an appropriate response. This is referred to as <strong>in-context learning</strong>, because the model is using just the context of the prompt to perform the task. In-context learning can be zero shot, one shot, or few shot.” (<a href="https://jaykmody.com/blog/gpt-from-scratch/">source</a>)</p><p>This means, if we give the model enough to go on in terms of in-context examples, we can achieve high quality output in specialised tasks without fine-tuning.</p><p>The question now is how many examples do we need and how we should organize them. In my experience, one or two in-context examples can significantly improve output quality in complex tasks.</p><p>In terms of organisation, here’s my approach. The best results I achieved by including in the System message examples of the Human — Assistant message pairs. This means unfortunately that the prompt will become somewhat convoluted. First, we’ll be providing in-context examples (Human-Assistant pairs), then we’ll be adding information on expected output schema, then we’ll be providing immediate input in the Human message… That’s a lot, especially if e.g. we need to include a lot of text in examples (e.g., 50+ page SOC 2 reports). That’s why it’s good to stick to the suggested high-level prompt structure for specific model and use XML tagging.</p><p>Let’s leave the examples field for now until we have general structure of the Human-Assistant interaction figured out, then we’ll “flesh it out”.</p><h4>Thinking steps and expected output schema</h4><p>I usually include the thinking steps and the definition of expected output schema into the System message as well.</p><p>In various prompt engineering tutorials you might often encounter recommendations to “give the model space to think”. It might be strange for an engineer to hear this kind of advice from another engineer but, similarly to “tipping” the model, this is one of those natural language processing patterns that initially seem out of place in the engineering field but actually work. “Giving space” is realised by instructing the model to come up with intermediate results by breaking down the complex task into steps and for each step, checking the results against a set of criteria before proceeding to the next step. In designing the thinking steps in a prompt it’s usually helpful to consult human operator that has expertise in the field.</p><p>Initial set of the thinking steps for the task at hand:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BiXxWUoRIg_ph6nsrKq2xA.png" /></figure><p>Now let’s define the output schema.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VqFcc0sid4PODNZ82n-HLg.png" /></figure><p>As you can see, there is space in the output schema for the model to put in their notes about the intermediate steps. Besides improving the quality of output by decomposing the problem we achieve one more thing — we have more control over the model’s chatter.</p><p>Some models (I assume the ones not fine-tuned well to follow instructions) have tendencies to add their chatter before or after the schema no matter how much you beg or threaten them, e.g..</p><blockquote>Assistant:</blockquote><blockquote>Of course, please find the requested schema below:<br>&lt;result&gt;<br>[…]<br>&lt;/result&gt;</blockquote><p>or</p><blockquote>Assistant:</blockquote><blockquote>&lt;result&gt;<br>[…]<br>&lt;/result&gt;<br>With the following results you will be able to proceed with the risk treatment procedure.</blockquote><p>This is rather frustrating when it comes to parsing the natural language output back to the structured data that can be handled by traditional algorithm.</p><p>I noticed that when I add space in the output schema for the model to think the chatter becomes outside the schema is very rare. And of course we can simply discard the chatter if we maintain the control over the schema.</p><h4>Human message</h4><p>All of the components for the System message except in-context examples have been sorted out. Now it’s time for the Human message in which we will include information on the specific task with task parameters that will be set on the application level. We’ll skip the chat history for now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0eqFssmXDh4CuwS7D47C6A.png" /></figure><p>Aaaand that’s it :)</p><p>Let’s wrap it in Langchain’s ChatPromptTemplate and update our chain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7jSHPV91QaRxiMt8DHXlJg.png" /></figure><h4>In-context examples based on Human-Assistant pairs</h4><p>Now we need the in-context examples. But we don’t need to create them ourselves. Let’s have the model create them by simply passing a prompt with the in-context examples temporarily empty and seeing what the model will come up with themselves. Let’s load the sample Asset Inventory and Risk Scenario Register, run the chain and see what results we’ll get.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ijsM8VwwtDzT9Diyweqmg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3AczCFr0beaikHHcZb96eA.png" /></figure><p>Haha OK that’s what I had in mind when I talked about issues with chatter, here before and after the schema :). But we can still extract valuable examples, let’s check out the trace in Langsmith:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rxySWPqu00UAteR4dxP6xQ.png" /></figure><p>This output needs a little adjustment but we can reuse it. First, let’s extract the schema without the chatter. Next, let’s wrap everything in &lt;response&gt; tags.</p><p>We get the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RMLKC5e5mZGMiu9uy7A95g.png" /></figure><p>And the trace:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qy5bhdEpRjpwVL_1BhDapA.png" /></figure><p>The calculations are now correct.</p><h4>Summary</h4><p>In the following episode, we created and executed an initial prompt for risk calculation according to a defined formula based on test data. We encountered a problem with the output parser and diagnosed it using Langsmith tracing function. Then we encountered another problem which is model not being able to execute a simple mathematic operation.</p><p>We improved our prompt using prompt engineering techniques for the Claude 2.x model including:</p><ul><li>using XML tags</li><li>following recommended high-level prompt structure</li><li>using System, Human and Assistant messages</li><li>breaking down the complex task into a simpler one and “giving the model space to think“</li><li>requesting the model to “think aloud”</li></ul><p>In the following episode, we’ll further improve the application by breaking down the single prompt into several smaller, parallel prompts and we’ll turn the model into more autonomic LLM agent that will be able to call functions. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb103ad9042a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Revolutionizing Risk Assessment — Part 2: Boilerplate application]]></title>
            <link>https://medium.com/@ishish222/revolutionizing-risk-assessment-part-2-boilerplate-application-5df41609bd39?source=rss-28d477675631------2</link>
            <guid isPermaLink="false">https://medium.com/p/5df41609bd39</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[risk-assessment]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[it-security]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Tomasz Salacinski]]></dc:creator>
            <pubDate>Fri, 29 Mar 2024 17:21:13 GMT</pubDate>
            <atom:updated>2024-04-14T17:00:00.518Z</atom:updated>
            <content:encoded><![CDATA[<h3>Revolutionizing Risk Assessment with LLMs— Part 2: Boilerplate application</h3><p>In this episode I will be implementing an LLM-based assistant that will support the Risk Manager in performing ISO-27005-based Risk Assessment by automating some of his tasks. The automation will involve natural language processing.</p><p>You can find the code discussed in this episode here: <a href="https://github.com/ishish222/llm-risk-assessment">https://github.com/ishish222/llm-risk-assessment</a> (v.0.1.0)</p><p>The wider context and rationale behind this implementation have been explained in previous episode <a href="https://medium.com/@ishish222/automating-security-tasks-with-llms-revolutionizing-risk-assessment-part-1-the-context-a8407a512663">Revolutionizing Risk Assessment — Part 1: The Context</a>, feel free to check it out. In this episode we’ll be getting out hands dirty and start working with the code.</p><p>The initial version of the application will be dealing with the task of <strong>selecting a subset of matching scenarios for each asset to combine them into risks. </strong>We will need the operator in the loop to supervise the execution of the task and make necessary adjustments, so we also need to account for that.</p><h3>Technology stack</h3><p>I obviously selected components of the technology stack that I am most familiar with but they’re exchangeable. In this episode I will deploy a web application in <strong>python</strong> built on top of the <strong>Gradio</strong> and <strong>Langchain</strong> libraries. We’ll be using AWS as a provider of the Anthropic’s <strong>Claude 2.x</strong> model hosted via <strong>Bedrock</strong> (and an IaaS provider).</p><p>The <a href="https://www.gradio.app/"><strong>Gradio</strong></a> package is a very useful interface builder that allows for re-using implementation of the most popular interface components used when interacting with LLMs. Gradio itself is built on top of <strong>FastAPI</strong>, a popular python package for implementing API interfaces.</p><p>Gradio lives in both worlds: backend and frontend. In the backend it allows us to abstract away the input-output interface components and just implement own methods to execute the transformation of data. In the frontend it generates the actual html content that will be served to the users.</p><p><a href="https://www.langchain.com/"><strong>Langchain</strong></a> is a set of packages that implement some classes and functions that allow for decoupling interfacing with specific LLM APIs and popular components of processing logic such as building prompts out of templates, providing RAG capabilities, LLM output parsing and structuring, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k-stC2IfMNXY6CKmXcZaEw.png" /><figcaption>Example LLM interaction’s trace recorded with Langsmith</figcaption></figure><p>Langchain’s close relative is <a href="https://www.langchain.com/langsmith"><strong>Langsmith</strong></a>, LLM tracing, diagnostic and evaluation service. Langsmith deals with a variety of tasks that are related to analysis of the interactions between the application and the LLM on a message level. It does so by recording selected interactions and their metadata and adding them to a separately maintained dataset.</p><h3>Procedure for automation</h3><p>As the first step of risk assessment automation we will be combining asset information with risk scenario information to form the risk. On the input we will have a list of assets (Asset Inventory) and a list of scenarios (Risk Scenario Register) and on the output we’ll have the Risk Register.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*FrjEwRe3rj8fOexIJNjrxQ.png" /><figcaption>Creating risks — inputs and outputs</figcaption></figure><p>To reiterate, we want to follow the ISO 27005 procedure in which the organisation decides on specific formula for the estimation of the final risk. The formula can be quantitative (e.g., risk estimation (3) = asset sensitivity (2) + scenario likelihood (1)) or qualitative (e.g., risk estimation (medium) = asset sensitivity (medium) + scenario likelihood (low)).</p><p>Where does the LLM part fit into this simple procedure? Why can’t we just do this manually or using traditional algorithm?</p><p>We could do this manually but it’s time consuming. First, we need to decide which combinations even make sense and discard all the remaining ones (e.g. the risk: “database” + “ransomware attack” makes sense while the risk “service continuity” + “phishing targeting customers” does not). Then, we need to calculate the estimation. If we have 20 items in Asset Inventory and 20 items in the Risk Scenario Register there are potentially 400 combinations that the operator needs to go through. And if risk re-assessment should be done e.g. every time new function is being considered for a product / service it can become a quite daunting task that would take the operator’s time out of the actual security operations.</p><p>We could try to automate it with traditional algorithm, up to a point. The estimation is a simple task of looking up appropriate value in the matrix, but combining the risk components and filtering out those which don’t make sense strongly relies on:</p><ul><li>IT security expertise</li><li>Description of assets and risk scenarios represented in the natural language</li></ul><h3>The interface</h3><p>Based on the procedure we defined we know what inputs and outputs we will be dealing with. Based on this we can define the initial version of the gradio interface:</p><pre>import gradio as gr<br><br>with gr.Blocks() as app:<br>  with gr.Row():<br>    with gr.Accordion(open=False, label=&#39;Assets&#39;):<br>      with gr.Row():<br>        rr_input_r_assets_f = gr.File(file_types=[&#39;.csv&#39;, &#39;.xlsx&#39;, &#39;.xls&#39;])<br>      with gr.Row():<br>        rr_input_r_assets_load_btn = gr.Button(&#39;Load assets (CSV)&#39;)<br>      with gr.Row():<br>        rr_input_r_assets_inv = gr.Dataframe(label=&#39;Asset Inventory&#39;)<br>  with gr.Row():<br>    with gr.Accordion(open=False, label=&#39;Risk Scenarios&#39;):<br>      with gr.Row():<br>        rr_input_r_scenarios_f = gr.File(file_types=[&#39;.csv&#39;, &#39;.xlsx&#39;, &#39;.xls&#39;])<br>      with gr.Row():<br>        rr_input_r_scenarios_load_btn = gr.Button(&#39;Load scenarios (CSV)&#39;)<br>      with gr.Row():<br>        rr_input_r_scenarios_reg = gr.Dataframe(label=&#39;Risk Scenarios Register&#39;)<br>  with gr.Row():<br>    rr_create_btn = gr.Button(&#39;Create Risk Register&#39;)<br>  with gr.Row():<br>    rr_create_log = gr.Text(label=&#39;Creation log&#39;)<br>  with gr.Row():<br>    rr_output = gr.Dataframe(label=&#39;Generated Risk Register&#39;)<br>      <br>server_name=&#39;0.0.0.0&#39;, server_port=8080</pre><p>After running the application and navigating to 127.0.0.1:8080 with the web browser we should see the following interface:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FkCRU4DbH2SlNXVF8Bq_0w.png" /></figure><p>The Assets and Risk Scenarios inner content:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UmEyN-S9Bnfveimi_yXC_Q.png" /></figure><p>The DataFrame objects will be populated with the content of the CSV documents what the user chooses to load. Now we need to service the loading buttons:</p><pre>import pandas as pd<br><br>def load_csv_data(<br>        input_file: str<br>    ) -&gt; gr.Dataframe:<br>    input_file = input_file.name<br>    print(f&#39;Opening CSV: {input_file}&#39;)<br>    df = pd.read_csv(input_file)<br>    return df<br><br>with gr.Blocks() as app:<br>  # interface definition<br><br>  rr_input_r_assets_load_btn.click(fn=load_csv_data, inputs=[rr_input_r_assets_f], outputs=[rr_input_r_assets_inv])</pre><p>We can reuse the <em>load_csv_data</em> function for loading the risk scenarios as well. The output gr.DataFrame object will assume a shape dictated by the contents of the input file. The only requirement it’s of rectangular shape, i.e. all of the rows have the same number of elements.</p><p>To service the generation button clicks we’ll add the following:</p><pre>import pandas as pd<br><br>def generate_rr(<br>        assets: pd.DataFrame,<br>        scenarios: pd.DataFrame<br>    ) -&gt; gr.Dataframe:<br>    print(&#39;Generating Risk Register&#39;)<br>    # interacting with Claude LLM<br><br>    return pd.DataFrame() <br><br>with gr.Blocks() as app:<br>  # interface definition<br><br>  rr_create_btn.click(fn=generate_rr, inputs=[rr_input_r_assets_inv, rr_input_r_scenarios_reg], outputs=[rr_output])</pre><p>This will serve as a context in which we will be interacting with the LLM to produce the actual risks.</p><h3>LLM interaction</h3><p>Since I decided to use AWS as IaaS provider to simplify the deployment I’ll be using Claude LLM served via Bedrock. Of course Claude is only one of tens of available models so we can exchange it for any other in order to test the produced output and maybe evaluate it and compare it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lld9CNxpioZGO_wOQmvsCA.png" /><figcaption>This is Claude 2.x</figcaption></figure><p>In order to be able to re-use a wide variety of clasess for buildind LLM applications we’ll interact with the model through the Langchain’s chain. The <strong>chain</strong> in Langchain refers to any number of special objects called <strong>runnables</strong> that are chained together so that the output from one runnable is being passed on to the second runnable.</p><p>In langchain we have runnables ready to use for creating LLM prompts, wrapping the LLM endpoints and parsing the LLM outputs. For our purpose we’ll be using a chain:</p><pre>chain = ( prompt | llm | parser)</pre><p>Where:</p><ul><li><em>prompt</em> represents the request that we’ll be sending out to Claude</li><li><em>llm</em> represents the Claude’s endpoint</li><li><em>parser</em> represents the output parser of content that is being generated by Claude in an attempt to structure the natural-language response back to a form that can be parsed with traditional algorithm</li></ul><p>Preparing the <em>llm</em> and the <em>parser</em> is quite straightforward:</p><pre>from langchain_community.chat_models import BedrockChat<br><br>LLM_TEMPERATURE = 0.0<br>LLM_MODEL_ID = &#39;anthropic.claude-v2&#39;<br><br>session = boto3.Session()<br>bedrock = session.client(&#39;bedrock-runtime&#39;)<br><br>llm = BedrockChat(<br>        model_id = LLM_MODEL_ID, <br>        client = boto3_bedrock, <br>        model_kwargs = {<br>          &quot;temperature&quot;: LLM_TEMPERATURE<br>        }<br>      )</pre><p>We need to establish a session to AWS bedrock-runtime service using pre-defined user or role and within this service we’ll create a session with specific model which is in our case Anthropic’s Claude 2.1. The <em>temperature</em> parameter is one of the parameters used to adjust the generation process to control the “creativeness” of the model. To simplify, it allows us to decide the diversity of generated tokens of output in context of their probabilities. Higher temperature allows creating more “creative” outputs with unlikely tokens being included but if we are after precision we set the temperature to 0.0 which means that we want only the most probable tokens to be included in the output.</p><p>For the output parser we’ll use XMLOutputParser():</p><pre>from langchain_core.output_parsers.xml import XMLOutputParser<br><br>parser = XMLOutputParser()</pre><p>The choice of the parser requires a bit of explanation which warrants a separate section.</p><h3>Significance of model training for prompt engineering</h3><p>The process of training an LLM is very important if we want to improve its generated output through prompt engineering. But what is prompt engineering? Prompt engineering is a process of refining the prompt that is being fed to the LLM model as an input tokens sequence in order for it to produce improved output sequence. This is an iterative process that sometimes involves techniques from a weird area that borders engineering and psychology.</p><p>A trivial example of iterative improvement improvement of the prompt can be progressing from the prompt:</p><p><em>“Please tell me a joke about Julius Caesar.”</em></p><p>to:</p><p><em>“Please tell me a joke about Julius Caesar. If I laugh, I’ll give you a 10% tip.”</em></p><p>Believe it or not, but there is <a href="https://arxiv.org/abs/2312.16171">research</a> that suggests that you can improve the quality of output by including this sequence of tokens. This is due to the fact that the training material used for building the model was originally produced by a human and humans often perform better when offered rewards. The output produced by the model is determined by the training material. That’s why it’s important to make sure that:</p><ul><li>Training date of the model used is later than the knowledge required for executing tasks has been published</li><li>There is high likelihood that the material used for training included the body of knowledge required to properly execute the task</li></ul><p>So for example in our case it might be sufficient that the training took place after publishing the version 2022 of the ISO 27005 standard and there is enough training material related to the standard that it’s very likely it has been included in the training. But this might not be the case with topics related to emerging technologies such as e.g. Zero Knowledge Proofs which witnessed a dynamic evolution in recent years or, Large Language Models themselves.</p><p>Another example of the evolution in the training process might be breaking down the continuous text into quasi-chat messages such as:</p><p><em>Human: Please tell me a joke about Julius Caesar.</em></p><p><em>Assistant: Why did Julius Caesar buy crayons? Because he wanted to Mark Antony!</em></p><p>This is a case of an evolution of the Claude model which started offering the <em>System</em> role in chat-like prompts since version 2.1.</p><p>There is number of other examples of training decisions that affect output such as constitutional training, languages used, etc. but for the purpose of this article I only need to mention two:</p><ul><li>overall prompt structure</li><li>Using XML</li></ul><h4>Prompt structure for Claude 2.x</h4><p>Claude performs better when the input prompt is formulated in XML and it follows an overall structure presented in this image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CNMJfdiBVAvuFHMkRXluSQ.png" /></figure><p>These structure requirements might soon become obsolete (they should already be altered after Claude 2.1 premiere) as Claude itself evolves very fast. I present it here as an example that sometimes it’s required to understand the training process to improve prompt engineering for a specific model and that two different models might have two different “optimal” prompt organisation.</p><p>Now we’re ready to deal with the prompt engineering, but I’ll delve into this process in the next episode. For now, let’s start with a simple prompt:</p><pre>def generate_rr(<br>        assets: pd.DataFrame,<br>        scenarios: pd.DataFrame<br>    ) -&gt; gr.Dataframe:<br>    parser = XMLOutputParser()<br><br>    session = boto3.Session()<br>    bedrock = session.client(&#39;bedrock-runtime&#39;)<br><br>    llm = BedrockChat(<br>            model_id = LLM_MODEL_ID, <br>            client = bedrock, <br>            model_kwargs = {<br>              &quot;temperature&quot;: LLM_TEMPERATURE<br>            }<br>          )<br><br>    prompt = ChatPromptTemplate.from_messages([<br>      (&quot;human&quot;, &#39;Please tell me a joke about {person}&#39;)<br>      ])<br><br>    chain = (prompt | llm )<br>    output = chain.invoke({&#39;person&#39; : &#39;Julius Caesar&#39;})<br><br>    return pd.DataFrame({&#39;joke&#39; : [output.content]})</pre><p>That will give us the following output in the interface:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Jriq8H8JukBcdFA7EZL7A.png" /></figure><h3>Summary</h3><p>In this episode we created the boilerplate code for gradio-based application and, defined inputs and outputs of the LLM interaction and introduced some context that will be useful in our prompt engineering work.</p><p>In the <a href="https://medium.com/@ishish222/revolutionizing-risk-assessment-part-3-initial-prompt-and-tracing-eb103ad9042a">next episode</a> we will start working with Anthropic’s Claude 2.x models and we’ll lay foundation for prompt engineering for this model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5df41609bd39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Security Tasks with LLMs: Revolutionizing Risk Assessment — Part 1: The Context]]></title>
            <link>https://medium.com/@ishish222/automating-security-tasks-with-llms-revolutionizing-risk-assessment-part-1-the-context-a8407a512663?source=rss-28d477675631------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8407a512663</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[iso27701]]></category>
            <category><![CDATA[it-security]]></category>
            <category><![CDATA[risk-management]]></category>
            <category><![CDATA[mi]]></category>
            <dc:creator><![CDATA[Tomasz Salacinski]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 12:45:56 GMT</pubDate>
            <atom:updated>2024-04-07T22:16:42.449Z</atom:updated>
            <content:encoded><![CDATA[<h3>Revolutionizing Risk Assessment with LLMs — Part 1: The Context</h3><p>This is the first episode in series. If you want to go straight to implementation, please go to: <a href="https://medium.com/@ishish222/revolutionizing-risk-assessment-part-2-boilerplate-application-5df41609bd39">Revolutionizing Risk Assessment — Part 2: Boilerplate application</a>.</p><p>Probably everyone who worked on securing an organisation has realised that its entirely different type of work to securing a single device or application. It’s not an isolated case of reversing a piece of malware or hunting for a crack in the attack surface. It’s also not as exciting for a security geek who finds pleasure in challenging themself. That’s because they need to assume the perspective of an organisation and the management aspect of their works starts to take priority, effectively leaving less space for any kind of cyberpunk romance.</p><p>From the organisation’s POV their work needs to be retained and usable by others. It needs to be documented, preferably in a form of processes that allows assigning responsibility and authority to designated roles. It needs to become prioritised with regards to goals, measurable, auditable, easy to communicate, etc.. There is a reason for the “Management” in Information Security Management System.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*44WclOMI9CAcC3ZplU2uxA.png" /></figure><p>Unfortunately for us security geeks all of these tasks, while simple, come in overwhelming volumes. Soon it seems that we’re swamped by mundane tasks that are way below our skill levels. While this work is necessary and valuable, we soon start feeling like a cog in a machine. Disconnected from the goals, our work philosophy. Dreaming about violently bringing down the system that we ourselves established in some peculiar revolution. Well, let’s make this revolution a constructive one!</p><h3>Automation to the rescue</h3><p>Thankfully, repeatable tasks can to a large extent be automated and transformed into programmatic tasks. We can generalise over repeatable work and come up with inventive projects and implementations. However, before LLMs it was only up to a point where we deal with structured data. There was no viable solution for dealing with natural language. That meant that we still needed e.g. to go over all these vendor risk management forms and SOC2 reports and manually verify if they fulfil our requirements. Well not anymore!</p><p>Recent development in capabilities and capacities of LLMs allow us now to take course into uncharted territory of automating natural language-related tasks. Of course it has its risks and costs but it offers an incredible opportunity to transform repeatable, mind-numbing work into creative and engaging one.</p><p>In this series of articles I am planning to share my experiences with doing exactly that — bringing back the magic into ISO’s work with the use of LLMs. I will be exploring several different use-cases while building on the recent developments in the AI and IT security areas. Right now I think I will be navigating the landscape with an ISO 27001 map (because this is a standard that I am most familiar with) but I’m certain that these ideas are applicable in other standards and norms that you guys encounter.</p><p>In this series we’ll deal with something relatively easy but central to the organisational ISMS — the Risk Management and Risk Assessment processes and procedures (OMG I’m actually habitually writing it with capital letters).</p><h3>Risk Management Process</h3><p>Why do we need Risk Management in the first place? It helps us answering and justifying the answers to important questions from the perspective of an organisation:</p><ul><li>Why do we spend resources on A and not on B?</li><li>What is the severity of the incident that has materialised?</li><li>What is the risk introduced by this specific vulnerability that we discovered?</li><li>Why do we need / why we don’t need this specific security control deployed?</li></ul><p>Without RM we rely on our experience and intuition (which I like to imagine as experience distilled and trickling from my cortex into my lizard brain) which are often good advisors. But they can mislead us in more than one way:</p><ul><li>We can get involved with details of a specific area (e.g., vulnerabilities in the attack surface) while losing sight of the big picture and other issues within it (e.g. inside threats or unintended damage scenarios)</li><li>We can have hard time justifying our decisions to the auditor, the management or even to our colleagues</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7RbHUnRUTnr3f5JbrWdu1w.png" /></figure><p>RM, in addition to being an excellent foundation for a number of security-related processes, allows us to reassure ourselves and others in following a specific direction. It will always be imperfect and a compromise and will always leave some things unattended due to resources being limited, but we need to be sure it’s the right way to move forward swiftly. It allows us to understand the Why of stuff.</p><h4>My take on a ISO 27005-based Risk Assessment</h4><p>Please note two things.</p><ul><li>I didn’t write “compliant” :). It‘s very strong word that carries too much meaning for the purpose of this series.</li><li>I am focusing on the assessment part, so we are leaving stuff like Risk Treatment Plan budgeting or implementation out for now.</li></ul><p>I referred to ISO 27005 in order to highlight one aspect that I think is different between ISO 27005 and SOC2 approach. I am no seasoned SOC2 expert but I noticed that often in context of the SOC2 the risk is defined as an independent unit, without a connection to company’s assets. For example, the risk:</p><blockquote>Hacker exploits a vulnerability in a web application and exfiltrates the database</blockquote><p>is being constructed without referring to the organisation’s Asset Inventory. We simply assign an estimation to it, e.g. “4/5”, “High”, etc.</p><p>In contrast to this in ISO 27005 we are combining an asset and a risk scenario to define a risk:</p><blockquote>Database + Exploitation of vulnerability in a web application = Hacker exploits a vulnerability in a web application and exfiltrates the database</blockquote><p>In this case the risk is defined based on the asset registered within Asset Inventory (database) and a risk scenario (hacker exploits vulnerability). Assigned <strong>risk estimation</strong> should be calculated based on <strong>asset sensitivity</strong> and the <strong>scenario likelihood</strong> with a formula that organisation chooses for itself. So assigned value could be e.g. “2+2 = 4”.</p><p>This might seem like a detail but actually it might have far reaching consequences to remaining areas of the ISMS. If we disconnect the risk estimation from asset sensitivity, we lose information that can be re-used in other processes. For example, if we are responding to an incident and we are estimating its criticality, we are not interested in the likelihood of scenario occurring because, well, it already occurred. What we can use in this situation to clearly determine the severity and decide wether to escalate or not is actually to consider affected assets and their sensitivity. If they are non-critical, we might decide not to escalate and vice-versa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H98-TD2GsrwE5PLTTYFAvQ.png" /></figure><p>For example, to further reccomend the ISO 27005 approach, in my work I have been re-using information about asset sensitivity in processes such as:</p><ul><li>security reviews of designs / architecture of new features</li><li>security reviews of deployments</li><li>estimating risks of vulnerabilities</li><li>estimating severity of incidents</li><li>prioritising business continuity-related work</li><li>defining asset handling / asset access procedures</li><li>assigning Asset Owners that hold certain responsibilities and authorities in the security context</li><li>etc.</li></ul><p>So, having this information available and not lost during the Risk Assessment execution allowed me to re-use the work and save time for reinventing other processes from scratch.</p><h4>Procedure before automation</h4><p>To simplify, I will consider the following “manual” procedure for risk assessment:</p><ol><li>Identify assets</li><li>Estimate asset sensitivity based on business strategy</li><li>Identify scenarios</li><li>Estimate scenarios’ likelihood based on available intel</li><li>Combine selected assets and scenarios and calculate risk estimations according to simple formula</li><li>Assign security controls to mitigate the inherent risks so that the residual risks are within acceptable threshold</li></ol><p>There is potential for LLM-backed automation in all of these steps but we’ll start with step 5.</p><p>As the inputs of step 5 we have:</p><ul><li>asset inventory with assigned sensitivity</li><li>risk scenarios register with assigned likelihood</li><li>formula for calculating risk inherent estimation</li></ul><p>As the output of step 5 we have:</p><ul><li>a list of risks (combinations of assets and scenarios) with assigned estimations</li></ul><p>The difficulty in here is to end up with a <strong>manageable</strong> risk register. It’s obviously difficult to theoretically decide when the risk register becomes unmanageable in an organisation but in practice it’s rather easy to see :).</p><p>For me (not doing RM full-time, need to deal with other costly processes such as vuln. management, incident mgmt. security reviews, etc.) this means that it has <strong>less than 100 risks</strong> and it still captures the overall risk situation of the organisation. In order to achieve this we sometimes might need to:</p><ul><li>reduce the number of assets by generalising and grouping assets</li><li>reduce the number of risk scenarios by generalising and grouping scenarios</li><li><strong>select only a subset of assets and a subset of scenarios that make sense as risks</strong></li></ul><p>This last sentence will be my point of departure in an attempt to automate the process. In the next episode of the series I will define the technical solution for automation and implement the first, basic version.</p><h3>Potential risks of automation</h3><p>While LLMs present an attractive opportunity for process automation, automation in general and LLM-backed automation specifically come with some significant risks that I would be amiss if I wouldn’t discuss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lrARgUfim45otuDvv6Dd_w.png" /></figure><h4>Machine Learning as a black box</h4><p>When we are using a traditional algorithm for solving a problem, it’s relatively easy to explain how the output has been arrived at. When we encounter an output that doesn’t meet our expectations we can often diagnose and point to the specific line of code that’s introducing misalignment.</p><p>LLMs on the other hand, as members of the broader family of Machine Learning (Neural Network) solutions, are represented in as a set of numbers with very high overall “entropy”. It’s difficult to say which number is responsible for the output and what will happen if we change a particular number.</p><p>Inability to understand the process behind producing a specific output and even inability to reproduce the same output with similar input can is a source of uncertainty and risk itself. This risk can be mitigated by looping in the operator that will approve the outputs at selected “checkpoints” in the process. Removing the operator from this loop should be gradual process that is tied closely to building trust in the solution.</p><p>But even so, in the big picture, we need to accept that clear understanding all building blocks of technical solutions that surround us is a forgone idea.</p><h4>LLMs capabilities — knowledge and reasoning</h4><p>In a highly specialised task such as Risk Assessment for a specific organisation we need to have reasonable confidence that the LLM is capable of producing valuable output. This means that:</p><ul><li>We need to make sure that LLM has been trained on material sufficient for capturing meaning behind concepts such as risk, risk scenarios, TTPs, vulnerabilities and their technical aspects, assets and their roles in key processes</li><li>We need to make sure that the LLM has sufficient reasoning capacity and capability of following instructions for executing tasks</li><li>We need to be able to break down complex tasks into a set of smaller, simpler tasks</li><li>We need to understand traits of a specific LLM that we use, e.g. preferred layout of prompts, formal structuring, etc.</li></ul><p>This confidence can be built by interacting with their LLM in a series of iterative attempts to improve produced outputs but also familiarising ourselves with important aspects of their training.</p><h4>Potential vulnerabilities</h4><p>Using LLM as a solution dependency means that we can introduce aditional weaknesses and vulnerabilities into it that we need to account for. And example of a potential vulnerability is prompt injection that can occur when we feed unsanitized input to the model.</p><p>In order to identify and mitigate these vulnerabilities I will be performing security tests on the implemented solution and selecting and implementing appropriate security controls.</p><h3>Summary</h3><p>In this episode I laid out the context in which I will be doing the automation work. I hope I managed to convey the importance of the Risk Management process as a foundational tool for selecting directions in IT security work and hint at the opportunities for automating it in context of the proliferation of LLMs.</p><p>In the episodes that will follow I will share my experiences in implementing automation solutions for specific instance of the process. Starting with <a href="https://medium.com/@ishish222/revolutionizing-risk-assessment-part-2-boilerplate-application-5df41609bd39">creating a boilerplate gradio application</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8407a512663" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>