<?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 Francesco Cerizzi on Medium]]></title>
        <description><![CDATA[Stories by Francesco Cerizzi on Medium]]></description>
        <link>https://medium.com/@cerizzi?source=rss-662295d90155------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8Vf7lyb7YwP7N65FFWYoow.jpeg</url>
            <title>Stories by Francesco Cerizzi on Medium</title>
            <link>https://medium.com/@cerizzi?source=rss-662295d90155------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 09:50:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cerizzi/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[How Decision Models Work: Inside the Open System One Models]]></title>
            <link>https://medium.com/@cerizzi/how-decision-models-work-inside-the-open-system-one-models-078de1398b58?source=rss-662295d90155------2</link>
            <guid isPermaLink="false">https://medium.com/p/078de1398b58</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[decision-model]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Francesco Cerizzi]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 17:36:39 GMT</pubDate>
            <atom:updated>2026-11-04T17:55:39.456Z</atom:updated>
            <content:encoded><![CDATA[<h4>What a decision model is, where it fits next to an LLM, and how the open ones on Hugging Face turn one forward pass into probabilities you can act on</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K9p5VhoXiFY0CrxpzrOuYg.png" /><figcaption>Image generated by the author with GPT Image 2.5 Flare.</figcaption></figure><p>On 15 September 2026, TypeSafe AI opened early access to Jev, a model that can’t write a sentence. You send it a state, say a support ticket, plus a few typed questions, and it returns one probability per answer: 0.96 that the customer is threatening to cancel, 1.00 that the ticket belongs to billing. TypeSafe calls this a System One model; I’ll mostly say decision model. By 28 October the community <a href="https://huggingface.co/spaces/multimodalart/jev-decision-index">Jev Decision Index</a> on Hugging Face scored 242 of them, and most of the open ones publish their code.</p><p>I wanted to know how a model like that works inside, so I read the cards and the code of the open ones and ran five of them on Amazon EC2 GPUs: KnowLine 31B Gen1, vLLM-SR d3-ultra, Perplexity Decider v1.2, Cloudflare’s Clef and Strands Decider 2B from AWS’s Strands Labs. In this post, I’ll start with what a decision model is and where it fits next to an LLM, send a first request with one curl, and then look inside: how the open models turn one forward pass into probabilities, what each token is allowed to see, why reading the state once matters, and how the probabilities get calibrated. At the end, I put them next to Jev and OpenAI’s Decisions API on the same 496 decisions.</p><h3>What a decision model is and what it can do</h3><p>TypeSafe’s documentation defines a System One model as one that evaluates a state and returns typed answers and probabilities instead of generated text, a name taken from the fast, intuitive System 1 of Daniel Kahneman’s <em>Thinking, Fast and Slow</em>. You write the possible answers yourself, with three question types:</p><ul><li>Choice: one option from a set you define, with a probability for each</li><li>Score: a level on an ordered scale, with a probability for each level</li><li>Noul: the probability that a yes/no question is true (OpenAI’s Decisions API calls it a predicate)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1f0w1RD1oZlAmANmYuqpqg.gif" /><figcaption>Figure 1: a generative model writes its answer token by token and your code parses it; a decision model returns one distribution per question in a single pass. Diagram by the author; schematic, not a measurement.</figcaption></figure><p>Because there’s no free text, the model can’t invent a label or return broken JSON. A perfectly typed answer can still be the wrong decision, though. What you get is a probability on every answer, so <em>your code decides when to act and when to escalate</em>.</p><p><em>The state doesn’t have to be text.</em> Jev, OpenAI’s Decisions API and some open models such as vLLM-SR d3-ultra also read images, so you can ask whether a product photo shows visible damage (an example from OpenAI’s guide) or what the person at the door is carrying (one from TypeSafe’s). Jev 1.14 and d3-ultra add a fourth question type, Box, which answers where something is in the picture, and d3-ultra also reads video. TypeSafe labels its image support “Dreamer-ready”: fine for prototypes, not yet up to its own bar for production.</p><h3>Where a decision model fits</h3><p>The simplest way I’ve found to think about it comes from ByteByteGo’s <a href="https://blog.bytebytego.com/p/ep227-top-9-places-to-use-jev">Top 9 Places to Use Jev</a>: <em>let the LLM do the generating, and give the decisions around it to a decision model</em>. Figure 2 is my version of their nine places.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQ9DQ7i_OVWWFbONRFEX2Q.png" /><figcaption>Figure 2: nine places for a decision model, each with its input and its possible answers. Diagram by the author, inspired by ByteByteGo’s “Top 9 Places to Use Jev”; the numbers in cards 5, 6 and 8 are illustrative.</figcaption></figure><p>The last card is what the probability is for: <em>act on the confident answers, confirm the middle ones and hand the rest to a person</em>. The Strands team lists similar uses in its <a href="https://strandsagents.com/blog/introducing-strands-decider/">launch post for Strands Decider</a>.</p><h4>Your first decision with a single curl command</h4><p>All you need is a TypeSafe API key and curl. Save this as ticket.json. The state is the evidence and each entry under questions is an independent decision; the quoted outage is there to tempt the model toward the wrong queue.</p><pre>{<br>  &quot;model&quot;: &quot;jev-1.14.0&quot;,<br>  &quot;state&quot;: {<br>    &quot;current_message&quot;: &quot;I was charged twice. Refund the duplicate today or I will cancel.&quot;,<br>    &quot;quoted_history&quot;: &quot;Last year there was an outage; it was resolved and is quoted only as history.&quot;<br>  },<br>  &quot;questions&quot;: {<br>    &quot;churn_threat&quot;: {<br>      &quot;criteria&quot;: null,<br>      &quot;instructions&quot;: &quot;Does the sender affirmatively threaten to cancel or leave? A negated statement such as &#39;not threatening to cancel&#39; is false.&quot;,<br>      &quot;type&quot;: &quot;noul&quot;<br>    },<br>    &quot;queue&quot;: {<br>      &quot;criteria&quot;: {<br>        &quot;account&quot;: &quot;account access or settings without an active compromise&quot;,<br>        &quot;billing&quot;: &quot;charges, invoices, payments, or refunds&quot;,<br>        &quot;general&quot;: &quot;none of the other queues&quot;,<br>        &quot;outage&quot;: &quot;current service unavailability or production failure&quot;,<br>        &quot;sales&quot;: &quot;pricing, purchase, or contract questions&quot;,<br>        &quot;security&quot;: &quot;active compromise, suspicious access, credential theft, or fraud&quot;<br>      },<br>      &quot;instructions&quot;: &quot;Route the current request using this priority: security &gt; outage &gt; billing &gt; account &gt; sales &gt; general. `quoted_history` does not describe the current issue.&quot;,<br>      &quot;type&quot;: &quot;choice&quot;<br>    },<br>    &quot;urgency&quot;: {<br>      &quot;criteria&quot;: [<br>        &quot;routine: no current harm or deadline&quot;,<br>        &quot;time-sensitive: billing impact or explicit near-term deadline&quot;,<br>        &quot;critical: active compromise or current outage&quot;<br>      ],<br>      &quot;instructions&quot;: &quot;Rate the urgency of `current_message`, not the quoted history.&quot;,<br>      &quot;type&quot;: &quot;score&quot;<br>    }<br>  }<br>}</pre><p>Then send it:</p><pre># macOS/Linux<br>export TYPESAFE_API_KEY=&quot;YOUR_TYPESAFE_API_KEY&quot;<br>curl -s https://api.typesafe.ai/v1/systemone \<br>  -H &quot;Authorization: Bearer $TYPESAFE_API_KEY&quot; \<br>  -H &quot;Content-Type: application/json&quot; \<br>  --data-binary @ticket.json</pre><p>Jev 1.14’s answers come back like this:</p><pre>{<br>  &quot;model&quot;: &quot;jev-1.14.0&quot;,<br>  &quot;answers&quot;: {<br>    &quot;churn_threat&quot;: { &quot;type&quot;: &quot;noul&quot;, &quot;noul&quot;: 0.96 },<br>    &quot;queue&quot;: {<br>      &quot;type&quot;: &quot;choice&quot;, &quot;choice&quot;: &quot;billing&quot;, &quot;confidence&quot;: 1.0,<br>      &quot;probabilities&quot;: { &quot;account&quot;: 0.0, &quot;billing&quot;: 1.0,<br>                         &quot;general&quot;: 0.0, &quot;outage&quot;: 0.0,<br>                         &quot;sales&quot;: 0.0, &quot;security&quot;: 0.0 }<br>    },<br>    &quot;urgency&quot;: {<br>      &quot;type&quot;: &quot;score&quot;, &quot;score&quot;: 1.0, &quot;confidence&quot;: 1.0,<br>      &quot;probabilities&quot;: { &quot;0&quot;: 0.0, &quot;1&quot;: 1.0, &quot;2&quot;: 0.0 }<br>    }<br>  },<br>  &quot;usage&quot;: { &quot;input_tokens&quot;: 570, &quot;output_tokens&quot;: 94 }<br>}</pre><p>All three answers are right, and Jev ignored the quoted outage. At $0.042 per million input tokens, with output tokens free, the request cost $0.000024 and took 74 ms.</p><p>OpenAI’s <a href="https://developers.openai.com/api/docs/guides/decisions">Decisions API</a>, now generally available, takes the same kind of request: a shared input and up to 400 questions of type predicate, choice or score, on gpt-6-luna. Any answer can come back as a refusal, so check the type before you read a probability.</p><h3>Six ways to read a decision out of a model</h3><p>Jev’s weights and architecture aren’t public. TypeSafe documents what you can rely on from the outside (it reads the state once and answers every question against it in parallel) and names its training method, RLCD (Reinforcement Learning for Calibrated Decisions). For an outside view, there’s Archer Hume’s public post <a href="https://archerhume.com/posts/jevs-architecture-unmasked/">Jev’s Architecture Unmasked</a>. For the open models, we can read the code line by line.</p><p>Almost all of them start from an ordinary LLM. Instead of letting it write an answer word by word, they give it the ticket, the question and the options in one go, <em>run it once, and read the probabilities straight out of it</em>. Take the ticket “I was charged twice.”, the question “Which team?” and the options billing, sales and tech: the six families differ in where they read the answer and what, if anything, they train (Figure 3).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YqgF_P89-IUMur_cHL9zlg.gif" /><figcaption>Figure 3: six ways to read a decision out of a model, all on one example ticket. Diagram by the author from each project’s card or code; the bars are illustrative.</figcaption></figure><ul><li>Read the option letters. List the options as A billing, B sales, C tech, and ask for the letter. An LLM’s last step gives a raw score, called a logit, to every word it could write next, and A, B and C are three of them. Keep those three scores, and a softmax turns them into probabilities that sum to one. No additional training is required: <a href="https://github.com/TheoLeeCJ/SemIf-OpenJev">SemIf</a> does this with a frozen Qwen3.5-4B, <a href="https://github.com/Mapika/decider">Decider chat</a> with stock Gemma-4-31B-it.</li><li>Fine-tune the readout. Same idea, but the model is trained so that those scores are right more often and the probabilities can be trusted. <a href="https://huggingface.co/PelaAI/KnowLine-31B-Gen1">KnowLine 31B Gen1</a>, a LoRA fine-tune of Gemma-4-31B-it, reads the scores of the options’ label words. <a href="https://huggingface.co/perplexity-ai/pplx-decider-v1.2">Perplexity Decider v1.2</a> and <a href="https://huggingface.co/vllm-sr/d3-ultra">vLLM-SR d3-ultra</a> add a dedicated readout with one row per answer code (Figure 4).</li><li>Train a new head. Replace the part of the LLM that picks the next word with a small new piece, trained only to choose among options. <a href="https://github.com/strands-labs/strands-decider">Strands Decider 2B</a>, from AWS’s Strands Labs, uses a pointer head of about a million parameters (Figure 4). <a href="https://huggingface.co/Cloudflare/clef">Cloudflare’s Clef</a> adds a small transformer on top of the LLM’s final hidden states that scores all the options of all the questions together.</li><li>Compare embeddings. <a href="https://huggingface.co/Contrastive-LM/CLM-v0.1-8B">CLM-v0.1-8B</a> turns the ticket and each option into a vector, a list of numbers that captures meaning, and picks the option whose vector best matches the ticket’s. Option vectors don’t depend on the ticket, so you can compute them once and reuse them.</li><li>Encode text and labels. <a href="https://huggingface.co/fastino/GLiNER2.5-Decide">GLiNER2.5-Decide</a> is a small encoder (340M parameters) that reads the text and your list of labels together and scores each label, with no prompt and no generated text. You pass any label set at call time, without retraining.</li><li>Denoise a JSON canvas. <a href="https://github.com/JoshuaSP/open-jev">open-jev</a> uses DiffusionGemma, a diffusion language model, which writes by filling in blanks instead of word by word. It lays out the JSON answer with the answers left blank, lets the model fill only those blanks, and keeps the most likely of the allowed values. No additional training is required, and what you get back is the chosen JSON: its README says the scores behind it aren’t calibrated probabilities.</li></ul><p>The two trained readouts are easier to see than to describe, so Figure 4 runs the same ticket, the one from the Strands launch post, through both.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*72imx-2EqKWzKnMbmrxdhQ.png" /><figcaption>Figure 4: two ways to turn one forward pass into option probabilities, on the same ticket from the Strands launch post. Left: the answer-code readout of d3-ultra and Perplexity v1.2, with d3-ultra’s probabilities from my run of 3 November 2026 (prompt shortened). Right: Strands Decider’s pointer head, with the output the launch post printed. Diagram by the author; schematic, vectors not to scale.</figcaption></figure><p>With answer codes, the prompt lists the options as A: billing, B: sales and C: retail and asks for the code. The model reads the whole prompt and ends up, at its last position, with a list of 5,120 numbers that sums up what it read: its hidden state. A chat LLM would turn that list into a score for every word in its vocabulary and pick the next word. d3-ultra and Perplexity replace that step with a small readout that has one row of 5,120 weights per answer code, and multiplying the hidden state by a row gives that code’s raw score. For this ticket, d3-ultra’s raw scores were 13.2 for A, 3.5 for B and 6.9 for C. Raw scores can be any number, so they aren’t probabilities yet: dividing them by a temperature (more on that below) and applying a softmax turns them into numbers between 0 and 1 that sum to 1, here 0.9975 for billing, 0.0001 for sales and 0.0025 for retail. With 255 rows, a question can have at most 255 options.</p><p>Strands Decider’s pointer head works the other way round, and it’s the design I find most elegant. Its prompt carries a special &lt;answer&gt; token, a placeholder whose hidden state ends up holding the model’s view of the answer. The head compares that hidden state with the hidden state at each option word in the prompt (billing, sales, retail), as if pointing at the option that matches, and turns the comparisons into probabilities that sum to one: 0.845 for billing in the launch post. <em>Nothing in the head belongs to a particular option</em>, so 3 options or 40 go through the same million parameters. It runs on a laptop: on my M1 Pro Mac it gave the same answers as on an EC2 GPU on 200 short test decisions, at a median of 510 ms. It’s Apache-2.0 with its training data and scripts published, which makes it the easiest of these designs to study end to end.</p><p>On the shared ticket, d3-ultra and Perplexity v1.2 both answer billing and rank retail above sales, the same order as the Strands launch post’s example, with 0.9975, 0.940 and 0.845 on billing. That’s one ticket, so it shows that the readouts agree here, not whose probabilities you can trust more.</p><h3>Where attention matters: what each word can see</h3><p>Attention, the core mechanism of the <a href="https://arxiv.org/abs/1706.03762">transformer</a> architecture that today’s LLMs are built on, is the step where each word of the input looks at the other words to work out what it means. In “I was charged twice”, “charged” only means a duplicate charge once it has seen “twice”. A model is a stack of layers that repeat this step, and it gets expensive on long inputs, because every word looks at every other word. So recent models do full attention only in some layers. In the Qwen3.8-27B layout, used by three of the larger models I ran, one layer in four sees the whole input and the others carry a running summary forward (Gated DeltaNet, a linear-attention layer). KnowLine’s Gemma-4-31B-it sees the whole input in one layer in six and the last 1,024 tokens in the others (Figure 5).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hLu8G_EzSbIPMUo_k8iHBg.png" /><figcaption>Figure 5: layer layouts from the models’ config.json files. Diagram by the author.</figcaption></figure><p>The layers that see the whole input are where the open models make their most interesting choice: which words may look at which. A chat LLM lets each word look only at the words before it, because it writes left to right and the next word doesn’t exist yet. Read that way, in “I was charged twice. Which queue?” the word “charged” is understood without “twice”, and the ticket is read without knowing the question; only the last words see everything. For a decision, <em>the whole ticket and every question are there from the start, so nothing forces that order</em>. Figure 6 shows the four choices on that ticket with two questions, “Which queue?” and “Cancel threat?”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7mLYcK4K7ENIOfXGh0aoOg.gif" /><figcaption>Figure 6: which tokens each token can attend to in the full-attention layers, for a short ticket and two questions, one word per token. The animation steps through the tokens one at a time, then shows every row at once. Strands Decider reads like KnowLine. d3-ultra’s list of the questions, which sits in the first part of its prompt with the ticket, is left out. Diagram by the author from each model’s card and code; schematic.</figcaption></figure><ul><li>KnowLine reads left to right, like a chat LLM. It reads the ticket once, keeps that reading, and then reads each question on its own, so “Which queue?” never sees “Cancel threat?”. Strands Decider works the same way: its 2B base model reads left to right, keeps the ticket in a shared cache, and scores each question independently.</li><li>d3-ultra splits its prompt in two. The first part is the same for every question: a list of all the questions in the request, then the ticket. This part reads itself in both directions, so “charged” sees “twice” and the ticket is read knowing what will be asked. The second part is one block per question, with that question’s options and answer codes. Each block sees the first part and itself, but the first part never sees any block, so the ticket’s reading is the same for every question.</li><li>Perplexity Decider v1.2, with all the questions in one request, lets every word see every word: the ticket sees the questions, and “Which queue?” sees “Cancel threat?”. Its card reports that this helps on some tasks and hurts on others.</li><li>Clef reads left to right over the ticket and both questions in one go, so “Cancel threat?” sees “Which queue?” but not the other way round, and then its joint head scores all the answers together.</li></ul><p>On a 20,000-token record the difference grows: read left to right, the records near the start are understood without what comes after them. <em>Letting the ticket look both ways turned out to matter on my long records</em>, as the tests at the end of this post show.</p><h3>Read the state once</h3><p>The design choice with the biggest effect on cost is <em>whether the state is read once per request or once per question</em>. Three questions about a 10,000-token record cost about 10,150 tokens of compute with a shared state and about 30,150 with one pass per question (Figure 7).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j11sH6dHmYV5ozzR9QcMow.gif" /><figcaption>Figure 7: with a shared state, three questions about a 10,000-token state cost about 10,150 tokens of compute; with one pass per question, about 30,150. Diagram by the author; illustrative arithmetic with 50 tokens per question.</figcaption></figure><p>TypeSafe documents that Jev reads the state once. d3-ultra does it with a class called StateOnce, and the mask in Figure 6 is what makes that valid: the first part of the prompt (the question list and the ticket) never sees a question’s own block, so it comes out the same for every question and is computed once per request. KnowLine keeps a cached reading of the ticket instead.</p><p>I measured the difference on eight 8,000-token records, with 1 to 64 questions per record (Figure 8). Here, “billed input tokens” means each system’s reported input-token usage. For the self-hosted models, these are usage counts; actual EC2 charges were based on GPU-hours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WadBfOtNYRUIV2MzW6oxkQ.png" /><figcaption>Figure 8: median time (left) and billed input tokens (right) per request for 8,000-token records with 1 to 64 questions per record, log scales. Open models single stream on one RTX PRO 6000; Jev 1.14 and the Decisions API, with prompt caching off, as round trips from AWS Lambda, so their times include the network. Chart by the author.</figcaption></figure><p>The designs that read the record once stay nearly flat on both charts. At 64 questions, d3-ultra with StateOnce and Perplexity with all the questions in one request took 2.2 to 3.4 times as long as one question, and Jev 1.14 and the Decisions API 1.4 and 1.6 times; 64 questions about one of these records cost $0.0008 with Jev and $0.0019 with the Decisions API. Reading the record again for every question requires 64 times as much input-token processing. For Perplexity with one question per call, this took 108 seconds. KnowLine sits in between, fast thanks to its cache but reporting every question’s full prompt in its input-token usage. So when you ask several questions about the same record, <em>how the model reads it matters more than which model it is</em>.</p><h3>Probabilities you can threshold</h3><p>A softmax always sums to one, but that doesn’t make 0.9 mean “right 90% of the time”. The 2017 paper <a href="https://arxiv.org/abs/1706.04599">On Calibration of Modern Neural Networks</a> found that modern neural networks are often poorly calibrated, and the networks it looked at tended to be overconfident: among the answers a model gives 0.99, fewer than 99 in 100 are right. For a decision model that matters more than for a chatbot, because <em>the probability is what your code acts on</em>. If you act above 0.9 and escalate the rest, a model that says 0.95 when it’s right 80% of the time sends its mistakes straight through.</p><p>The same paper found a simple fix surprisingly effective: temperature scaling. You choose one number, the temperature T, and divide every raw score by it before the softmax. A T above 1 pulls the scores closer together and makes the probabilities less extreme: with T = 2, d3-ultra’s 0.9975 on the payouts ticket in Figure 4 would become 0.95. A T below 1 does the opposite. T is fitted on held-out examples (ones the model wasn’t trained on) to bring predicted confidence closer to observed accuracy. <em>It never changes which answer wins, only how sure the model says it is.</em> The open models ship theirs:</p><ul><li>d3-ultra: 1.046 for a single question and 1.0 otherwise</li><li>Perplexity Decider v1.2: 1.382, fitted in its joint format</li><li>KnowLine: 1.44, folded into its weights</li><li>Jev: calibrated in training, by TypeSafe’s description of RLCD</li></ul><p>Can you change it? <em>With the open models, yes</em>: you run the code, so you can divide the raw scores by any T you like, and d3-ultra keeps its T as one number in decision_config.json. When I refitted d3-ultra’s temperature on my short test sets (T = 2.11), its calibration error on routine decisions halved and on long records doubled, which is why I’d fit T on data like your own. With a hosted API you can’t touch the model, but you can rescale what it returns: raise each probability to the power 1/T and divide by their sum, which gives exactly what dividing the raw scores by T would. It works less well on rounded numbers: Jev and the Decisions API mostly return two decimals, and an answer at 1.00 stays at 1.00.</p><p>To check the result I use expected calibration error (ECE), the average gap between confidence and accuracy, where zero is perfect. Over all my test decisions d3-ultra, Perplexity v1.2 and Jev 1.14 were well calibrated, at about 0.02, but a temperature fitted on one kind of data doesn’t always carry over: on long records alone, Jev’s ECE rose to 0.094. <em>Calibrate on traffic that looks like yours.</em></p><h3>Seven designs on the same 496 decisions</h3><p>I built a synthetic benchmark of three sets, with every expected answer computed by code: 200 routine decisions over short states, 128 short cases that chain two or three stated rules, and 168 long records of 1,000 to 20,000 tokens. <em>The first set is intended to resemble routine application traffic</em>: a ticket, a message, a short record. I built the long-record set on purpose to push the models to the edge, Jev included. Each case is simpler than it looks: three records decide the answer, a twin case changes one word so the answer must change, and everything else is noise (Figure 9). Along the way I asked myself whether that’s a fair benchmark, and my answer is that it’s a stress test, not a picture of everyday use: it shows where the designs differ, not how they’ll do on your tickets. To choose a model for your own traffic, the <a href="https://huggingface.co/spaces/multimodalart/jev-decision-index">Jev Decision Index</a> is a better place to start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MFmbl7i7UxCOGSoJoeBeBA.png" /><figcaption>Figure 9: one case from the long-record set, and its twin. Three records decide the answer, and the twin changes one word in the third. The set’s other cases ask whether a request was approved under an event log, or what a group’s census says about its members. Synthetic data. Diagram by the author.</figcaption></figure><p>I ran the open models on Amazon EC2 G7e instances (NVIDIA RTX PRO 6000 GPUs with 96 GB each), one model per GPU on Spot at $2.10 to $2.24 per GPU-hour, and called Jev and the Decisions API from AWS Lambda. Figure 10 puts each design next to what it measured.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bhj-anJwyVp529ZpaqQSvQ.png" /><figcaption>Figure 10: design summary from the cards and code, with the share of decisions right on the routine and long-record sets, the median latency on the routine set, and how many times longer a 20,000-token record took than a 1,000-token one. Open models single stream on one RTX PRO 6000; Jev and the Decisions API as round trips from AWS Lambda in us-east-1. Strands Decider’s server cuts longer states to its 4,096-token window, so its growth covers at most 4,096 tokens. Chart by the author.</figcaption></figure><p>On routine decisions all the models perform similarly, at 93.0% to 98.5%, except Strands Decider 2B, which is built for something different from the others: its team made it small for fast experiments and local development on hardware you already have. With fewer than one-tenth as many parameters and about 6 GB of GPU memory, it answered routine decisions in 106 ms with 83.0% right. Most long records are longer than its 4,096-token window, and its server cuts them to fit, so they’re beyond it (31.5%).</p><p>On long records the other six spread from 53.6% to 97.0%, and <em>the two models that read the record in both directions lead</em>: d3-ultra at 97.0% and Perplexity v1.2 at 93.5%, ahead of KnowLine (80.4%), Jev 1.14 (75.0%), the Decisions API (56.0%) and Clef (53.6%).</p><p>Each of these models was also trained on different data, so that lead could come from training as much as from attention. To separate the two, I kept everything else fixed and ran the same d3-ultra weights under three attention modes (Figure 11).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vCtdKJZgU1q6TNi-N2Q2KA.png" /><figcaption>Figure 11: vLLM-SR d3-ultra under three attention modes on the same weights: share of the long records right at each length, then decisions right, median time per long record and peak GPU memory as PyTorch counted it. In-process on one RTX PRO 6000, one record at a time. Chart by the author.</figcaption></figure><p>Reading left to right (a causal mask), d3-ultra got 145 of 168 long records right instead of 163, with the gap opening from 8,000 tokens on; with every word seeing every word, it got 165. The weights were trained for the shipped mode, so part of the drop can come from that, but on the same weights and the same cases, <em>letting the record look both ways was worth about 18 decisions</em>. For me, that’s the most interesting result in this post.</p><p><em>Looking both ways costs some time, but not much.</em> Against reading left to right, the shipped mask took 7% longer on a typical long record and 9% longer at 20,000 tokens; letting every word see every word took 15% and 35% longer, most likely because more pairs of words get compared. Memory didn’t follow the mask: the shipped mode’s 81 GB comes from StateOnce, which keeps the record’s reading for the questions, and with it off the shipped mask peaked at the same 57 GB as the other two. That’s the price of reading the record once, and it pays off when you ask several questions about the same record (Figure 8). Of the two masks that read both ways, the shipped one was nearly as accurate (163 against 165 of 168) and faster (1.91 s against 2.07 s per long record).</p><h3>Conclusion</h3><p>Decision models are useful wherever your application needs a quick, closed answer: a queue, a yes or no, a score, each with a probability your code can act on. They’re fast and cheap enough to sit in a request path: Jev answered my first ticket in 74 ms for $0.000024. <em>The open decision models add what a hosted API can’t</em>: you can read how they work, run them on your own GPUs or even on a laptop, and set the temperature yourself.</p><p>Inside, most of them are LLMs with a different ending: a readout over answer codes or labels, a new head, or no training at all, plus a temperature. What matters when you deploy one is what the record can see, whether it’s read once per request, and how the probability was calibrated. On my 200 routine decisions, the four larger open models were 93% to 98% right and answered in 106 to 194 ms on one GPU, in the same range as Jev 1.14 (59 ms) and OpenAI’s Decisions API (161 ms) as round trips from AWS Lambda. <em>Long, rule-heavy records are where the designs separate.</em></p><h3>Key takeaways</h3><ul><li>Use a decision model wherever your code needs one closed answer with a probability: routing, guardrails, tool-call gates, triage, evals.</li><li>Measure calibration on data like yours, and set input limits explicitly when you serve a model yourself.</li><li>To choose a model, start from the <a href="https://huggingface.co/spaces/multimodalart/jev-decision-index">Jev Decision Index</a>; this post is about how they work, not which one to pick.</li></ul><h3>Further reading</h3><ul><li><a href="https://huggingface.co/spaces/multimodalart/jev-decision-index">Jev Decision Index</a>, the community board on Hugging Face that scores open decision models</li><li><a href="https://arxiv.org/abs/2609.37647">Evaluating and Benchmarking the System One Model Jev</a>, an independent evaluation of Jev 1.13 on 37 public datasets and, since its 29 October revision, on sequential tasks</li></ul><h3>Acknowledgments</h3><p>This post builds on public work: TypeSafe’s documentation; ByteByteGo’s map of places to use a decision model; the Strands Labs team’s <a href="https://strandsagents.com/blog/introducing-strands-decider/">Strands Decider</a> and its open training recipe; the Jev Decision Index and its maintainer, multimodalart; and the authors of KnowLine, vLLM-SR d3-ultra, Perplexity Decider, Clef, SemIf, Decider chat, CLM, GLiNER and open-jev, who publish their weights and code.</p><h3>Personal thoughts</h3><p>What I enjoyed most is that <em>this new way of using an LLM unlocks many opportunities</em>: a fast, typed decision with a probability you can act on fits in places where a chat model never could. That’s why I decided to dive deep into how these models work, and reading their code taught me more than any benchmark. If you’re about to put one in a request path, read its card and its serving code first. It’s an hour well spent.</p><p>If you’re as passionate about generative AI as I am and want to dive deeper into these topics, feel free to connect with me on LinkedIn. I’m always excited to discuss AI innovations and share experiences with fellow developers and architects.</p><h3>General disclaimer</h3><p>This post and all the code examples are intended for demonstration and educational purposes only. The implementations shown are not designed for production use without further modifications and hardening. Before deploying to a production environment, ensure you:</p><ul><li>Conduct thorough testing</li><li>Perform security assessments</li><li>Implement proper error handling</li><li>Optimize based on your specific requirements</li><li>Follow AWS and industry best practices</li></ul><p>The opinions expressed in this article are my personal views and do not necessarily represent the views of AWS or any other organization.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=078de1398b58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond chatbots: Building intelligent travel planning with multi-agent AI orchestration on Amazon…]]></title>
            <link>https://medium.com/@cerizzi/beyond-chatbots-building-intelligent-travel-planning-with-multi-agent-ai-orchestration-on-amazon-7a70c0a9c47c?source=rss-662295d90155------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a70c0a9c47c</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[amazon-bedrock-agents]]></category>
            <category><![CDATA[travel]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Francesco Cerizzi]]></dc:creator>
            <pubDate>Mon, 11 Aug 2025 10:50:57 GMT</pubDate>
            <atom:updated>2025-08-11T14:22:09.444Z</atom:updated>
            <content:encoded><![CDATA[<h3>Beyond chatbots: Building intelligent travel planning with multi-agent AI orchestration on Amazon Bedrock — Part 2</h3><p><em>Part 2 of a series on implementing multi-agent AI systems with Amazon Bedrock</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lVoLVdt9EJwyYA4F3k5M_w.png" /><figcaption>Image generated by the authors with Amazon Nova Canvas through Amazon Bedrock.</figcaption></figure><p><a href="https://medium.com/@chiara.relandini/beyond-chatbots-building-intelligent-travel-planning-with-multi-agent-ai-orchestration-on-amazon-597c7e63366a">In Part 1</a>, we established the foundation for intelligent travel planning by combining social media analysis with user profiling to generate structured recommendations. Now, we dive into the heart of our system: <strong>multi-agent orchestration</strong> that transforms those recommendations into comprehensive travel plans through sophisticated AI collaboration.</p><p>Instead of a single AI handling everything, imagine a team of specialized travel experts working behind the scenes, one researching destinations, another checking current events, a third analyzing government travel requirements, and a fourth creating personalized packing lists. All while you watch their progress unfold in real-time.</p><p>This is exactly what we’ve built using Amazon Bedrock Agents and AWS AppSync Events, and in this post, we’ll show you how to implement similar intelligent orchestration systems that go far beyond simple chatbots.</p><p><em>This is a 3-part series co-authored with Chiara Relandini (</em><a href="https://medium.com/@crelandini">@crelandini</a><em>) that describes the complete implementation of this multi-agent travel planning system.</em></p><h3>The Challenge: Moving Beyond Sequential AI</h3><p>Traditional AI applications process requests sequentially: analyze input, generate response, return result. But real-world problems like travel planning require parallel expertise, iterative research, and complex decision-making that benefits from specialized knowledge domains.</p><p>Consider planning a 14-day adventure trip to Japan in August:</p><ul><li><strong>Itinerary Planning</strong>: Requires destination expertise, activity research, and timing optimization</li><li><strong>Current Events</strong>: Need to check for disruptions, festivals, or safety concerns</li><li><strong>Government Requirements</strong>: Must verify visa needs, health advisories, and entry restrictions</li><li><strong>Practical Preparation</strong>: Packing lists must consider climate, activities, and cultural norms</li></ul><p>No single AI agent excels at all these tasks, but a coordinated team of specialized agents can tackle each aspect expertly while working in parallel for efficiency.</p><h3>Amazon Bedrock Agents: The Intelligence Engine</h3><p>To understand our multi-agent system, we first need to grasp what powers it. <strong>Amazon Bedrock Agents</strong> provides the foundation for building AI agents that can reason, plan, and execute complex tasks using foundation models.</p><p>Unlike simple LLM calls, Bedrock Agents can:</p><ul><li><strong>Plan multi-step workflows</strong> by breaking down complex requests</li><li><strong>Use external tools</strong> through Action Groups (Lambda functions)</li><li><strong>Access knowledge bases</strong> for domain-specific information</li><li><strong>Collaborate with other agents</strong> through orchestration patterns</li><li><strong>Maintain conversation context</strong> across multiple interactions</li></ul><p>In our travel system, we use Bedrock Agents to create specialized AI workers. Each agent has specific instructions, access to relevant tools, and the ability to reason about their domain expertise.</p><p><strong>The key insight</strong>: Bedrock Agents don’t just generate responses: they execute workflows. And every step of that execution is captured in detailed traces that show their reasoning process, tool usage, and decision-making.</p><h3>Real-Time Intelligence with AWS AppSync Events</h3><p>Before diving into agent orchestration, let’s address a fundamental challenge: <strong>how do users experience long-running AI processes?</strong></p><p>As Werner Vogels, Amazon’s CTO, noted: “The world we live in is asynchronous.” This is especially true for AI agents that may take seconds or minutes to complete complex tasks. Users shouldn’t stare at loading spinners — they should observe intelligence at work.</p><h4>AWS AppSync Events: Agent Trace Interpretation</h4><p>AWS AppSync Events provides the infrastructure for real-time, serverless WebSocket APIs that can broadcast to millions of subscribers without managing connections or scaling resources.</p><p>Here’s where it gets interesting. Amazon Bedrock Agents produce detailed execution traces describing every step of their reasoning process. We capture these traces and pass them through Amazon Nova Lite — a small, fast LLM — to translate technical execution logs into human-readable progress updates.</p><pre>def interpret_agent_trace(trace_data):<br>    &quot;&quot;&quot;Convert technical agent traces to user-friendly progress updates&quot;&quot;&quot;<br>    prompt = f&quot;&quot;&quot;<br>    Translate this technical agent trace into user-friendly progress:<br>    {trace_data}<br>    <br>    Focus on what the agent is doing and why, in natural language.<br>    &quot;&quot;&quot;<br>    <br>    response = bedrock_client.invoke_model(<br>        modelId=&quot;us.amazon.nova-lite-v1:0&quot;,<br>        body=json.dumps({&quot;prompt&quot;: prompt})<br>    )<br>    <br>    return parse_response(response)</pre><p><strong>The Result:</strong> Users see messages like “Researching transportation disruptions in Japan for August 2025” instead of technical logs. They watch intelligence unfold rather than wait for results.</p><p>Here an example of real-time updates coming from the running agents.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FiL2GFpbL1LE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DiL2GFpbL1LE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FiL2GFpbL1LE%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/331eb5c30e54a4ac4d692dd5b729bc25/href">https://medium.com/media/331eb5c30e54a4ac4d692dd5b729bc25/href</a></iframe><h3>Multi-Agent Architecture: Six Specialists, Two Orchestrators</h3><p>Our system employs six specialized agents organized into two distinct workflows, each managed by a supervisor agent that coordinates parallel execution and intelligent integration.</p><h4>Two-Phase Architecture</h4><p><strong>Phase 1: Itinerary Creation</strong></p><ul><li>Itinerary Supervisor coordinates Travel Planner and News Checker agents</li><li>Creates personalized itineraries while checking for current events and disruptions</li></ul><p><strong>Phase 2: Travel Preparation</strong></p><ul><li>Travel Preparation Supervisor coordinates Country Info and Backpack Creator agents</li><li>Handles government requirements and personalized packing recommendations</li></ul><p>The architecture’s strength lies in <strong>specialization and parallel execution</strong> — while one agent queries government databases, another simultaneously researches practical requirements, with the orchestrator adding contextual intelligence to their combined outputs.</p><p>The following points are the key design principles we followed in building our agentic solution:</p><ul><li><strong>Batch Operations</strong>: Process multiple items simultaneously</li><li><strong>Markdown Output</strong>: Optimized for LLM consumption</li><li><strong>Source Attribution</strong>: Maintain data provenance</li><li><strong>Parallel Execution</strong>: Independent agents work simultaneously</li></ul><p>See in the video below the phase two happening in real-time.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F0WvnSPvTz2Q%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D0WvnSPvTz2Q&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F0WvnSPvTz2Q%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f414cf784b34f7e4815e478cdc1dc49e/href">https://medium.com/media/f414cf784b34f7e4815e478cdc1dc49e/href</a></iframe><h3>Real-World Results: The Japan Adventure</h3><p>Let’s see the complete workflow in action with our Japan travel example.</p><h4>Phase 1 Output: Comprehensive Itinerary</h4><p>The Travel Planner and News Checker agents collaborate to produce:</p><p><strong>Itinerary Structure:</strong></p><pre>- Days 1–5: Tokyo (urban exploration, technology, culture)<br>- Days 6–8: Kyoto (traditional temples, historical sites)<br>- Days 9–11: Okinawa (diving activities - matching user preferences!)<br>- Days 12–14: Nara (famous deer temple, cultural immersion)</pre><p><em>Notice how the system remembers the user’s diving interest from Part 1’s preference collection (“I want to go diving during my vacation”) and intelligently incorporates it by selecting Okinawa — perfect for underwater activities while maintaining the cultural richness of the overall Japan experience.</em></p><p><strong>Current Events Integration:</strong></p><pre>- Starting in 2025, private insurance will be mandatory for travelers<br>- Transportation disruption alerts for August 2025<br>- Festival and event recommendations</pre><h4>Phase 2 Output: Travel Preparation</h4><p>The Backpack Creator and Country Info agents collaborate to produce:</p><p><strong>Official Requirements for Italian travellers (from viaggiaresicuri.it)</strong></p><pre># OFFICIAL TRAVEL INFORMATION: JAPAN (GIAPPONE)<br><br>## ENTRY REQUIREMENTS<br>- Passport: Valid passport required for Italian citizens<br>- Visa: Not required for stays up to 90 days for tourism<br>- No special permits required for regular tourism visits<br><br>## HEALTH ADVISORIES  <br>- No mandatory vaccinations required<br>- Recommended: Standard travel insurance<br>- COVID protocols: Check current requirements</pre><p><strong>Personalized Packing List</strong></p><pre>## JAPAN ADVENTURE: 14-DAY SUMMER EXPLORATION PACKING LIST<br><br>### ESSENTIAL PACKING FACTORS<br>- Weather: Hot and humid (August peak summer)<br>- Temperature Range: 25-35°C (77-95°F)  <br>- High humidity and heatstroke risk<br>- Cultural sensitivity in dress required<br><br>### DIVING GEAR (Okinawa Activities)<br>- [ ] Swimwear (2 sets)<br>- [ ] Rash guard for sun protection<br>- [ ] Diving mask and snorkel<br>- [ ] Reef-safe sunscreen<br><br>### HIKING GEAR (Multi-terrain)<br>- [ ] Quick-dry hiking pants (2 pairs)<br>- [ ] Lightweight, breathable shirts (3-4)<br>- [ ] Comfortable walking shoes<br>- [ ] Portable rain gear</pre><p>In the below video, you can see an example of multi-agent orchestration. In particular, we have isolated the Phase 2 agents. You can observe their reasoning and the messages exchanged between these agents.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FIH1QoC-8X6A%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DIH1QoC-8X6A&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FIH1QoC-8X6A%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e40ab783f7ca10e2acfb382517168f4/href">https://medium.com/media/8e40ab783f7ca10e2acfb382517168f4/href</a></iframe><h3>Are you Ready to Build?</h3><p>We’ve journeyed from the challenge of sequential AI to a sophisticated multi-agent orchestration that handles real-world complexity. You’ve seen how specialized agents collaborate in parallel, how real-time progress transforms user experience, and how intelligent orchestration creates results that no single AI could achieve alone.</p><p>The architecture we’ve demonstrated — combining Amazon Bedrock Agents for intelligent reasoning, AWS AppSync Events for real-time communication, and thoughtful orchestration patterns — provides a proven foundation for building AI applications that go far beyond simple chatbots.</p><p>Whether you’re tackling financial advisory, healthcare coordination, legal research, or any domain requiring complex problem-solving, these multi-agent patterns can transform how users interact with AI systems. Instead of chat interfaces, you can create intelligent processes that users observe and trust.</p><p><strong>Start building today.</strong></p><p>The tools are available, the patterns are proven, and the potential applications are limitless. Your users are ready for AI that works like a team of experts — not just another chatbot.</p><h3>What’s Next: Preview of Part 3</h3><p>In our final post, we’ll dive into the practical lessons learned from building this multi-agent system:</p><ul><li><strong>Performance Optimization</strong>: Strategies for controlling costs and latency</li><li><strong>Error Handling</strong>: Managing agent failures and inconsistencies</li><li><strong>Prompt Engineering</strong>: Advanced techniques for agent coordination</li><li><strong>Development Tools</strong>: Using Amazon Q Developer for multi-agent system development</li><li><strong>User Experience</strong>: Designing interfaces for long-running AI processes</li></ul><p>We’ll also explore the future of agentic AI, including hyper-personalization, advanced memory systems, and the evolution toward human-AI collaboration.</p><h3>Key Takeaways</h3><p>Building multi-agent AI systems requires thinking beyond traditional request-response patterns:</p><ol><li><strong>Specialization Over Generalization</strong>: Multiple focused agents outperform single general-purpose models</li><li><strong>Parallel Execution</strong>: Independent agents should work simultaneously for efficiency</li><li><strong>Real-Time Communication</strong>: Users should observe AI processes, not wait for results</li><li><strong>Tool Integration</strong>: Agents need access to external systems and data sources</li><li><strong>Orchestration Logic</strong>: Coordination between agents is as important as individual agent capabilities</li></ol><p>The techniques demonstrated here apply far beyond travel planning — from financial advisory systems to healthcare coordination, any domain requiring complex, multi-step problem solving can benefit from multi-agent orchestration.</p><p><em>Ready to build your own multi-agent AI system? The architecture patterns and code examples in this post provide a foundation for implementing sophisticated AI orchestration using Amazon Bedrock Agents and AWS services.</em></p><p><em>This series is based on a presentation </em><a href="https://summitmilano.awslivestream.com/v-dev302/live/"><em>delivered at AWS Summit Milano 2025</em></a><em>, showcasing practical implementations of multi-agent AI systems. The techniques demonstrated apply to various domains beyond travel planning. The opinions expressed are our personal views and do not necessarily represent the views of AWS.</em></p><h3>About the authors</h3><p><em>This project was developed and presented by two passionate architects working with generative AI applications and modern full-stack development. The implementation showcases a practical demonstration for building AI applications on AWS, but the opinions expressed in this article are our personal views and do not necessarily represent the views of AWS or any other organization.</em></p><p><em>Ready to build your own multi-agent AI system? Stay tuned for Part 3, we’ll cover lessons learned and optimization strategies (And who knows? Maybe a Part 4 exploring the future with </em><a href="https://aws.amazon.com/bedrock/agentcore/"><em>Amazon Bedrock AgentCore</em></a><em> and </em><a href="https://strandsagents.com/latest/"><em>Strands Agents</em></a><em> — but that’s for another day!).</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a70c0a9c47c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DeepSeek R1 on AWS: Making a 671B Model Run on Consumer GPUs]]></title>
            <link>https://medium.com/@cerizzi/deepseek-r1-on-aws-making-a-671b-model-run-on-consumer-gpus-0732558747ab?source=rss-662295d90155------2</link>
            <guid isPermaLink="false">https://medium.com/p/0732558747ab</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Francesco Cerizzi]]></dc:creator>
            <pubDate>Fri, 31 Jan 2025 21:27:09 GMT</pubDate>
            <atom:updated>2025-02-01T14:14:43.559Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lxmo4YfgyWIpJUY8JTur0g.png" /><figcaption>Image from Amazon Nova Canvas</figcaption></figure><p>The recent release of DeepSeek R1, a 671B parameter model that rivals GPT-4 and Claude 3’s performance, has sparked considerable excitement in the AI community. Traditionally, running such a massive model would require high-powered infrastructure like AWS p5e instances, costing a $84.8 per hour. However, thanks to Unsloth AI’s innovative dynamic quantization approach, we can now deploy this model on more affordable hardware while maintaining most of its reasoning capabilities.</p><h3>Understanding DeepSeek R1 and Dynamic Quantization</h3><p>DeepSeek R1 is a groundbreaking 671B parameter model using a Mixture of Experts (MoE) architecture. While the total parameter count is 671B, it only activates about 37B parameters per task, making it already more efficient than traditional architectures. The model excels at complex reasoning tasks, achieving:</p><ul><li>Nearly 80% accuracy on advanced math tests</li><li>Outperforming 96% of human competitors in programming challenges</li><li>Similar or better performance than GPT-4 and Claude in many tasks</li></ul><p><strong>The Innovation: Dynamic Quantization</strong></p><p>Unsloth’s approach to quantizing DeepSeek R1 is particularly clever, as it considers the model’s unique architecture:</p><ol><li><strong>Architectural Analysis</strong>:<br>- The first 3 layers are fully dense (non-MoE), using 0.5% of weights<br>- MoE layers use shared experts, comprising 1.5% of weights<br>- MLA attention modules use &lt;5% of weights<br>- The remaining 88% are MoE weights that can be heavily quantized</li><li><strong>Smart Precision Distribution</strong>:<br>- Dense layers: Kept at 4–6 bit precision<br>- Shared MoE experts: Maintained at 6-bit precision<br>- Attention modules: Preserved at 4–6 bit precision<br>- Down projection matrices: Higher precision in early layers<br>- Remaining MoE weights: Aggressively quantized to 1.58-bit</li></ol><p>This selective approach results in:</p><ul><li>80% reduction in model size (from 720GB to 131GB)</li><li>a good model output even with the most aggressive quatization at 1.58bit</li></ul><p>The key insight is that naively quantizing all layers equally would break the model, causing endless loops and gibberish outputs. Instead, by understanding which parts of the architecture need higher precision, Unsloth achieved dramatic size reduction while preserving functionality.</p><h3>The Cost-Performance Tradeoff</h3><p>Let’s look at the pricing difference:</p><p>- Full R1 on p5en.48xlarge: $84.8/hour<br>- 1.58 quantized R1 on g6e.12xlarge: $10.493/hour</p><p>That’s an 87% cost reduction! While we do sacrifice some performance and speed, the tradeoff is often worth it for many use cases.</p><h3>Deployment Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cnWIp0W8sO_IKFPOon9yrg.gif" /><figcaption>DeepSeek R1 quatization 1.58-bit running on AWS on a g6e.12xlarge</figcaption></figure><p>There are two approaches to deploy DeepSeek R1 on Amazon EC2:</p><ol><li><a href="https://github.com/ollama/ollama">Ollama</a>: this offers the simplest path forward. It handles resource management automatically, though you’ll be limited to Ollama’s options and configurations;</li><li><a href="https://github.com/ggerganov/llama.cpp">llama.cpp</a>: this provides more control over your deployment, at the cost of some added complexity;</li></ol><p>Before diving into both methods, I’d like to thank <a href="https://medium.com/u/575230725d27">Massimiliano Angelino</a>, whose work provided valuable insights for the Ollama deployment and performance analysis we’ll discuss later.</p><p>For both solutions, the first step is creating an EC2 instance capable of handling Large Language Model inference.</p><h4>Launch EC2 Instance</h4><p>First, let’s set up our EC2 instance through the AWS Console:</p><ol><li>Go to EC2 Dashboard and click “Launch Instance”</li><li>Configure the instance:<br>Name: `deepseek-r1-quantized`<br>AMI: Ubuntu Server 24.04 LTS (HVM)<br>Instance type: g6e.12xlarge<br>Key pair: Create new or select existing<br>Network settings: <br> — Create security group<br> — Allow SSH traffic from your IP<br>Storage: 300 GiB gp3 (you’ll need space for the model)</li><li>Click “Launch Instance”</li><li>Connect into the EC2 instance with <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect.html">the method that you prefer most</a>.</li></ol><h4>Quick Start with Ollama</h4><p>This is the simplest path and it might be sufficient for many users. Thanks to <a href="https://medium.com/u/575230725d27">Massimiliano Angelino</a>’s work, you can run the 1.58-bit quantized version of DeepSeek R1 using Ollama with just two commands:</p><pre># Install Ollama<br>curl -fsSL https://ollama.com/install.sh | sh<br># Run the model<br>ollama run SIGJNF/deepseek-r1–671b-1.58bit</pre><p>That’s it! The model will be downloaded and run automatically. This approach provides:</p><ul><li>(REALLY!) the simplest setup process</li><li>Automatic resource management</li></ul><p>While this method offers less control over the deployment, it’s perfect for:</p><ul><li>Simple API deployments</li><li>Users who prefer convenience over fine-tuned control</li></ul><p>Here <a href="https://github.com/ollama/ollama/blob/main/docs/linux.md">the Ollama documentation</a> to use it as server on Linux.</p><h4>Quick Start with llama.cpp</h4><p>For those seeking more control over their deployment, llama.cpp provides a robust alternative. This approach allows you to fine-tune various aspects of the model’s execution, from quantization parameters to memory management. While it requires a few more steps than the Ollama method, the additional flexibility can be worth the effort, especially for production environments.</p><h4>System Setup and GPU Tools</h4><p>First, install monitoring tools and CUDA:</p><pre># Update and install GPU monitoring tool<br>sudo apt-get update<br>sudo apt-get install nvtop<br># Install CUDA 12.8 (latest stable as of Jan 2025)<br>wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2404/x86_64/cuda-keyring_1.1-1_all.deb<br>sudo dpkg -i cuda-keyring_1.1-1_all.deb<br>sudo apt-get update<br>sudo apt-get -y install cuda-toolkit-12-8<br>sudo apt-get install -y nvidia-open<br># Install additional required packages<br>sudo apt-get install build-essential cmake curl libcurl4-openssl-dev -y<br>sudo apt install nvidia-cuda-toolkit</pre><p><em>Note: for cuda-toolkit and nvidia-open you can reference </em><a href="https://developer.nvidia.com/cuda-downloads?target_os=Linux&amp;target_arch=x86_64&amp;Distribution=Ubuntu&amp;target_version=24.04&amp;target_type=deb_network"><em>the following Nvidia page</em></a><em>.</em></p><p>Verify your GPU installation:</p><pre>nvtop # You should see your GPU(s) listed with their utilization</pre><h4>Build llama.cpp with Server Support</h4><p>Clone and build llama.cpp with CUDA support:</p><pre>git clone https://github.com/ggerganov/llama.cpp<br># Configure build with CUDA support<br>cmake llama.cpp -B llama.cpp/build \<br> -DBUILD_SHARED_LIBS=OFF \<br> -DGGML_CUDA=ON \<br> -DLLAMA_CURL=ON<br># Build all necessary targets<br>cmake --build llama.cpp/build --config Release -j --clean-first --target llama-quantize llama-cli llama-gguf-split llama-server</pre><p>This build command creates several executables:<br>- <em>llama-cli</em>: For interactive command-line interface<br>- <em>llama-server</em>: For running as an API server<br>- <em>llama-quantize</em>: For model quantization<br>- <em>llama-gguf-split</em>: For splitting large models</p><p>Copy the executables to an accessible location:</p><pre>cp llama.cpp/build/bin/llama-* llama.cpp</pre><h4>Set Up Python Environment and Download Model</h4><pre># Create and activate virtual environment<br>sudo apt-get install python3.12-venv<br>python3 -m venv .venv<br>source .venv/bin/activate<br># Install required packages<br>pip install huggingface_hub hf_transfer<br># Create download script<br>cat &lt;&lt; EOF &gt; dwnmodel.py<br># pip install huggingface_hub hf_transfer<br>import os # Optional for faster downloading<br>os.environ[&quot;HF_HUB_ENABLE_HF_TRANSFER&quot;] = &quot;1&quot;<br><br>from huggingface_hub import snapshot_download<br>snapshot_download(<br>  repo_id = &quot;unsloth/DeepSeek-R1-GGUF&quot;,<br>  local_dir = &quot;DeepSeek-R1-GGUF&quot;,<br>  allow_patterns = [&quot;*UD-IQ1_S*&quot;], # Select quant type UD-IQ1_S for 1.58bit<br>)<br>EOF<br># Download the model<br>python3 dwnmodel.py</pre><p><em>Note: changing allow_patterns = [“*UD-IQ1_S*”] line you can download all the dynamic quantization from</em><a href="https://huggingface.co/unsloth/DeepSeek-R1-GGUF"><em> Unsloth</em></a><em>.</em></p><h4>Running the Model</h4><p><strong>As CLI Interface</strong>:</p><pre>./llama.cpp/llama-cli \<br> --model DeepSeek-R1-GGUF/DeepSeek-R1-UD-IQ1_S/DeepSeek-R1-UD-IQ1_S-00001-of-00003.gguf \<br> --cache-type-k q4_0 \<br> --threads 12 -no-cnv --prio 2 \<br> --n-gpu-layers 62 \<br> --temp 0.6 \<br> --ctx-size 8192 \<br> --seed 3407 \<br> --prompt &quot;&lt;｜User｜&gt;Create a Flappy Bird game in Python.&lt;｜Assistant｜&gt;&quot;</pre><p>Key parameters explained:</p><ol><li>n-gpu-layers 62: offloads all model’s 62 layers to GPU — adjust lower if you have limited GPU memory.</li><li>cache-type-k q4_0: uses 4-bit quantization for the KV cache</li><li>temp 0.6: temperature setting recommended for DeepSeek R1</li><li>ctx-size 8192: sets context window size</li><li>The prompt format `&lt;｜User｜&gt;…&lt;｜Assistant｜&gt;` is specific to <a href="https://github.com/deepseek-ai/DeepSeek-R1/blob/main/DeepSeek_R1.pdf">DeepSeek R1’s tokenizer</a></li></ol><p><strong>As Server:</strong></p><pre>  ./llama.cpp/llama-server \<br>    --model DeepSeek-R1-GGUF/DeepSeek-R1-UD-IQ1_S/DeepSeek-R1-UD-IQ1_S-00001-of-00003.gguf \<br>    --cache-type-k q4_0 \<br>    --threads 12 --prio 2 \<br>    --n-gpu-layers 100 \<br>    --ctx-size 8192</pre><p><em>Note: The server version uses ` — n-gpu-layers 100` to maximize GPU utilization for concurrent requests. This works because the model has fewer than 100 layers, so it effectively offloads all layers to GPU.</em></p><p>Test the server with a simple curl command:</p><pre>curl - request POST \<br> - url http://localhost:8080/completion \<br> - header &quot;Content-Type: application/json&quot; \<br> - data &#39;{&quot;prompt&quot;: &quot;&lt;｜User｜&gt;How much is 2*2&lt;｜Assistant｜&gt;&quot;}&#39;</pre><h3>Performance Considerations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JI3-3fLtGDXoW2aaGzUs4w.png" /><figcaption>Memory consumption of NVIDIA L40S GPUs running DeepSeek R1 1.58-bit quantized model with full layer offloading to VRAM</figcaption></figure><p>On the g6e.12xlarge with 1.58-bit quantization, you can expect: ~20/25 tokens/second throughput</p><p>While this is less performant than the full model running on p5e instances, there are several optimization paths available:</p><ol><li><strong>Less Aggressive Quantization</strong>: You can use the 1.73-bit or 2.22-bit quantized versions, which offer better performance at the cost of more memory usage. This might require offloading more layers to CPU but could provide better quality outputs.</li><li><strong>Instance Upgrade</strong>: Consider using a g6e.48xlarge ($30.131/hour) which is still significantly cheaper (64%) than a p5en.48xlarge ($84.8/hour). This allows you to:<br>- Handle larger batch sizes<br>- Run higher-precision quantized versions<br>- Achieve better throughput</li></ol><p>Here’s a quick cost-performance comparison (AWS region us-west-1):</p><ul><li>p5en.48xlarge (full model): $84.8/hour</li><li>g6e.48xlarge (2.51-bit): $30.131/hour (-64% full model as reference)</li><li>g6e.12xlarge (1.58-bit): $10.493/hour (-87% full model as reference)</li></ul><p>The impact of dynamic quantization on model performance compared to the full version running on p5e instances is still being investigated by the community. While we know there’s some degradation in reasoning capabilities, Unsloth, <a href="https://unsloth.ai/blog/deepseekr1-dynamic">in their dynamic quantization blogpost</a>, suggests the following quality table:</p><pre>MoE Bits    Disk Size    Type        Quality<br>------------------------------------------- <br>1.58-bit    131GB        IQ1_S       Fair<br>1.73-bit    158GB        IQ1_M       Good<br>2.22-bit    183GB        IQ2_XXS     Better<br>2.51-bit    212GB        Q2_K_XL     Best</pre><p>The optimal configuration will depend on your specific use case, balancing between:</p><ul><li>Cost constraints</li><li>Required inference speed</li><li>Acceptable quality threshold</li><li>Batch processing needs</li></ul><h4><strong>Distilled vs Quantized</strong></h4><p>Recent testing by <a href="https://medium.com/u/575230725d27">Massimiliano Angelino</a> has revealed interesting comparisons between different versions:</p><ol><li><strong>Distilled vs Quantized</strong>: the <a href="https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Llama-70B">R1-Distill-Llama-70B</a> shows superior performance compared to the 1.58-bit quantized version in many tasks, while being more resource-efficient;</li><li><strong>Single GPU Option</strong>: for maximum cost efficiency, the R1-Distill-Llama-70B can run with 4-bit quantization on a single GPU. Using a g6e.xlarge instance ($1.861/hour) becomes a viable option for smaller deployments;</li><li><strong>Amazon Bedrock</strong>: the R1-Distill-Llama-70B <a href="https://aws.amazon.com/it/blogs/machine-learning/deploy-deepseek-r1-distilled-llama-models-with-amazon-bedrock-custom-model-import/">can be deployed on Amazon Bedrock through custom model import</a>, enabling serverless inference with pay-per-token pricing model.</li></ol><p>This suggests that for many use cases, especially where cost is a primary concern, the distilled version might be a better choice than running the quantized full model. Consider your specific needs:</p><ul><li>Need maximum reasoning power? Use the 2.51-bit quantized version on g6e.48xlarge for best quality/cost ratio</li><li>Want balanced performance? Go with the 1.58-bit quantized version on g6e.12xlarge</li><li>Looking for cost efficiency? Consider R1-Distill-Llama-70B on smaller instances</li><li>Need serverless flexibility? Deploy the distilled version on Amazon Bedrock with pay-per-token pricing</li></ul><p>For a comprehensive guide on deploying distilled versions on AWS services including SageMaker and Bedrock, check out <a href="https://medium.com/u/f80b5968183d">Davide Gallitelli</a>’s detailed <a href="https://dgallitelli95.medium.com/deepseek-r1-on-aws-70c1c4b692f3">post on Medium</a>.</p><h3>Conclusion and Next Steps</h3><p>Running DeepSeek R1 do not always requires expensive specialized hardware. Through dynamic quantization, we can deploy this powerful model on more accessible hardware while maintaining much of its reasoning capabilities.</p><p>The trade-off between cost and performance makes this approach particularly attractive for:<br>- Development and testing<br>- Small to medium-scale deployments<br>- Projects with an initial limited budget</p><h4>Looking Ahead: SageMaker Text Generation Inference</h4><p>While the EC2 deployment detailed above works well, managing high availability, scaling, and infrastructure can be challenging. Once Text Generation Inference (TGI) support becomes available for DeepSeek R1’s quantized versions, deploying on Amazon SageMaker will offer significant advantages:</p><ul><li>Automatic scaling and high availability</li><li>Built-in monitoring and logging</li><li>Simplified deployment and updates</li><li>Cost optimization through automatic scaling</li><li>Integration with AWS security features</li></ul><p>While we wait for official TGI support, the EC2 deployment remains a viable solution for testing and development. For production workloads, consider watching for TGI compatibility announcements to leverage SageMaker’s managed infrastructure.</p><h3>Acknowledgments</h3><p>This post wouldn’t be possible without the groundbreaking work by Unsloth AI. Their research and open-source contributions in dynamic quantization have made DeepSeek R1 accessible to a much wider audience. Their detailed analysis of the model architecture and innovative quantization approach, shared openly through their <a href="https://unsloth.ai/blog/deepseekr1-dynamic">blog post</a> and <a href="https://github.com/unslothai/unsloth">GitHub repository</a>, exemplifies the collaborative spirit of the AI community.</p><p>If you find this deployment useful, consider to check out their other optimization work.</p><p>I want to thank lot <a href="https://medium.com/u/575230725d27">Massimiliano Angelino</a> for his work on the Ollama integration and performance analysis of different R1 versions</p><h3>Personal Thoughts</h3><p>As someone who works extensively with large language models, I find this democratization of access to cutting-edge AI technology incredibly exciting. While there are certainly use cases that require the full model’s performance, having a cost-effective alternative opens up numerous possibilities for innovation and experimentation.</p><p>If you’re as passionate about generative AI as I am and want to dive deeper into these topics, feel free to connect with me on <a href="https://www.linkedin.com/in/francesco-cerizzi/">LinkedIn</a>. I’m always excited to discuss AI innovations and share experiences with fellow developers and architects.</p><h3>General Disclaimer</h3><p>This post is intended for demonstration and educational purposes only. The implementation shown is not designed for production use without further modifications and hardening. Before deploying to a production environment, ensure you:</p><p>- Conduct thorough testing<br>- Perform security assessments<br>- Implement proper error handling<br>- Optimize based on your specific requirements<br>- Follow AWS and industry best practices</p><p>The opinions expressed in this article are my personal views and do not necessarily represent the views of AWS or any other organization.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0732558747ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Evolution of AWS Generative AI: Key Announcements from re:Invent 2024 (part 1/N)]]></title>
            <link>https://medium.com/@cerizzi/the-evolution-of-aws-generative-ai-key-announcements-from-re-invent-2024-part-1-n-34e1c8a85af7?source=rss-662295d90155------2</link>
            <guid isPermaLink="false">https://medium.com/p/34e1c8a85af7</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[technology-news]]></category>
            <category><![CDATA[genai]]></category>
            <dc:creator><![CDATA[Francesco Cerizzi]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 00:58:15 GMT</pubDate>
            <atom:updated>2024-12-03T00:58:15.046Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4YYbYKzvkXQIPFt68QvSQ.png" /><figcaption>Image from Amazon Bedrock Stable Diffusion 3 Ultra</figcaption></figure><p>AWS re:Invent is running and we are starting to see a wave of groundbreaking Generative AI innovations, marking significant advancements in enterprise AI capabilities. In this series I’ll dive deep into these announcements trying to give a comprehensive and personal view of what is revealed in the Generative AI space.</p><p>I’m attending the AWS re:Invent 2024 so if you would like to discuss in person about Generative AI or you’re as passionate about generative AI as I am and want to dive deeper into these topics, feel free to connect with me on <a href="https://www.linkedin.com/in/francesco-cerizzi/">LinkedIn</a>.</p><h4>RAG Improvements</h4><p>Amazon Bedrock’s Knowledge Bases has undergone a remarkable transformation with four major enhancements that significantly improve RAG applications.</p><p><strong>Binary Vector Embeddings</strong><br>The introduction of binary vector embeddings represents a strategic shift in RAG architecture, offering enhanced storage efficiency and computational speed. This feature converts document embeddings into binary vectors (0s and 1s), dramatically reducing storage requirements while maintaining acceptable precision levels.</p><p><em>Learn more: </em><a href="https://aws.amazon.com/about-aws/whats-new/2024/11/amazon-bedrock-knowledge-bases-binary-vector-embeddings-rag-applications/"><em>https://aws.amazon.com/about-aws/whats-new/2024/11/amazon-bedrock-knowledge-bases-binary-vector-embeddings-rag-applications/</em></a></p><p><strong>Streaming Responses</strong><br>The new RetrieveAndGenerateStream API eliminates the traditional waiting time for complete responses. Instead of waiting for the entire processing pipeline, responses now stream as they’re generated, significantly improving user experience and application responsiveness.</p><p><em>Learn more: </em><a href="https://aws.amazon.com/about-aws/whats-new/2024/12/amazon-bedrock-knowledge-bases-streaming-retrieveandgeneratestream-api/"><em>https://aws.amazon.com/about-aws/whats-new/2024/12/amazon-bedrock-knowledge-bases-streaming-retrieveandgeneratestream-api/</em></a></p><p><strong>Reranking Revolution</strong><br>The new Rerank API addresses a critical challenge in RAG applications — result relevance. By implementing sophisticated reranking models, the system can now better understand user intent and prioritize the most relevant content, optimizing both accuracy and cost-effectiveness.</p><p><em>Learn more: </em><a href="https://aws.amazon.com/about-aws/whats-new/2024/12/amazon-bedrock-rerank-api-accuracy-rag-applications/"><em>https://aws.amazon.com/about-aws/whats-new/2024/12/amazon-bedrock-rerank-api-accuracy-rag-applications/</em></a></p><p><strong>Intelligent Query Filtering</strong><br>Perhaps, in my personal option, the most innovative addition is the auto-generated query filters feature. This system automatically interprets query context to apply relevant filters, eliminating the need for complex manual filter expressions.</p><p><em>Learn more: </em><a href="https://aws.amazon.com/about-aws/whats-new/2024/12/amazon-bedrock-knowledge-bases-auto-generated-query-filters-improved-retrieval/"><em>https://aws.amazon.com/about-aws/whats-new/2024/12/amazon-bedrock-knowledge-bases-auto-generated-query-filters-improved-retrieval/</em></a></p><h4>Advanced AI Orchestration and Prompting</h4><p>AWS has introduced significant improvements to how developers can interact with and control AI models. These enhancements focus on simplifying complex workflows while providing greater flexibility in how AI agents process and respond to tasks.</p><p><strong>Custom Agent Orchestration</strong><br>Bedrock Agents now support flexible orchestration patterns beyond the traditional ReACT framework. This allows developers to implement custom reasoning patterns and specialized workflows using AWS Lambda, opening new possibilities for complex AI applications.</p><p><em>Learn more: </em><a href="https://aws.amazon.com/about-aws/whats-new/2024/11/amazon-bedrock-agents-custom-orchestration/"><em>https://aws.amazon.com/about-aws/whats-new/2024/11/amazon-bedrock-agents-custom-orchestration/</em></a></p><p><strong>Prompt Optimization</strong><br>The new prompt optimization feature automatically refines prompts for various foundation models, including Claude and Llama 3 variants. This ensures optimal model performance without extensive prompt engineering expertise.</p><p><em>Learn more: </em><a href="https://aws.amazon.com/about-aws/whats-new/2024/11/prompt-optimization-preview-amazon-bedrock/"><em>https://aws.amazon.com/about-aws/whats-new/2024/11/prompt-optimization-preview-amazon-bedrock/</em></a></p><h4>Cost-Effective Model Deployment</h4><p>As organizations scale their AI implementations, cost optimization becomes increasingly critical. AWS has responded with two game-changing features that fundamentally improve how models can be deployed and managed in production environments.</p><p><strong>Scale to Zero Inference<br></strong>In a significant move toward cost optimization, SageMaker now supports scaling inference endpoints to zero instances during periods of inactivity. This feature automatically manages capacity based on actual usage, potentially reducing inference costs dramatically for workloads with intermittent traffic patterns.</p><p><em>Learn more: </em><a href="https://aws.amazon.com/about-aws/whats-new/2024/11/amazon-sagemaker-scale-down-zero-ai-inference-save-costs/"><em>https://aws.amazon.com/about-aws/whats-new/2024/11/amazon-sagemaker-scale-down-zero-ai-inference-save-costs/</em></a></p><p><strong>Multi-Adapter Innovation</strong><br>SageMaker’s multi-adapter inference capability represents a breakthrough in model deployment efficiency. Organizations can now host hundreds of LoRA adapters behind a single endpoint, switching between them in milliseconds.</p><p><em>Learn more: </em><a href="https://aws.amazon.com/about-aws/whats-new/2024/11/amazon-sagemaker-multi-adapter-model-inference/"><em>https://aws.amazon.com/about-aws/whats-new/2024/11/amazon-sagemaker-multi-adapter-model-inference/</em></a></p><h4>Enterprise AI Integration</h4><p>Making AI accessible and practical for everyday business use is crucial for widespread adoption. These new features bring AI capabilities directly into users’ workflows while enhancing the ability to understand and process various types of business content.</p><p><strong>Amazon Q Browser Extension</strong><br>The release of Amazon Q Business as a browser extension marks a significant step in AI accessibility. This new integration brings AI assistance directly into users’ daily workflows through their web browsers, eliminating the need to switch between different applications or interfaces. For enterprise users, this means having immediate access to AI capabilities while browsing internal documentation, working on AWS Console, or accessing other web-based resources.</p><p><em>Learn more: </em><a href="https://aws.amazon.com/about-aws/whats-new/2024/11/amazon-q-business-browser-extension/"><em>https://aws.amazon.com/about-aws/whats-new/2024/11/amazon-q-business-browser-extension/</em></a></p><p><strong>Visual Understanding Capabilities<br></strong>Adding to Q’s capabilities, the new visual understanding feature enables Q to analyze and extract insights from diagrams, charts, and other visual elements within documents. This advancement significantly improves Q’s ability to comprehend and assist with technical documentation, architectural diagrams, and visual business data.</p><p><em>Learn more: </em><a href="https://aws.amazon.com/about-aws/whats-new/2024/12/amazon-q-business-extract-insights-visual-elements-documents"><em>https://aws.amazon.com/about-aws/whats-new/2024/12/amazon-q-business-extract-insights-visual-elements-documents</em></a></p><h3>Looking Ahead</h3><p>These announcements represent just the beginning of what promises to be an exciting re:Invent 2024. The improvements in RAG capabilities, agent orchestration, and model deployment efficiency demonstrate AWS’s commitment to making enterprise AI more accessible, efficient, and powerful.</p><p>What particularly excites me is how these features address real-world challenges in AI implementation. The binary vector embeddings and multi-adapter innovations show a clear focus on cost optimization, while improvements in knowledge base functionality and Amazon Q demonstrate a push toward more intuitive AI interactions.</p><p>Stay tuned for more updates in this series as re:Invent 2024 continues. I’ll be sharing more insights about new announcements here and on Linkedin, deep dives into specific features, and practical implications for enterprise AI implementations.</p><p>Got questions or want to discuss these innovations? I’m at re:Invent this week — feel free to reach out on LinkedIn or drop a comment below. Let’s explore how these new capabilities can transform your AI initiatives.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34e1c8a85af7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing AWS Multi-Agent Orchestrator: The Symphony of AI Agents ]]></title>
            <link>https://medium.com/@cerizzi/introducing-aws-multi-agent-orchestrator-the-symphony-of-ai-agents-41a6a87de927?source=rss-662295d90155------2</link>
            <guid isPermaLink="false">https://medium.com/p/41a6a87de927</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Francesco Cerizzi]]></dc:creator>
            <pubDate>Tue, 19 Nov 2024 17:38:47 GMT</pubDate>
            <atom:updated>2025-05-05T15:04:37.396Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yNUFkAOPlA-b9InHAA2YSw.png" /><figcaption>Image from Amazon Bedrock Stable Diffusion 3 Ultra</figcaption></figure><p>In this article I would like to share my thoughts on a new groundbreaking framework for multi agent orchestrator by AWS, that will change how we think about AI agent orchestration into AWS – but not only. <a href="https://github.com/awslabs/agent-squad">The Multi-Agent Orchestrator</a> framework represents AWS’s first venture into the multi-agent space, and it’s packed with features that make it a game-changer for AI development. Moreover, it supports <em>both </em>Python and TypeScript; in this article we’ll provide examples in both languages.</p><h3>Why Another Multi-Agent Framework?</h3><p>In today’s AI landscape, we’re moving beyond the “one model fits all” approach. While having a powerful LLM is great, the real magic happens when you combine specialized agents — each an expert in its domain. Think of it as assembling a team of experts rather than relying on a single generalist.</p><h4>The Orchestra of AI: How It Works</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qTxvDR1bKk0Ac3w0.jpg" /><figcaption><a href="https://awslabs.github.io/multi-agent-orchestrator/general/how-it-works/">https://awslabs.github.io/multi-agent-orchestrator/general/how-it-works/</a></figcaption></figure><p>At its heart, the Multi-Agent Orchestrator works like a sophisticated symphony conductor. It all starts with when a user sends a request:</p><ol><li>The Classifier (our conductor) analyzes it using an LLM, considering:<br>- The user’s current request;<br>- Available agents’ descriptions;<br>- Complete conversation history;<br>- Current session context.</li></ol><p>2. Based on this analysis, it routes the request to the most suitable agent.</p><p>3. The chosen agent processes the request using automatically its own conversation context, not the whole message history.</p><p>4. The response is delivered back while the conversation history is automatically saved.</p><p>What makes this special? <strong>The Classifier has a global view, but agents only see their own conversation threads</strong> — just like musicians in an orchestra focusing on their parts while the conductor sees the whole score.</p><h3>Stunning Features That Make This Framework Shine ✨</h3><p>When exploring a new framework, certain features make you stop and think, “<em>Wow, they really thought this through</em>.” The Multi-Agent Orchestrator has several of these moments. Let’s dive into them!</p><h4>The Power of Flexible Agents</h4><p>Here’s where things starts to get interesting. Each agent can be powered by different models and deployed anywhere.</p><p>The Multi-Agent Orchestrator <a href="https://awslabs.github.io/multi-agent-orchestrator/agents/overview/">provides a set of pre-built agents</a> powered by different services. Currently, the framework already includes agents for:</p><ul><li>Bedrock LLM Agent: supports Amazon Bedrock models with built-in Guardrails and tool use capabilities;</li><li>Amazon Bedrock Agent: is a specialized agent class in the Multi-Agent Orchestrator that integrates directly with Amazon Bedrock agents;</li><li>Lex Bot Agent: integrates with Amazon Lex bots;</li><li>Lambda Agent: enables connections to other services (like Amazon SageMaker endpoints);</li><li>Chain Agent: it allows for the sequential execution of multiple agents. It processes a request by passing the output of one agent as input to the next, creating a chain of agent interactions;</li><li>Comprehend Filter Agent: it uses <a href="https://aws.amazon.com/comprehend/?nc1=h_ls">Amazon Comprehend</a> to analyze and filter content based on sentiment, Personally Identifiable Information (PII), and toxicity.</li></ul><p>But not only!<br>The framework is designed to be extensible — you can create custom agents to integrate with any additional service or system you need.</p><p>Whether you’re using cloud services or custom implementations, the framework provides a unified way to orchestrate them all while optimizing for both performance and cost.</p><pre>import { <br>  MultiAgentOrchestrator,<br>  BedrockLLMAgent,<br>  ComprehendFilterAgent,<br>  ComprehendFilterAgentOptions,<br>  ChainAgent<br>} from &quot;multi-agent-orchestrator&quot;;<br><br>// log of the orchestrator, later in the post we are going to talk about it<br>const orchestrator = new MultiAgentOrchestrator({<br>  config: {<br>    LOG_AGENT_CHAT: true,<br>    LOG_CLASSIFIER_CHAT: true,<br>    LOG_CLASSIFIER_RAW_OUTPUT: false,<br>    LOG_CLASSIFIER_OUTPUT: true,<br>    LOG_EXECUTION_TIMES: true,<br>  }<br>});<br><br>// Create a ComprehendFilterAgent<br>const options: ComprehendFilterAgentOptions = {<br>  name: &#39;AdvancedContentModerator&#39;,<br>  description: &#39;Advanced content moderation with custom settings&#39;,<br>  region: &#39;us-west-2&#39;,<br>  enableSentimentCheck: true,<br>  enablePiiCheck: true,<br>  enableToxicityCheck: true,<br>  sentimentThreshold: 0.8,<br>  toxicityThreshold: 0.6,<br>  allowPii: false,<br>  languageCode: &#39;en&#39;<br>};<br><br>const filterAgent = ComprehendFilterAgent(options)<br><br>// Create a BedrockLLMAgent (or any other agent you want to use after filtering)<br>const llmAgent = new BedrockLLMAgent({<br>  name: &#39;LLMProcessor&#39;,<br>  description: &#39;Extract topics for writing something&#39;,<br>  streaming: true<br>});<br><br>// Create a ChainAgent that combines the filter and LLM agents<br>const chainAgent = new ChainAgent({<br>  name: &#39;FilteredLLMChain&#39;,<br>  description: &#39;Chain that filters content before processing with LLM&#39;,<br>  agents: [filterAgent, llmAgent]<br>});<br><br>orchestrator.addAgent(chainAgent);<br><br>orchestrator.addAgent(<br>  new BedrockLLMAgent({<br>    name: &quot;Medium writing Agent&quot;,<br>    description: &quot;Specializes in writing Medium articles with given topics&quot;,<br>  })<br>);<br><br>orchestrator.addAgent(<br>  new BedrockLLMAgent({<br>    name: &quot;Blog writing agent&quot;,<br>    description: &quot;Specializes in writing blogposts with given topics&quot;,<br>    streaming: true<br>  })<br>);</pre><h4>Smart Routing Patterns</h4><p>Using the framework you can create some sophisticated routing patterns:</p><ol><li><a href="https://awslabs.github.io/multi-agent-orchestrator/cookbook/patterns/cost-efficient/">Cost-Efficient Routing</a>, it routes queries based on complexity:<br>- Simple queries → cheaper models;<br>- Complex tasks → specialized models;<br>- Automatic optimization based on task requirements.</li></ol><pre>import { <br>  LambdaAgent,<br>  BedrockLLMAgent,<br>} from &quot;multi-agent-orchestrator&quot;;<br><br>// Cost-optimized setup example<br>const agents = [<br> // Basic queries using Mistral<br> new BedrockLLMAgent({<br> name: &quot;Basic&quot;,<br> modelId: &quot;meta.llama3-2-3b-instruct-v1:0&quot;,<br> description: &quot;Handles simple queries&quot;,<br> streaming: true<br> }),<br> <br> // Complex tasks using Claude<br> new BedrockLLMAgent({<br> name: &quot;Expert&quot;,<br> modelId: &quot;anthropic.claude-3-5-sonnet-20241022-v2:0&quot;,<br> description: &quot;Handles complex analysis&quot;<br> }),<br> <br> // Custom ML model via Lambda<br> new LambdaAgent({<br> name: &quot;Math Guru&quot;,<br> functionName: &quot;calculator-agent&quot;,<br> description: &quot;Handles math analysis&quot;<br> // parsing for the lambda agent omitted<br> })<br>];</pre><p>2. <a href="https://awslabs.github.io/multi-agent-orchestrator/cookbook/patterns/multi-lingual/">Multi-lingual Support</a>: handles multiple languages seamlessly</p><pre>import { <br>  BedrockLLMAgent,<br>} from &quot;multi-agent-orchestrator&quot;;<br><br>// Multi-lingual configuration<br>new BedrockLLMAgent({<br> name: &quot;French-Expert&quot;,<br> modelId: &quot;anthropic.claude-3-sonnet&quot;,<br> description: &quot;Complex French queries&quot;,<br> streaming: true<br>})</pre><h4>Built-in Monitoring and Analysis</h4><p>One of the framework’s standout features is its sophisticated monitoring and analysis capabilities right out of the box.</p><p><strong>Comprehensive Logging</strong></p><p>The framework provides <a href="https://awslabs.github.io/multi-agent-orchestrator/cookbook/monitoring/logging/">flexible logging</a> that can be tailored to your needs. It provides a default logger based on standard output but you can override the default logger with any custom logging solution.</p><p>Here an example in a AWS Lambda using the AWS Lambda Powertools package:</p><pre>import { Logger } from &quot;@aws-lambda-powertools/logger&quot;;<br>import { <br>  MemoryStorage,<br>  MultiAgentOrchestrator<br>} from &#39;multi-agent-orchestrator&#39;;<br><br>const logger = new Logger({<br>  logLevel: &quot;INFO&quot;,<br>  serviceName: &quot;MyOrchestratorService&quot;<br>});<br><br>const memoryStorage = new MemoryStorage.InMemoryChatStorage();<br><br>const orchestrator = new MultiAgentOrchestrator({<br>  storage: memoryStorage,<br>  config: {<br>    LOG_AGENT_CHAT: true,<br>    LOG_CLASSIFIER_CHAT: true,<br>    LOG_CLASSIFIER_RAW_OUTPUT: true,<br>    LOG_CLASSIFIER_OUTPUT: true,<br>    LOG_EXECUTION_TIMES: true,<br>  },<br>  logger: logger,<br>});</pre><p>This setup gives you visibility into:</p><ul><li>Agent interactions;</li><li>Classifier decisions;</li><li>Raw and processed outputs;</li><li>Performance metrics;</li><li>Execution timings.</li></ul><p><strong>Agent Overlap Analysis</strong></p><p>A <em>standout</em> monitoring feature is the <a href="https://awslabs.github.io/multi-agent-orchestrator/cookbook/monitoring/agent-overlap/">Agent Overlap Analysis tool</a>. Think of it as a quality control system for your agent configurations.</p><pre>import { <br>  AgentOverlapAnalyzer,<br>  BedrockLLMAgent<br>} from &#39;multi-agent-orchestrator&#39;;<br><br><br>const agents = {<br> finance: new BedrockLLMAgent({<br>   name: &quot;Finance Agent&quot;,<br>   modelId: &quot;meta.llama3-2-3b-instruct-v1:0&quot;,<br>   description: &quot;Handles financial queries and calculations&quot;,<br>   streaming: true<br>   }),<br> <br> tech: new BedrockLLMAgent({<br>   name: &quot;Tech Support&quot;,<br>   modelId: &quot;anthropic.claude-3-5-sonnet-20241022-v2:0&quot;,<br>   description: &quot;Provides technical support and troubleshooting&quot;<br>   }),<br> <br> hr: new BedrockLLMAgent({<br>   name: &quot;HR Assistant&quot;,<br>   description: &quot;Assists with human resources tasks and queries&quot;<br>   })<br>  };<br><br>const analyzer = new AgentOverlapAnalyzer(agents);<br>analyzer.analyzeOverlap();</pre><p>The analyzer provides:</p><ol><li>Pairwise Overlap Results</li></ol><pre>Pairwise Overlap Results:<br>_________________________<br><br>finance - tech:<br>- Overlap Percentage - 15.23%<br>- Potential Conflict - Medium<br><br>finance - hr:<br>- Overlap Percentage - 8.75%<br>- Potential Conflict - Low<br><br>tech - hr:<br>- Overlap Percentage - 12.10%<br>- Potential Conflict - Medium</pre><p>2. Uniqueness Scores</p><pre>Uniqueness Scores:<br>_________________<br><br>Agent: finance, Uniqueness Score: 89.55%<br>Agent: tech, Uniqueness Score: 86.32%<br>Agent: hr, Uniqueness Score: 91.20%</pre><p>This analysis helps you:</p><ul><li>Identify redundant agent roles;</li><li>Detect potential routing conflicts;</li><li>Ensure each agent has a distinct purpose;</li><li>Optimize your multi-agent setup.</li></ul><p>The framework suggests taking action based on overlap percentages:</p><ul><li><strong>High Overlap (&gt;30%)</strong>: Refine agent descriptions;</li><li><strong>Medium Overlap (10–30%)</strong>: Review if overlap is intentional;</li><li><strong>Low Overlap (&lt;10%)</strong>: Generally good, but verify coverage.</li></ul><h4>Smart Memory Management</h4><p>The Multi-Agent Orchestrator’s storage system is key to maintaining coherent conversations across multiple interactions. Here’s how it works:</p><p><strong>Conversation Identity</strong><br>Each interaction is uniquely tracked using three identifiers:</p><ul><li>userId: who is having the conversation;</li><li>sessionId: which conversation thread;</li><li>agentId: which agent is involved.</li></ul><p>This allows the system to maintain separate conversation threads while preserving context for each agent.</p><p><strong>Built-in Storage Options</strong></p><p>The framework provides out of the box storage options to handle automatically the user session with it.</p><p>It provides:</p><ol><li>In-Memory Storage: which is perfect for development and prototyping, it is fast, efficient and, it resets when the application restarts;</li><li>DynamoDB Storage (by far my favorite): it gives you automatically a memory which relies on all the Amazon DynamoDB features such as limitless scalability, efficiency, velocity. Basically the perfect storage option for a production-ready application.</li></ol><p><strong>Custom Storage Integration</strong></p><p>Need a different storage solution? The framework allows you to implement a custom storage solution simply by implementing the ConversationStorage interface.</p><h3>Let’s Build Something! A Quick Tutorial</h3><p>Want to try it out? Let’s create a simple multi-agent system:</p><h4>(Optional) Configuring Your Local AWS Profile</h4><p>If you haven’t set up your AWS profile locally yet, here’s a quick guide:</p><p><strong>1. Install the AWS CLI</strong></p><p>Follow the instructions on the official <a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">AWS CLI installation page</a>.</p><p><strong>2. Configure your AWS profile</strong></p><p><a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-examples">Follow the official AWS instructions here.</a></p><p>Remember to keep your AWS credentials secure and never share them publicly.</p><h4><strong>Let’s set up your environment:</strong></h4><p>On MacOS or Linux:</p><pre>mkdir test_multi_agent_orchestrator<br>cd test_multi_agent_orchestrator<br>python3.12 -m venv .venv # or python<br>source .venv/bin/activate<br>pip3 install multi-agent-orchestrator # or pip<br>touch app.py</pre><p>On Windows:</p><pre>mkdir test_multi_agent_orchestrator<br>cd test_multi_agent_orchestrator<br>python -m venv .venv<br>.venv\Scripts\activate<br>pip install multi-agent-orchestrator<br>type nul &gt; app.py</pre><p><strong>Creating Our Multi-Agent System</strong></p><p>Open the app.py file created in the above command and add the following import code:</p><pre>import uuid<br>import asyncio<br>import sys<br>from multi_agent_orchestrator.orchestrator import (<br>    BedrockClassifier, <br>    MultiAgentOrchestrator, <br>    OrchestratorConfig, <br>    BedrockClassifierOptions<br>)<br>from multi_agent_orchestrator.agents import (<br>    BedrockLLMAgent,<br>    BedrockLLMAgentOptions,<br>    AgentResponse,<br>    AgentCallbacks<br>)</pre><p><strong>Configuring the Classifier</strong></p><p>We’ll use Claude 3 Haiku for our classifier and then we will configure the orchestrator with comprehensive logging:</p><pre>custom_bedrock_classifier = BedrockClassifier(BedrockClassifierOptions(<br>    model_id=&#39;us.anthropic.claude-3-5-haiku-20241022-v1:0&#39;<br>))<br><br>orchestrator = MultiAgentOrchestrator(<br>    classifier=custom_bedrock_classifier,<br>    options=OrchestratorConfig(<br>        LOG_AGENT_CHAT=True,<br>        LOG_CLASSIFIER_CHAT=True,<br>        LOG_CLASSIFIER_RAW_OUTPUT=True,<br>        LOG_CLASSIFIER_OUTPUT=True,<br>        LOG_EXECUTION_TIMES=True,<br>        MAX_RETRIES=3,<br>        USE_DEFAULT_AGENT_IF_NONE_IDENTIFIED=True,<br>        MAX_MESSAGE_PAIRS_PER_AGENT=10<br>    ))</pre><p><strong>Creating Our Agents</strong></p><p>Let’s implement streaming callbacks and create our specialized agents. Moreover let’s create an async function to handle user requests:</p><pre>class BedrockLLMAgentCallbacks(AgentCallbacks):<br>    def on_llm_new_token(self, token: str) -&gt; None:<br>        print(token, end=&#39;&#39;, flush=True)<br><br># Tech Expert using Claude 3 Sonnet<br>tech_agent = BedrockLLMAgent(BedrockLLMAgentOptions(<br>    name=&quot;Tech Agent&quot;,<br>    streaming=True,<br>    description=&quot;Specializes in technology areas including software development, hardware, AI, \<br>    cybersecurity, blockchain, cloud computing, emerging tech innovations, and pricing/costs \<br>    related to technology products and services.&quot;,<br>    model_id=&quot;anthropic.claude-3-5-sonnet-20241022-v2:0&quot;,<br>    callbacks=BedrockLLMAgentCallbacks()<br>))<br># Blog Writer using Claude 3 Haiku<br>blog_writer_agent = BedrockLLMAgent(BedrockLLMAgentOptions(<br>    name=&quot;Blog Writer Agent&quot;,<br>    streaming=True,<br>    description=&quot;Specializes in writing blogpost on Medium. It writes articles about each topic given the text to write it down&quot;,<br>    model_id=&quot;anthropic.claude-3-5-haiku-20241022-v1:0&quot;,<br>    callbacks=BedrockLLMAgentCallbacks()<br>))<br># Add agents to orchestrator<br>orchestrator.add_agent(tech_agent)<br>orchestrator.add_agent(blog_writer_agent)<br><br>async def handle_request(_orchestrator: MultiAgentOrchestrator, _user_input: str, _user_id: str, _session_id: str):<br>    response: AgentResponse = await _orchestrator.route_request(_user_input, _user_id, _session_id)<br>    print(&quot;\nMetadata:&quot;)<br>    print(f&quot;Selected Agent: {response.metadata.agent_name}&quot;)<br>    if response.streaming:<br>        print(&#39;Response:&#39;, response.output.content[0][&#39;text&#39;])<br>    else:<br>        print(&#39;Response:&#39;, response.output.content[0][&#39;text&#39;])</pre><p><strong>Running the System</strong></p><p>Finally, create the main loop:</p><pre>if __name__ == &quot;__main__&quot;:<br>    USER_ID = &quot;user123&quot; # for test purposes<br>    SESSION_ID = str(uuid.uuid4())<br>    print(&quot;Welcome to the interactive Multi-Agent system. Type &#39;quit&#39; to exit.&quot;)<br>    while True:<br>        user_input = input(&quot;\nYou: &quot;).strip()<br>        if user_input.lower() == &#39;quit&#39;:<br>            print(&quot;Exiting the program. Goodbye!&quot;)<br>            sys.exit()<br>        asyncio.run(handle_request(orchestrator, user_input, USER_ID, SESSION_ID))</pre><h4>Testing It Out</h4><p>Now we are ready to test it out:</p><pre>python3.12 app.py # or python</pre><p>Try these example queries:</p><ol><li>“What are the latest trends in AI?”</li><li>“Write a blog post about the future of quantum computing”</li><li>“Explain the differences between CPU and GPU”</li><li>“Sum up the AI and GPU questions to correlate them”</li></ol><p>The system will automatically route each query to the most appropriate agent — technical queries to the Tech Agent and writing requests to the Blog Writer Agent.</p><pre>You: What are the latest trends in AI?<br>** CLASSIFIED INTENT **<br>INFO:multi_agent_orchestrator.utils.logger:&gt; Text: What are the latest trends in AI?<br>INFO:multi_agent_orchestrator.utils.logger:&gt; Selected Agent: Tech Agent<br>INFO:multi_agent_orchestrator.utils.logger:&gt; Confidence: 0.95<br>** AGENT TECH-AGENT CHAT HISTORY **<br>INFO:multi_agent_orchestrator.utils.logger:&gt; - None -<br><br>Here are some of the most significant current trends in AI:<br>....REST OF ANSWER<br>======================<br><br>You: Write a blog post about the future of quantum computing<br>** CLASSIFIED INTENT **<br>INFO:multi_agent_orchestrator.utils.logger:&gt; Text: Write a blog post about the future of quantum computing<br>INFO:multi_agent_orchestrator.utils.logger:&gt; Selected Agent: Blog Writer Agent<br>INFO:multi_agent_orchestrator.utils.logger:&gt; Confidence: 0.95<br>** AGENT BLOG-WRITER-AGENT CHAT HISTORY **<br>INFO:multi_agent_orchestrator.utils.logger:&gt; - None -<br><br>Here&#39;s a draft blog post for Medium about the future of quantum computing:<br>....REST OF THE BLOGPOST<br>======================<br><br>You: Explain the differences between CPU and GPU<br>** CLASSIFIED INTENT **<br>INFO:multi_agent_orchestrator.utils.logger:&gt; Text: Explain the differences between CPU and GPU<br>INFO:multi_agent_orchestrator.utils.logger:&gt; Selected Agent: Tech Agent<br>INFO:multi_agent_orchestrator.utils.logger:&gt; Confidence: 0.95<br>** AGENT TECH-AGENT CHAT HISTORY **<br>INFO:multi_agent_orchestrator.utils.logger:&gt; 1. USER: What are the latest trends in AI?<br>INFO:multi_agent_orchestrator.utils.logger:&gt; 2. ASSISTANT: Here are some of the most significant current trends in AI:<br><br>....REST OF ANSWER<br>======================<br><br>You: Sum up the AI and GPU questions to correlate them<br>** CLASSIFIED INTENT **<br>INFO:multi_agent_orchestrator.utils.logger:&gt; Text: Sum up the AI and GPU questions to correlate them<br>INFO:multi_agent_orchestrator.utils.logger:&gt; Selected Agent: Tech Agent<br>INFO:multi_agent_orchestrator.utils.logger:&gt; Confidence: 0.95<br>** AGENT TECH-AGENT CHAT HISTORY **<br>INFO:multi_agent_orchestrator.utils.logger:&gt; 1. USER: What are the latest trends in AI?<br>INFO:multi_agent_orchestrator.utils.logger:&gt; 2. ASSISTANT: Here are some of the most significant current trends in AI:<br><br>1. Generative AI &amp; ...<br>INFO:multi_agent_orchestrator.utils.logger:&gt; 3. USER: Explain the differences between CPU and GPU<br>INFO:multi_agent_orchestrator.utils.logger:&gt; 4. ASSISTANT: I&#39;ll break down the key differences between CPUs (Central Processing Units) and ...<br><br>Here&#39;s how AI and GPUs are interconnected, especially in modern computing:<br>....REST OF ANSWER</pre><p>Notice how the Blog Writer Agent maintained its own separate context, while the Tech Agent accumulated relevant history for technology-related queries, shown as “** AGENT TECH-AGENT CHAT HISTORY **” in the logs. This intelligent context management allows each agent to:</p><ul><li>Maintain topic-specific conversation threads;</li><li>Access relevant previous interactions;</li><li>Provide coherent follow-up responses;</li><li>Keep conversations organized by domain;</li></ul><h3>Conclusion and Next Steps</h3><p>Our journey through the Multi-Agent Orchestrator framework has shown how AWS is revolutionizing multi-agent systems. From its intelligent routing to its sophisticated memory management, the framework offers a powerful yet elegant solution for orchestrating AI agents.</p><h4>Key Takeaways</h4><ol><li><em>Intelligent Design</em>: The framework’s conductor-orchestra model ensures efficient query routing while maintaining clean separation of concerns.</li><li><em>Flexible Architecture</em>: Whether you’re using Amazon Bedrock models, Lex bots, or custom implementations, the framework adapts to your needs.</li><li><em>Built for Production</em>: With features like:<br>- DynamoDB integration for scalable storage;<br>- Comprehensive logging;<br>- Agent overlap analysis;<br>- Cost-efficient routing patterns.</li><li><em>Smart Context Management</em>: As we saw in our tutorial, each agent maintains its own conversation history, enabling more coherent and contextually aware interactions.</li></ol><p>The Multi-Agent Orchestrator framework represents a significant step forward in making complex AI systems more manageable, scalable, and production-ready. Whether you’re building a customer service solution, a content generation system, or a complex analytical tool, this framework provides the building blocks for sophisticated AI applications.</p><p>Ready to start building? Check out the <a href="https://awslabs.github.io/multi-agent-orchestrator/">GitHub repository</a> and join the community in shaping the future of multi-agent systems.</p><h4>Personal Thoughts</h4><p>I’m genuinely enthusiastic about where this framework is heading. Features like the overlap analysis tool and the intelligent context management system solve real problems I’ve encountered when building multi-agent systems. It’s refreshing to see a new framework trying to address the challenge of the future: building multi-agent systems</p><p>If you’re as passionate about generative AI as I am and want to dive deeper into these topics, feel free to connect with me on <a href="https://www.linkedin.com/in/francesco-cerizzi/">LinkedIn</a>. I’m always excited to discuss AI innovations and share experiences with fellow developers and architects.</p><p>Ready to start building? Check out the <a href="https://github.com/awslabs/multi-agent-orchestrator">GitHub repository</a> and join the community in shaping the future of multi-agent systems.</p><h3>General Disclaimer</h3><p>This post and all the code examples are intended for demonstration and educational purposes only. The implementations shown are not designed for production use without further modifications and hardening. Before deploying any of these concepts to a production environment, it is crucial to:</p><ul><li>Conduct thorough testing;</li><li>Perform security assessments;</li><li>Implement proper error handling;</li><li>Optimize based on your specific requirements;</li><li>Follow AWS and industry best practices.</li></ul><p>The opinions expressed in this article are my personal views and do not necessarily represent the views of AWS or any other organization.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41a6a87de927" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your AWS Machine Learning Playground: Local Jupyter Notebook with Your AWS Profile]]></title>
            <link>https://medium.com/@cerizzi/your-aws-machine-learning-playground-local-jupyter-notebook-with-your-aws-profile-048eda8e8653?source=rss-662295d90155------2</link>
            <guid isPermaLink="false">https://medium.com/p/048eda8e8653</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sagemaker]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <dc:creator><![CDATA[Francesco Cerizzi]]></dc:creator>
            <pubDate>Tue, 16 Jul 2024 13:05:55 GMT</pubDate>
            <atom:updated>2024-07-16T13:05:55.943Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cyUOD1mz1M16x6qMANLcFg.png" /><figcaption>Image created by myself using Amazon Titan Image Generator</figcaption></figure><p>Have you ever felt frustrated trying to quickly test a new AWS feature or play around with cloud services? Do you find yourself wishing for a simpler way to interact with AWS without the overhead of complex setups? If you’ve nodded along to these questions, you’re not alone. While Amazon SageMaker Studio notebooks are powerful for serious work, sometimes you just want to write a few lines of code to test an API or experiment with a service. That’s where setting up a local environment can be a game-changer.</p><h3>The Challenge of Quick AWS Experimentation</h3><p>AWS role management is a powerful feature, but when you’re just looking to get your hands dirty with services like Amazon Bedrock for generative AI or other AWS offerings using boto3 or the SageMaker SDK, it can feel like overkill. Sure, you could spin up a SageMaker Studio notebook with the right roles, but why go through all that configuration for a few lines of experimental code?</p><h3><strong>The Local Solution: Your AWS Playground</strong></h3><p>The good news is that you can leverage your locally configured AWS profile to create a simple, contained environment for your AWS experiments. Here’s how to set it up:</p><h4>1. Create a Python Virtual Environment</h4><p>This keeps your AWS playground isolated from your system Python installation. Click <a href="https://docs.python.org/3/tutorial/venv.html">here</a> if you want to dive deep onto Python virtual environments.</p><p>On MacOS or Linux:</p><pre>python -m venv .venv<br>source .venv/bin/activate</pre><p>On Windows:</p><pre>python -m venv .venv<br>.venv\Scripts\activate</pre><h4>2. Install Jupyter and Other Dependencies</h4><pre>pip install -U jupyter #and what else (boto3, sagemaker, etc.)</pre><h4>3. Launch Jupyter</h4><pre>jupyter notebook # or &quot;jupyter lab&quot; depending on what you are looking for</pre><p>That’s it! Your Jupyter environment will now use your locally configured AWS profile and its associated permissions. No more worrying about complex role setups for quick tests.</p><p>When you’re done, simply deactivate the virtual environment:</p><pre>deactivate</pre><p>And if you want to start fresh, you can delete the entire virtual environment folder:</p><p>On MacOS or Linux:</p><pre>rm -rf .venv</pre><p>On Windows:</p><pre>rmdir /s /q .venv</pre><h3><strong>(<em>Optional) </em>Configuring Your Local AWS Profile</strong></h3><p>If you haven’t set up your AWS profile locally yet, here’s a quick guide:</p><h4>1. Install the AWS CLI</h4><p>Follow the instructions on the official <a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">AWS CLI installation page</a>.</p><h4>2. Configure your AWS profile</h4><p><a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-examples">Follow the official AWS instructions here.</a></p><p>Remember to keep your AWS credentials secure and never share them publicly.</p><h3>Bonus: Supercharge Your Development with Amazon Q Companion</h3><p>If you want to take your local AWS development to the next level, take into account adding the Amazon Q Companion to your Jupyter setup. Amazon Q is an AI-powered assistant that can help you with code generation and improvement, it can even understand AWS architecture and best practices.</p><p>To add Amazon Q to your Jupyter environment:</p><h4>1. Install the Amazon Q extension for Jupyter Lab</h4><pre>pip install -U amazon-q-developer-jupyterlab-ext</pre><h4>2. Enable the extension</h4><pre>jupyter server extension enable amazon_q_developer_jupyterlab_ext</pre><h4>3. Restart Jupyter Lab</h4><pre>jupyter lab</pre><p>Look for the Amazon Q at the bottom of the window.</p><h4>4. Authenticate yourself with an AWS Builder ID</h4><p>Follow the instruction <a href="https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/jupyterlab-setup.html#jupyterlab-setup-bid">here</a> to start using Amazon Q completely for free. You can access it with your <a href="https://docs.aws.amazon.com/signin/latest/userguide/sign-in-aws_builder_id.html">AWS Builder ID</a>.</p><p>With Amazon Q, you’ll have on-demand access to AWS expertise, code suggestions, and even security vulnerability scanning right in your local development environment.</p><p><em>Note: that not all the Amazon Q features are available today inside Jupyter lab. Use your </em><a href="https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/q-in-IDE.html"><em>favorite IDE</em></a><em> to get access to all of them for free.</em></p><h3><strong>A Note on Performance</strong></h3><p>While this local setup is perfect for quick prototyping and experimentation, it’s worth remembering that for more intensive tasks, Amazon SageMaker Studio notebooks have a <em>significant</em> advantage. Operating inside a SageMaker Studio notebook allows you to upload and download files at the speed of the cloud instance powering that notebook, not limited by your local internet connection. So, use this local setup for <em>fast </em>and <em>simple</em> prototyping, but don’t hesitate to move to SageMaker Studio when you need <em>more computational power</em> or <em>faster data transfer</em> speeds.</p><h3><strong>Conclusion</strong></h3><p>Setting up a local environment for AWS experimentation doesn’t have to be complicated. By leveraging your existing AWS profile and a few simple commands, you can create a powerful playground for testing new AWS features, like the <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/conversation-inference.html">new Converse API in Amazon Bedrock</a> which I personally love. This approach simplifies your workflow, allowing you to focus on coding and experimentation rather than complex configuration. By combining the flexibility of local development with the power of AWS services and tools like Amazon Q, you’re setting yourself up for efficient and enjoyable cloud development. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=048eda8e8653" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying PaliGemma Vision-Language Model on Amazon SageMaker]]></title>
            <link>https://medium.com/@cerizzi/deploying-googles-paligemma-vision-language-model-on-amazon-sagemaker-6e79c42fe68b?source=rss-662295d90155------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e79c42fe68b</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Francesco Cerizzi]]></dc:creator>
            <pubDate>Sat, 18 May 2024 09:57:12 GMT</pubDate>
            <atom:updated>2024-05-20T12:07:33.227Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploying Google’s PaliGemma Vision-Language Model on Amazon SageMaker</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6QnaIJUHS4WVuH7btOWimQ.png" /><figcaption>Image generated by myself</figcaption></figure><p>Three days ago Google announced PaliGemma, a lightweight open <em>vision-language model</em> (VLM) inspired by <a href="https://arxiv.org/abs/2310.09199">PaLI-3</a>, and based on open components like the <a href="https://arxiv.org/abs/2303.15343">SigLIP vision model</a> and the <a href="https://arxiv.org/abs/2403.08295">Gemma language model</a>. PaliGemma takes both images and text as inputs and can answer questions about images with detail and context, meaning that PaliGemma can perform deeper analysis of images and provide useful insights, such as captioning for images and short videos, object detection, and reading text embedded within images.</p><p>In this post, we’ll explore how to deploy the pre-trained Paligemma model on Amazon SageMaker, a fully managed machine learning service from AWS, and create a real-time inference endpoint for testing and integration with your applications.</p><h3>Model Capabilities</h3><p>PaliGemma is a single-turn vision language model not meant for conversational use, and it works best when fine-tuning to a specific use case.</p><p>You can configure the task by conditioning it with prefixes like “detect” or “segment.” The pre-trained models were trained with these prompts to acquire capabilities such as question answering, captioning, and segmentation. However, they are intended as a starting point for fine-tuning on specialized tasks with similar prompts, rather than direct use. For interactive testing, the “mix” family, fine-tuned on a mixture of tasks, is recommended to experience PaliGemma’s versatilities.</p><h3>Deploying Paligemma on Amazon SageMaker</h3><p>To deploy Paligemma on Amazon SageMaker, we’ll be following a Jupyter Notebook that streamlines the entire process. <a href="https://github.com/Cerrix/paligemma_sagemaker_inference_notebooks">Here the full repository code with a fully functional Jupyter notebook</a>.</p><p><a href="https://github.com/Cerrix/paligemma_sagemaker_inference_notebooks">GitHub - Cerrix/paligemma_sagemaker_inference_notebooks: This repository containes the notebook to deploy and run Paligemma on Amazon Sagemaker. It deploys a realtime custom inference endpoint</a></p><h4>Prerequisites</h4><p>Before proceeding with this post, ensure that you have the following prerequisites:</p><p>- An AWS account with appropriate permissions to create and manage SageMaker resources.</p><p>- A Hugging Face account and access token (https://huggingface.co/settings/tokens).</p><p>Let’s dive into the step-by-step guide:</p><h4>Setting up the Environment</h4><p>You need to install the required Python packages:</p><pre>pip install --upgrade huggingface_hub<br>pip install --upgrade sagemaker</pre><p><em>Tip: if you are executing it in a Jupyter Notebook add “!” before the bash command. For example: </em>!pip install --upgrade sagemaker</p><h4><strong>Authenticating with AWS</strong></h4><p>If you are executing it in a Sagemaker Studio notebook you can authenticate with your AWS account by obtaining the SageMaker execution role and default bucket. This step is crucial for SageMaker to have the necessary permissions to create resources:</p><pre>import sagemaker<br>import boto3<br>sess = sagemaker.Session()<br># sagemaker session bucket -&gt; used for uploading data, models and logs<br># sagemaker will automatically create this bucket if it not exists<br>sagemaker_session_bucket=None<br>if sagemaker_session_bucket is None and sess is not None:<br>    # set to default bucket if a bucket name is not given<br>    sagemaker_session_bucket = sess.default_bucket()<br><br>try:<br>    role = sagemaker.get_execution_role()<br>except ValueError:<br>    iam = boto3.client(&#39;iam&#39;)<br>    role = iam.get_role(RoleName=&#39;sagemaker_execution_role&#39;)[&#39;Role&#39;][&#39;Arn&#39;]<br><br>sess = sagemaker.Session(default_bucket=sagemaker_session_bucket)<br><br>print(f&quot;sagemaker role arn: {role}&quot;)<br>print(f&quot;sagemaker bucket: {sess.default_bucket()}&quot;)<br>print(f&quot;sagemaker session region: {sess.boto_region_name}&quot;)</pre><h4>Preparing the Model Directory</h4><p>Now, we create a directory structure to store the PaliGemma model files, the requiremens.txt file and, the custom inference code which are needed to customized the inference in the Amazon Sagemaker container:</p><pre>mkdir code</pre><p><em>Tip: if you are executing it in a Jupyter Notebook add “!” before the bash command. For example: </em>!mkdir code</p><pre>%%writefile code/requirements.txt<br>accelerate<br>bitsandbytes<br>git+https://github.com/huggingface/transformers.git<br>Pillow</pre><pre>%%writefile code/inference.py<br>from transformers import AutoTokenizer, PaliGemmaForConditionalGeneration, PaliGemmaProcessor<br>import torch<br>import base64<br>from io import BytesIO<br>from PIL import Image<br><br>device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br><br>def get_RGB_image_io(image_bytes):<br>    image_io = BytesIO(image_bytes)<br>    image = Image.open(image_io)<br>    resized_image = image.convert(&quot;RGB&quot;)<br>    return resized_image<br><br>def model_fn(model_dir):<br>    model = PaliGemmaForConditionalGeneration.from_pretrained(model_dir, torch_dtype=torch.bfloat16).to(device)<br>    # Load the processor<br>    processor = PaliGemmaProcessor.from_pretrained(model_dir)<br>    return [model, processor]<br><br><br>def predict_fn(data, model_process):<br>    model = model_process[0]<br>    processor = model_process[1]<br>    <br>    # get prompt &amp; image<br>    prompt = data.get(&quot;prompt&quot;, &quot;&quot;)<br>    image_b64=data.get(&quot;image&quot;, &quot;&quot;)<br>    <br>    # decode image from Base64<br>    image_data = base64.b64decode(image_b64)<br>    input_image = get_RGB_image_io(image_data)<br><br>    inputs = processor(text=prompt, images=input_image, padding=&quot;longest&quot;, do_convert_rgb=True, return_tensors=&quot;pt&quot;).to(device)<br>    inputs = inputs.to(dtype=model.dtype)<br><br>    with torch.no_grad():<br>        output = model.generate(**inputs, max_length=496)<br>        str_out = processor.decode(output[0], skip_special_tokens=True)<br>    return {&quot;response&quot;: str_out}</pre><p><em>Tip: pin the python dependencies in requirements.txt to have a consistent experience. In this moment we need to download the latest </em><a href="https://huggingface.co/docs/transformers/index"><em>Hugging Face Library Transformers</em></a><em> version to use it with PaliGemma</em></p><h4>Downloading the Model Snapshot</h4><p>Using the Hugging Face snapshot_download function and our access token, we download the PaliGemma wights from the Hugging Face repository. Then, we move the previously created code folder inside the model one:</p><pre>from distutils.dir_util import copy_tree<br>from pathlib import Path<br>from huggingface_hub import snapshot_download<br>import random<br>HF_MODEL_ID=&quot;google/paligemma-3b-mix-224&quot;<br># you need to accept the Gemma terms and conditions at: https://huggingface.co/google/paligemma-3b-mix-224<br>HF_TOKEN=&quot;YOUR_HF_TOKEN&quot; # your hugging face token: https://huggingface.co/settings/tokens<br>assert len(HF_TOKEN) &gt; 0, &quot;Please set HF_TOKEN to your huggingface token. You can find it here: https://huggingface.co/settings/tokens&quot;<br><br># download snapshot<br>snapshot_dir = snapshot_download(repo_id=HF_MODEL_ID,use_auth_token=HF_TOKEN)<br><br># create model dir<br>model_folder_name=f&quot;model-{random.getrandbits(16)}&quot;<br>model_tar = Path(model_folder_name)<br>model_tar.mkdir(exist_ok=True)<br><br># copy snapshot to model dir<br>copy_tree(snapshot_dir, str(model_tar))<br><br># copy code/ to model dir<br>from pathlib import Path<br>copy_tree(&quot;code/&quot;, str(model_tar.joinpath(&quot;code&quot;)))</pre><p><em>Tip: remember to set your HF_TOKEN obtained in the </em><strong><em>Prerequisites </em></strong><em>section of this post.</em></p><h4><strong>Creating a Compressed Model Archive</strong></h4><p>The notebook compresses the model directory into a .tar.gz file, which will be uploaded to Amazon S3 and, it will be used for the container deployment:</p><pre># if you want to use multithreading compression you need pigz. This command installs it on the notebook<br>conda install -y pigz<br><br># multi-threading compression with pigz<br>cd {model_folder_name}; tar cvf model.tar.gz --use-compress-program=pigz ./*<br><br>#move the tar in the current folder<br>mv ./{model_folder_name}/model.tar.gz ./</pre><p><em>Tip 1: pigz is useful for compressing large files using multi-threading. Typically, machine learning models are huge in terms of storage, so compressing them with a single-threaded utility like gzip might be slow. Using pigz, which can utilize multiple CPU cores, can make the compression process orders of magnitude faster.</em></p><p><em>Tip 2: conda is available only in Jupyter Notebook environments, use your OS packet manager to download pigz. If you are executing it in a Jupyter Notebook add “!” before the bash command. For example: </em>!conda install -y pigz</p><h4><strong>Uploading the Model to S3</strong></h4><p>The compressed model archive is then uploaded to an S3 bucket associated with our SageMaker session. This will be loaded inside your inference container later:</p><pre>from sagemaker.s3 import S3Uploader<br><br># upload model.tar.gz to s3<br>s3_model_uri=S3Uploader.upload(local_path=&quot;model.tar.gz&quot;, desired_s3_uri=f&quot;s3://{sess.default_bucket()}/paligemma&quot;)<br><br>print(f&quot;model uploaded to: {s3_model_uri}&quot;)</pre><h4><strong>Deploying the Model to SageMaker</strong></h4><p>Now it is finally time to generate our model endpoint. It will take some minutes to be deployed. The notebook creates a HuggingFaceModel instance and deploys it to a SageMaker endpoint on a ml.g4dn.xlarge instance. This step involves specifying the model data location (the S3 URI generated in the previous step), execution role, and various configuration parameters like instance type and transformers version:</p><pre>from sagemaker.huggingface.model import HuggingFaceModel<br>import datetime<br><br>timestamp = str(datetime.datetime.now()).replace(&quot; &quot;,&quot;-&quot;).replace(&quot;.&quot;,&quot;-&quot;).replace(&quot;:&quot;,&quot;-&quot;)<br><br># create Hugging Face Model Class<br>huggingface_model = HuggingFaceModel(<br>   model_data=s3_model_uri,      # path to your model and script<br>   role=role,                    # iam role with permissions to create an Endpoint<br>   transformers_version=&quot;4.37.0&quot;,  # transformers version used<br>   pytorch_version=&quot;2.1.0&quot;,        # pytorch version used<br>   py_version=&#39;py310&#39;,           # python version used<br>)<br><br># deploy the endpoint<br>predictor = huggingface_model.deploy(<br>    initial_instance_count=1,<br>    instance_type=&quot;ml.g4dn.xlarge&quot;,<br>    endpoint_name=f&quot;paligemma-{timestamp}&quot;<br>    )</pre><h3><strong>Running the Deployed Model</strong></h3><p>Finally, we demonstrate how to send a request to the deployed SageMaker endpoint. The notebook encodes a <a href="https://picsum.photos/id/237/1000">test image</a> (in this case, a dog picture) as base64, includes a textual prompt (“detect dog”) which corresponds to one of the model capabilities, and sends it to the endpoint for inference. The response from the endpoint is then printed, showcasing Paligemma’s object detection capabilities:</p><pre>import base64<br>from PIL import Image<br>from io import BytesIO<br><br># helper decoder<br>def decode_base64_image(image_string):<br>    base64_image = base64.b64decode(image_string)<br>    buffer = BytesIO(base64_image)<br>    return Image.open(buffer)<br><br># content_type = &#39;application/json;jpeg&#39;, endpoint expects payload to be a json with the original image and the mask image as bytes encoded with base64.b64 encoding.<br># To send raw image to the endpoint, you can encoded_image as np.array(PIL.Image.open(input_img_file_name.jpg)).tolist()<br>content_type = &quot;application/json;jpeg&quot;<br><br>input_img_path = &#39;./test.jpg&#39;<br>with open(input_img_path, &quot;rb&quot;) as f:<br>    input_img_image_bytes = f.read()<br><br>encoded_input_image = base64.b64encode(bytearray(input_img_image_bytes)).decode()<br><br>payload = {<br>    &quot;prompt&quot;: &quot;detect dog&quot;,<br>    &quot;image&quot;: encoded_input_image<br>}<br><br>query_response = predictor.predict(data=payload)</pre><p><em>response: ‘&lt;loc0055&gt;&lt;loc0000&gt;&lt;loc1021&gt;&lt;loc0900&gt; dog’. </em><a href="https://huggingface.co/blog/paligemma">In this Hugging Face blog post, you can find details on the model answers based on the task, as well as how to use them.</a></p><h3>Delete the endpoint</h3><p>If you don’t want to incur unnecessary costs, you can delete the model:</p><pre># delete endpoint<br>predictor.delete_endpoint()</pre><h3>Conclusions</h3><p>Throughout the notebook, we dive into important code passages, such as authenticating with AWS, downloading and preparing the model, compressing and uploading the model, deploying the model to SageMaker, and sending inference requests to the deployed endpoint.</p><p>Using Amazon SageMaker you can deploy a <strong><em>private</em></strong> real-time endpoint to take advantage PaliGemma model capabilities. This endpoint allows you to send inference requests to the deployed model and receive predictions in real-time, enabling seamless and private integration with your applications.</p><p>We deploy the PaliGemma model to a ml.g4dn.xlarge instance, which is a cost-effective GPU instance type suitable for running large-scale vision-language models. Amazon SageMaker’s real-time inference endpoints are designed for low-latency, high-throughput inference workloads, making them an ideal choice for deploying and scaling models like Paligemma.</p><p>In conclusion, deploying cutting-edge vision-language models like PaliGemma can be a complex task, but with the help of Amazon SageMaker and the <a href="https://github.com/Cerrix/paligemma_sagemaker_inference_notebooks">provided Jupyter Notebook,</a> the process becomes streamlined and accessible.</p><p>Remember, the notebook focuses on deploying the pre-trained Paligemma model for inference tasks and does not cover fine-tuning or training aspects. If you’re interested in fine-tuning Paligemma for specific tasks, <a href="https://huggingface.co/blog/paligemma">you can refer to the resources mentioned in the Hugging Face blog post</a>.</p><h3><strong>General Disclaimer</strong></h3><p>This post and the associated notebooks are intended for demonstration and educational purposes only. It is not designed for production use without further modifications and hardening. Before deploying this endpoint to a production environment, it is crucial to conduct thorough testing, security assessments, and optimizations based on your specific requirements and best practices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e79c42fe68b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>