[{"href":"/when-are-nims-faster/","title":"When Are NIMs Faster?","subtitle":"What switching to NVIDIA NIMs changed in our timings, our costs and our designs","description":"A Nextflow benchmark compares NVIDIA NIMs and open-source containers on AWS Batch, tracking task time, compute cost and design agreement.","abstract":"A Nextflow benchmark compares NVIDIA NIMs and open-source containers on AWS Batch, tracking task time, compute cost and design agreement.","tags":["Nextflow","AWS","Protein Design","Benchmarking"],"topics":["biomedical-ai","benchmarks","inference"],"authors":["Jelena Pejovic Simeunovic","Patrícia Rocha","Jorge Moura Sampaio","Bojan Jakimovski"],"text":"Abstract Whether NVIDIA NIMs are faster than open-source containers depends on how they are deployed. We built the same PD-L1 workflow twice in Nextflow and ran both versions on AWS Batch. At one design per container, the NIM arm used 12.3% more container time and cost 19.8% more in the compute model, because an OpenFold3 task spent about 100 seconds outside the 12-second model fold. Giving each RFdiffusion and OpenFold3 server 15 designs cut those stages’ time per design about sixfold. The two arms also produced different designs, and network transfer cost twice as much as compute. Deployment decided the result more than the model did. Introduction NVIDIA ships models as NIMs: containers that serve a model behind an HTTP endpoint, with an accelerated inference stack already tuned for their GPUs. NIMs can be chained into full workflows, with examples across industries: fraud detection in finance, video analytics for cities and warehouses, document research for enterprises. NVIDIA publishes many of these chains as blueprints. Teams building a pipeline like this often face the same choice: NIM containers or open-source ones. Does the pipeline get faster and cheaper while retaining accuracy? We put that to the test with a protein binder design workflow, where the goal is to design a new protein that binds specifically to a chosen target. We focused on PD-L1, an immune checkpoint protein that helps several tumors evade immune attack by binding to PD-1 on T cells. Blocking this interaction is an established strategy in cancer immunotherapy. We built the same PD-L1 workflow twice in Nextflow, once with NIM services and once with open-source containers, and ran both on AWS Batch. We got three different answers to the same question. At 20 binders, NIMs looked faster and cheaper. At 150 designs with a matched baseline, the result reversed. When we gave each NIM server 15 designs instead of one, the NIM stages ran about six times faster per design. Same models, same data. What changed each time was the deployment. The sections below describe the pipeline, what did and did not reproduce across the two arms, the timing, quality and cost results, and the batching test. What we built and why Figure 1. PD-L1 binder-design workflow. Both arms share the same Nextflow process graph on AWS Batch. OpenFold3 receives alignments assembled from a precomputed target alignment and the binder query. We built a Nextflow DSL2 workflow to design binders against PD-L1 and compare NVIDIA NIM services with direct model execution in OSS Docker images. Both arms followed the pipeline in Figure 1: RFdiffusion generated backbones, ProteinMPNN designed sequences, thread/relax prepared structures, OpenFold3 predicted complexes, and the same BindCraft scoring workflow evaluated the designs. Nextflow handled dependencies, parallel tasks and retries; AWS Batch ran the GPU and CPU containers. The main comparison generated 150 designs per arm, with 78-residue binders, matched RFdiffusion seeds and identical resource requests at each step. Both arms reused a precomputed PD-L1 alignment and a query-only binder alignment. The MSA step assembled those files; MSA search was outside the benchmark. GPU stages ran on g6e.4xlarge instances, one NVIDIA L40S each. Stage NIM arm Open-source arm RFdiffusion NIM 2.3.0 rfdiffusion-fixed, standalone runner ProteinMPNN NIM 1.2.0 proteinmpnn_dl_binder_design OpenFold3 NIM 1.5.0, patched to emit PAE openfold3:0.5-pixi Reproducibility: what transferred, and what didn’t RFdiffusion — matching the execution stack with agents We used coding agents to adapt a non-NIM Docker image to match NIM’s RFdiffusion execution environment: software versions, CUDA and TensorRT/Warp acceleration. Matching software versions, CUDA and model weights alone was insufficient. By default both images presented the same exact model weights, but different software versions affecting Numpy, Python and CUDA. We adapted all this but binders remained different while passing the same precise input and seed. So identical seeds still produced different backbones until we adapted the code of the non-NIM Docker image to match the TensorRT and Warp acceleration. After this alignment, all 150 paired backbones were byte-identical, with a Cα RMSD of 0.000 Å. This demonstrated that agents can help replicate NIM’s optimized execution stack and that tensor acceleration is part of the model’s generative behavior, even when software versions and weights have been matched. ProteinMPNN — sequences The same control did not carry through sequence generation. ProteinMPNN received identical backbones, checkpoint v_48_002, seed 102 and temperature 1e-6, yet none of the 150 paired sequences matched exactly. Mean sequence identity was 63%. Despite the sequence differences, the predicted 3D structures often remained similar after OpenFold3 folding. The median binder Cα RMSD between NIM and non-NIM was 2.00 Å after superposing the binder chains. The cause of this difference lies in the implementations. At the same seed both arms reproduce their own sequences exactly, so each arm is internally deterministic, but they do not agree with each other. RFdiffusion showed the same pattern, producing different backbones from identical seeds and weights until the execution paths were aligned. Different RFdiffusion backbones would be a much bigger change than different ProteinMPNN sequences for the same backbone (with median 2.00 Å difference), because the two pipelines would be designing for different shapes from the start. Still, a paired comparison has to begin after this step, with both arms folding the same sequences. From ProteinMPNN onward, we were folding and scoring different sequences, so downstream quality comparisons are affected, and matching the binder length at 78 residues controls one workload variable. RFdiffusion and ProteinMPNN ran on identical inputs; from OpenFold3 onward each arm folds its own sequences, which is why the timings that follow are end-to-end for the two workflows. Results: time, quality, cost Time: startup changed the answer At 20 binders, NIMs looked faster and cheaper. Two things in the setup produced that. The baseline ran its MSA search inside the GPU task, paying GPU rates for work the NIM path did on a CPU queue, and matching the execution stacks later added the NIM’s own 52.6-second RFdiffusion warmup to the open-source side, taking that step from 56.6 to 108.4 seconds. Neither was a property of the NIM. At one design per container, the NIM arm used 12.3% more summed container time and cost 19.8% more in the compute model. The NIM tasks were faster at RFdiffusion and ProteinMPNN, but the extra 47.8 seconds at OpenFold3 outweighed those savings. Whole pipeline, one design per container OSS / direct NIM Summed container time per design, all stages 345.6 s 388.2 s Modeled compute cost per design $0.127 $0.152 Elapsed time for 150 designs About 2 h 30 min About 3 h Task time by stage Stage OSS / direct NVIDIA NIM NIM − OSS RFdiffusion 98.0 93.9 −4.2 ProteinMPNN 10.3 6.6 −3.7 Thread / relax 104.7 108.5 +3.8 MSA assembly 0.4 0.4 0.0 OpenFold3 66.5 114.3 +47.8 BindCraft 65.7 64.6 −1.1 Total 345.6 388.2 +42.6 Mean seconds per design at one design per container. The inline bars share a 0–120 s scale. OpenFold3 shows why inference and deployment need separate measurements. Warm, the NIM folds in 12.05 seconds and the direct container in 10.56. Add the server startup around those folds and the same task takes 114.3 seconds against 66.5. Time outside the logged fold accounts for nearly all of the difference. It was also the only stage whose logs separated startup from model work on both sides, so the NIM’s wins at RFdiffusion and ProteinMPNN are full-task wins rather than evidence about inference. Two clocks are in play: summed container time counts work inside the tasks, while elapsed time includes queueing and instance launch and lets tasks overlap. The cost column is modeled from queue rates, not billed. Where OpenFold3 task time went Logged fold Remaining task time OSS / direct 66.5 s10.56 s folding NIM 1.5.0 114.3 s12.05 s folding 0120 s Mean time per design at one design per container. The remaining task time includes startup and any other work outside the logged fold. Quality: similar summaries, different designs Both pipelines delivered 150 designs with no unresolved failures, and their summary metrics look alike: complex pLDDT averaged 82.20 for OSS and 82.55 for NIM. The molecules are not the same ones. Only half of the paired binder structures were within 2 Å of each other, and while both arms had 26 designs above the 10 Å backbone-recovery failure threshold, only 14 of those were the same designs. The primary BindCraft score favored OSS by 3.87 points (95% CI 0.97 to 6.76), against a within-arm standard deviation of roughly 24. On the 150 paired designs that difference is significant (p = 0.009, paired t-test). A 20,000-draw permutation test agrees. The average is not the number to act on, though. At an ipTM cutoff of 0.5, a common threshold since this run applied no filter of its own, 39 of 150 OSS designs pass against 44 in the NIM arm, but only 21 designs pass in both. Of the top 20 by BindCraft score, 11 are the same designs; ranked by ipTM, 9. The two arms agree on about half of what you would carry forward while their averages stay close, so the container moves the shortlist more than it moves the summary. Similar summary metrics do not establish quality equivalence. While RFdiffusion reproduces the generative step between arms, the ProteinMPNN divergence prevents attributing downstream differences to OpenFold3 alone. These are computational assessments, not measurements of binding success. Which designs cleared the ipTM cutoff? OSS only 18 Both arms 21 NIM only 23 030 designs At ipTM ≥ 0.5, the OSS arm passed 39 designs and NIM passed 44. The overlap counts paired design IDs, whose sequences differed between arms. The container version moves the designs as well. Replaying the same 150 inputs through OpenFold3 NIM 1.6.0 returned no prediction identical to 1.5.0’s. On the binder chain the two versions agree within 2 Å on 89 of 150 designs, against 75 of 150 between the two pipelines; across the whole complex only 46 of 150 agree. Rank the designs by ipTM and only 13 of the top 20 are the same under both versions, so a shortlist drawn from these scores depends on which container produced them. Cost: what the compute model leaves out Compute for the benchmark day came to $67.46 at list prices. Network traffic cost twice that. The biggest charge is NAT gateway data processing. Every NIM server downloads its weights before it answers its first request, nothing cached them between tasks, and 600 tasks did that over a path that bypassed the VPC endpoints already in place for ECR and S3. A shared weight cache is where that bill gets cut. It would not touch the next line, which is mostly container images landing on fresh instances. Where the $212.43 benchmark-day spend went NAT data processing $101.97 EC2 compute $67.46 Cross-AZ transfer $35.76 Everything else $7.24 0$120 NAT data processing and cross-AZ transfer made up about 65% of the day’s list-price total, including verification runs. View traffic and cost table Benchmark day, at list prices Traffic Cost Compute, EC2 — $67.46 NAT gateway data processing 2,266 GB $101.97 Cross-AZ transfer 3,576 GB $35.76 Everything else — $7.24 Total $212.43 These are day-level totals at list prices before credits, including verification runs, and transfer was not attributed per arm. The weight-cache saving is modeled, not re-measured. The per-design figures in the tables above are modeled from container time and total $41.86 across both arms; the rest of the $67.46 is instance boot, image pulls, idle capacity and those verification runs. Batching One startup, fifteen designs: a sixfold gain Batching delivered the largest measured speedup in this benchmark. At 15 designs per container, RFdiffusion was 5.9× faster and OpenFold3 was 6.0× faster per design than the original NIM deployment—with server startup included. Figure 2. Per-design and batched NIM execution in the PD-L1 binder-design workflow. Nextflow submits tasks to AWS Batch for execution on Amazon EC2. In the per-design configuration, each server handles one request before shutting down. In the batched configuration, RFdiffusion and OpenFold3 each start one server and process 15 designs sequentially. ProteinMPNN uses one server per design in both configurations. Structure preparation and BindCraft scoring run on CPUs. The advantage came from keeping the accelerated model working. In the original setup, every task started a NIM server, sent one request and shut it down. Batching lets that server handle more than one design before exiting, spreading the same startup cost across the batch (Figure 2). NIM stage 1 design/container 15 designs/container Speedup RFdiffusion 93.9 s/design 15.96 s/design 5.9× OpenFold3 114.3 s/design 18.97 s/design 6.0× How server reuse changed time per design RFdiffusion 1 per server 93.87 s 15 per server 15.96 s OpenFold3 1 per server 114.27 s 15 per server 18.97 s 0120 s Observed NIM stage times include server startup. Each batched stage ran two tasks of 15 sequential requests. These were measurements inside the Nextflow pipeline: two tasks of 15 designs per stage, covering seeds 0–29. A separate OpenFold3 test made the mechanism clear: one 97-second startup, followed by 15 folds at 12–13 seconds each, with no slowdown from the first fold to the fifteenth. Here, batching means sequential requests to a reused server. The NVIDIA 1.6.0 release notes describe concurrent serving with one inference process per GPU. The gain here is amortized startup, not concurrent inference, which is why the larger speedups NVIDIA reports for heavily batched workloads do not apply to a pipeline shaped like this one. What batching changes, and what it does not In the pipeline model that is 37.8% less summed task time and 65.1% lower compute cost per design than one design per OSS container: 215.0 seconds and $0.044, with the other four stages unchanged. Deployment decides more than the image does. At 15 designs per server the OpenFold3 stage took 14.40 seconds per design on the open-source container and 18.97 on NIM 1.5.0. Applying the warm-fold improvement from 1.6.0 gives a modeled 10.6 seconds. Configuration Summed task time/design, all stages Modeled compute cost/design OSS, 1 design/container 345.6 s $0.127 NIM, 1 design/container 388.2 s $0.152 NIM, 15 designs/container (estimate) 215.0 s $0.044 The stage gains are measured. The whole-pipeline figures come from the model: ProteinMPNN stays unbatched, and the batched open-source baseline covers OpenFold3. What a faster model actually buys NVIDIA released OpenFold3 NIM 1.6.0 after our implementation, and it folds 3.2 times faster: 12.05 seconds per prediction against 3.75 on the same 150 inputs, one L40S, identical harness. NVIDIA attributes this to capturing the diffusion module as a CUDA graph, which removes a fixed per-request overhead rather than a proportional one. How much of that reaches the pipeline depends on how each server is used. At one design per container, swapping it in and changing nothing else would reduce summed task time by about 2%, assuming the same startup and other stage times. OpenFold3 stage, per design 1.5.0 baseline 1.6.0 estimate one design per container 114.3 s 106.0 s 15 designs per container 18.9 s 10.6 s At one design per container the upgrade is worth 7% of the OpenFold3 stage, because startup dominates it. At fifteen it is worth 44%, and the modeled stage time falls to 10.6 seconds per design, below the 14.40 seconds measured for the batched open-source container. The same release, in the same pipeline, is worth six times more under one deployment than the other. A version change also moves the science, not just the clock: replaying the same 150 inputs through 1.6.0 returned no prediction identical to 1.5.0’s, and while the target chain reproduced to a median 0.3 Å, only 46 of the 150 complexes landed within 2 Å. This upgrade changed the predictions. 1.6.0 changed three things at once — CUDA graph capture, a CUDA 13.2 and PyTorch 2.12 base image, and per-request sampler seeding — so this is a property of the version, not of any one of them. Nextflow: what it gave us This improvement fit inside the existing Nextflow and AWS Batch workflow. Nextflow still scheduled tasks and handled dependencies and retries; each task simply did more work before exiting. We could reuse NIM servers without introducing an always-on GPU endpoint. That flexibility is most of why the comparison was possible at all. Both arms are the same DSL2 workflow with different containers, so swapping a NIM for an open-source image, or one NIM version for another, is a configuration change rather than a new pipeline. Nextflow retried the eleven tasks that failed during the run without intervention, and all 300 designs completed. It overlaps stages, so folding starts on the first designs while later backbones are still being generated. And because each step is cached, with -resume and the previous task outputs still available, changing one stage reruns that stage onward instead of the whole run. Keeping an EC2 instance warm would not achieve the same result: a fresh task still starts a fresh model server. Weight caching addresses a different expense. In the separate OpenFold3 test, preloaded weights reduced readiness time only from about 102 to 97 seconds. That figure is the server’s own startup inside a task. A machine’s first container pays a further one-off cost of roughly 100 seconds for image extraction and GPU runtime setup, which is why the same image takes about 210 seconds to answer on a freshly launched instance and 86 on its second container. Caching can reduce repeated downloads; batching spreads the remaining startup across designs. The practical lesson: give each NIM server enough work to make its accelerated inference count. In this deployment, changing the amount of work per task unlocked the performance advantage. Conclusions and what to learn Three things decided the outcome. Giving each NIM server more than one design to handle before it shut down was the largest measured gain, about sixfold per design. Matching the execution stacks made RFdiffusion reproducible across both paths, without which nothing downstream could be compared at all. And the bill was dominated not by compute but by data crossing the network, much of it model weights fetched again for every task. Five things that matter when you put a pipeline like this together. Check both containers produce the same thing before you compare them. Identical seeds, versions and weights were not enough for RFdiffusion until the execution stacks matched, and ProteinMPNN never matched at all. Compare equivalent server-reuse strategies. Batch both arms the same way before comparing them, and report designs that pass the intended quality filters. Report inference, task time and elapsed time separately. Pair those measurements with actual compute and transfer costs. Treat weight reuse as part of the deployment. A fast model can still sit inside an expensive workflow. Pin the container, not the tag. Moving from OpenFold3 NIM 1.5.0 to 1.6.0 cut folding 3.2× and changed the predicted complexes. A mutable tag can do both without anyone editing the pipeline. Swapping an open-source container for a NIM is not a drop-in change. It moves the timings, the costs, and the designs themselves, and which way it moves them depends on how many designs share each server and which version is running. Those are deliberate choices, and they are worth measuring before committing a project to either path. Before you switch, run both setups on a workload you actually plan to ship. If you’re weighing up NIMs for your own pipeline, get in touch with Loka. We can help you run that comparison. References NVIDIA. (n.d.). BioNeMo NIM overview Di Tommaso, P., et al. (2017). Nextflow enables reproducible computational workflows. Nature Biotechnology, 35(4), 316–319 Amazon Web Services. (n.d.). What is AWS Batch? Herbst, R. S., et al. (2014). Predictive correlates of response to the anti-PD-L1 antibody MPDL3280A in cancer patients. Nature, 515(7528), 563–567 Watson, J. L., et al. (2023). De novo design of protein structure and function with RFdiffusion. Nature, 620(7976), 1089–1100 The OpenFold3 Team. (2026). OpenFold3-preview2 technical report Abramson, J., et al. (2024). Accurate structure prediction of biomolecular interactions with AlphaFold 3. Nature, 630(8016), 493–500 NVIDIA. (2026, September 3). Release notes for NVIDIA NIM for OpenFold3, version 1.6.0 Dauparas, J., et al. (2022). Robust deep learning-based protein sequence design using ProteinMPNN. Science, 378(6615), 49–56 Bennett, N. R., et al. (2023). Improving de novo protein binder design with deep learning. Nature Communications, 14, Article 2625 Pacesa, M., et al. (2025). One-shot design of functional protein binders with BindCraft. Nature, 646(8084), 483–492 Amazon Web Services. (n.d.). Amazon EC2 G6e instances NVIDIA. (2026). NVIDIA NIM for RFdiffusion (Version 2.3.0) [Container image]. NVIDIA NGC Catalog NVIDIA. (2026). NVIDIA NIM for ProteinMPNN (Version 1.2.0) [Container image]. NVIDIA NGC Catalog NVIDIA. (2026). NVIDIA NIM for OpenFold3 (Version 1.5.0) [Container image]. NVIDIA NGC Catalog NVIDIA. (n.d.). Prerequisites for NVIDIA NIM for RFdiffusion, version 2.3.0 NVIDIA. (2026). NVIDIA NIM for OpenFold3 (Version 1.6.0) [Container image]. NVIDIA NGC Catalog OpenFold Consortium. (2026). OpenFold3 (Version 0.5-pixi) [Container image]. Docker Hub Australian Protein Design Initiative. (n.d.). Containers: proteinmpnn_dl_binder_design, bindcraft [Container images] NVIDIA. (n.d.). BioNeMo blueprint for generative protein binder design"},{"href":"/twelve-protein-design-methods/","title":"The Protein Design Method Matters Less Than Its Search Space","description":"A re-run benchmark of twelve protein fitness optimization methods on GFP and AAV under a matched query budget, reporting oracle-guided and surrogate-guided results separately: the representation moves results more than the optimizer does, and the leaderboard reorders when the evaluator changes.","abstract":"Twelve sequence optimization methods re-run under one 3,840-query budget, five seeds and a shared ground-truth oracle, scored under both oracle-guided and surrogate-guided feedback. No method wins outright; the ranking depends on the search space and on which model closes the loop.","tags":["Protein Design","Reinforcement Learning","Benchmarking","Protein Language Models"],"topics":["biomedical-ai","benchmarks"],"authors":["André Barbosa","Patrícia Rocha","Telmo Felgueira","Mário Figueiredo"],"text":"A protein design search works in rounds: propose new sequences, score them, and use the scores to propose the next batch. Protein fitness optimization papers are hard to read against each other, because every paper runs that loop differently. Each one picks its own task, its own oracle, its own query budget, its own terminal statistic. One paper reports the best sequence it ever saw; another reports the median of a final batch. One lets the ground-truth scoring model answer every query during the search; another trains a predictor on a restricted dataset and calls the ground truth once, at the end. All four call the result “fitness,” but the numbers are not comparable. Which of these would we actually run on a design campaign? The literature has no answer. Getting one took a master’s thesis: we re-ran nine published methods and added three of our own, instead of citing published numbers. No single method won outright. What the study produced instead is a ranking that moves depending on two things most papers leave implicit: the space a method searches, and the model that closes its loop. We start with the space. The setup Four fixed-length tasks from the benchmark released with GGS: GFP, a fluorescent protein (237 residues), and a 28-residue window of the AAV capsid, the virus’s protein shell, each at medium and hard difficulty. One shared ground-truth CNN oracle, used unchanged. Every method gets the same budget within a regime: five seeds, fifteen rounds, 15 × 256 = 3,840 guidance queries per seed. The antibody experiment at the end runs on a longer schedule of its own. Fitness is the median ground-truth score over a frozen top-128 selection; Top is the mean of the best 16. The design decision that mattered most was running everything twice, under two feedback regimes that we report separately and never average: Oracle-guided. The ground-truth oracle answers every query during the search. Surrogate-guided. A predictor trained only on the restricted starting set guides the search, and the ground truth scores the frozen terminal selection once. This is closer to a real campaign, where the thing you optimize is a model and the truth is an assay you cannot call 3,840 times. The benchmark calls that reference model the oracle, but its scores are themselves predictions, not lab measurements, so every comparison below shares that ceiling. The two regimes measure different things, so they never share a column. The gap between them turned out to be one of the most informative quantities in the study. The roster covered: Sequence-space: Bayesian optimization, CMA-ES, PEX, and AdaLead Latent-space: Latent CMA-ES, LatProtRL Mutation planning: µSearch Preference tuning: ZymCTRL and ProtGPT2 Three decoding paths of our own, driven by PPO over a continuous latent action space: AR, CE and LevT Everything ran on a single AWS g5.4xlarge (A10G, 24 GB). Where you search matters more than how you search CMA-ES is an off-the-shelf optimizer. We ran it twice on the same task, with the same budget and the same scoring model, changing only what it was allowed to search: a one-hot sequence encoding, or a learned latent space. Median fitness goes from -0.105 with one-hot to 0.681 with the latent space, on a task where the strongest runs in the study reach about 0.9. The mechanism is not mysterious. Gaussian sampling over one-hot encodings does not respect the categorical structure of amino acids, and projecting back to a sequence destroys the distribution the search intended. Changing the representation turns a non-competitive optimizer into a competitive one. That spread is wider than any comparison we ran between two optimizers inside the same space. So when a paper credits a gain to its algorithm, check which representation the algorithm ran in. Part of the delta may belong to the encoder. That is the search space. A single fitness number has its own blind spot too, even once the representation is fixed. Same score, different designs We tracked three distance diagnostics alongside fitness: diversity (mean pairwise distance within the selection), novelty (mean distance to the nearest sequence in the initial set), and High (mean distance to the nearest experimentally observed high-fitness variant). Lower High is better, because it means the designs sit near something measured. Novelty on its own is not a good sign. High novelty combined with a high High means the method walked into territory where no measured function supports it. Figure 04 Explore beyond the starting pool. Check the distance to measured variants. Novelty and proximity to measured high-fitness variants describe different aspects of a design. Distance to a measured high-fitness variant ↑ mutations · lower is better 010100300 010100300 Novelty · mutations from the initial pool Oracle-guidedSurrogate-guidedEqual distances Hover, tap, or focus a point for its method and exact values. Use arrow keys to move between points. 60 supplied results. Surrogate results are available for CE, AR, and LevT only. View the novelty and distance values Supplied novelty / High results. Both axes use mutation counts. Method Task Feedback Novelty High CMA-ES GFP-medium oracle 170.3 171.1 CMA-ES GFP-hard oracle 221.2 221.5 CMA-ES AAV-medium oracle 17.8 18.8 CMA-ES AAV-hard oracle 19.6 19.8 Bayesian optimization GFP-medium oracle 32.4 34.9 Bayesian optimization GFP-hard oracle 73.9 79.2 Bayesian optimization AAV-medium oracle 9.8 8.4 Bayesian optimization AAV-hard oracle 10.2 8.8 PEX GFP-medium oracle 6.3 8.2 PEX GFP-hard oracle 8.8 10.4 PEX AAV-medium oracle 5.3 5 PEX AAV-hard oracle 6.2 6.4 AdaLead GFP-medium oracle 9.4 10.6 AdaLead GFP-hard oracle 15.2 19.4 AdaLead AAV-medium oracle 7.8 6.2 AdaLead AAV-hard oracle 7.8 5.4 Latent CMA-ES GFP-medium oracle 7.8 4 Latent CMA-ES GFP-hard oracle 8.2 3.4 Latent CMA-ES AAV-medium oracle 7.4 5.7 Latent CMA-ES AAV-hard oracle 9.2 6 LatProtRL GFP-medium oracle 5.8 1.2 LatProtRL GFP-hard oracle 7.4 2 LatProtRL AAV-medium oracle 6 2.5 LatProtRL AAV-hard oracle 7 2.2 µSearch GFP-medium oracle 30.2 31.6 µSearch GFP-hard oracle 58.4 62 µSearch AAV-medium oracle 11.2 9.8 µSearch AAV-hard oracle 10.4 8.2 DPO (ZymCTRL) GFP-medium oracle 10.6 15.6 DPO (ZymCTRL) GFP-hard oracle 11.2 16.8 DPO (ZymCTRL) AAV-medium oracle 8.6 7.6 DPO (ZymCTRL) AAV-hard oracle 12.4 11.2 DPO (ProtGPT2) GFP-medium oracle 11 16 DPO (ProtGPT2) GFP-hard oracle 11.4 17 DPO (ProtGPT2) AAV-medium oracle 12.5 12.2 DPO (ProtGPT2) AAV-hard oracle 13.6 12.8 Fixed-length (CE) GFP-medium oracle 19.2 16.4 Fixed-length (CE) GFP-hard oracle 12 7 Fixed-length (CE) AAV-medium oracle 5.2 6.1 Fixed-length (CE) AAV-hard oracle 6.6 7.4 Autoregressive (AR) GFP-medium oracle 5.2 1 Autoregressive (AR) GFP-hard oracle 7 2 Autoregressive (AR) AAV-medium oracle 6.6 5.2 Autoregressive (AR) AAV-hard oracle 7 3.2 Edit-based (LevT) GFP-medium oracle 28.8 33.9 Edit-based (LevT) GFP-hard oracle 22.4 28.2 Edit-based (LevT) AAV-medium oracle 5.3 6.9 Edit-based (LevT) AAV-hard oracle 7.6 9 Fixed-length (CE) GFP-medium surrogate 15.6 12.3 Fixed-length (CE) GFP-hard surrogate 12 7 Fixed-length (CE) AAV-medium surrogate 3.8 5.8 Fixed-length (CE) AAV-hard surrogate 4.7 6.8 Autoregressive (AR) GFP-medium surrogate 5 1 Autoregressive (AR) GFP-hard surrogate 6 1 Autoregressive (AR) AAV-medium surrogate 5 2.2 Autoregressive (AR) AAV-hard surrogate 6 2 Edit-based (LevT) GFP-medium surrogate 2 8 Edit-based (LevT) GFP-hard surrogate 2 8.5 Edit-based (LevT) AAV-medium surrogate 2.7 6 Edit-based (LevT) AAV-hard surrogate 5.6 8 Figure 4. Supplied method/task/regime results. Both axes are linear through 10 mutations and logarithmic above 10. Below the dashed equality line, designs are closer to a measured high-fitness variant than to their initial pool. Most of the field sits on or near the identity line, which is the uninformative case: those methods buy distance from the starting pool and distance from anything measured in equal amounts. The runs off that line are the interesting ones, and they separate methods whose fitness scores barely differ. Oracle-guided Bayesian optimization reaches novelty 32.4 on GFP-medium against High of 34.9, with fitness stuck at 0.299. It explores where its own surrogate is most uncertain, which is also where nothing is known. LatProtRL travels less far, novelty 5.8 to 7.4, but holds the lowest High in the field at 1.2 to 2.5: less adventurous, far better anchored to observed function. Median and Top split a second way. Oracle-guided latent CMA-ES hits Top of 0.922 on GFP-medium with a median of only 0.473. It finds isolated peaks inside an otherwise mediocre batch. If you are ordering 128 sequences for a plate, that is a different product from a method whose whole batch is good, and the fitness column alone will not tell you which one you bought. Figure 03 A high peak can hide a mediocre batch. Compare the best 16 sequences with the median of the frozen top 128. Top · mean of best 16Fitness · median of top 128 GFP-medium Reference fitness · oracle-guided LatProtRL0.9890.921 AdaLead0.9740.922 Autoregressive (AR)0.9630.925 Latent CMA-ES0.9220.473 DPO (ZymCTRL)0.8140.78 µSearch0.8090.699 PEX0.780.638 Fixed-length (CE)0.7280.503 DPO (ProtGPT2)0.670.52 Edit-based (LevT)0.4650.427 Bayesian optimization0.3930.299 CMA-ES0.087-0.043 00.51 GFP-hard Reference fitness · oracle-guided LatProtRL0.9290.823 AdaLead0.7530.718 Autoregressive (AR)0.9670.914 Latent CMA-ES0.9120.5 DPO (ZymCTRL)0.5030.429 µSearch0.7660.715 PEX0.6030.48 Fixed-length (CE)0.8420.782 DPO (ProtGPT2)0.3650.234 Edit-based (LevT)0.3180.278 Bayesian optimization0.3490.292 CMA-ES0.064-0.041 00.51 AAV-medium Reference fitness · oracle-guided LatProtRL0.7530.67 AdaLead0.7630.733 Autoregressive (AR)0.7250.685 Latent CMA-ES0.750.628 DPO (ZymCTRL)0.7320.699 µSearch0.7410.617 PEX0.7050.642 Fixed-length (CE)0.5850.534 DPO (ProtGPT2)0.4420.338 Edit-based (LevT)0.6050.555 Bayesian optimization0.6680.623 CMA-ES0.1520.04 00.51 AAV-hard Reference fitness · oracle-guided LatProtRL0.7180.644 AdaLead0.7190.686 Autoregressive (AR)0.7060.683 Latent CMA-ES0.6830.512 DPO (ZymCTRL)0.6440.621 µSearch0.7270.604 PEX0.7020.633 Fixed-length (CE)0.570.525 DPO (ProtGPT2)0.4470.345 Edit-based (LevT)0.5860.531 Bayesian optimization0.6760.622 CMA-ES0.1290.036 00.51 Hover, tap, or focus a method to inspect the gap between its best sequences and its batch median. View all 48 method/task comparisons Oracle-guided fitness. Same method order and fixed −0.25 to 1.05 scale across tasks. Method Task Top Median Gap Fixed-length (CE) GFP-medium 0.728 0.503 0.225 Fixed-length (CE) GFP-hard 0.842 0.782 0.06 Fixed-length (CE) AAV-medium 0.585 0.534 0.051 Fixed-length (CE) AAV-hard 0.57 0.525 0.045 Autoregressive (AR) GFP-medium 0.963 0.925 0.038 Autoregressive (AR) GFP-hard 0.967 0.914 0.053 Autoregressive (AR) AAV-medium 0.725 0.685 0.04 Autoregressive (AR) AAV-hard 0.706 0.683 0.023 Edit-based (LevT) GFP-medium 0.465 0.427 0.038 Edit-based (LevT) GFP-hard 0.318 0.278 0.04 Edit-based (LevT) AAV-medium 0.605 0.555 0.05 Edit-based (LevT) AAV-hard 0.586 0.531 0.055 CMA-ES GFP-medium 0.087 -0.043 0.13 CMA-ES GFP-hard 0.064 -0.041 0.105 CMA-ES AAV-medium 0.152 0.04 0.112 CMA-ES AAV-hard 0.129 0.036 0.093 Bayesian optimization GFP-medium 0.393 0.299 0.094 Bayesian optimization GFP-hard 0.349 0.292 0.057 Bayesian optimization AAV-medium 0.668 0.623 0.045 Bayesian optimization AAV-hard 0.676 0.622 0.054 PEX GFP-medium 0.78 0.638 0.142 PEX GFP-hard 0.603 0.48 0.123 PEX AAV-medium 0.705 0.642 0.063 PEX AAV-hard 0.702 0.633 0.069 AdaLead GFP-medium 0.974 0.922 0.052 AdaLead GFP-hard 0.753 0.718 0.035 AdaLead AAV-medium 0.763 0.733 0.03 AdaLead AAV-hard 0.719 0.686 0.033 Latent CMA-ES GFP-medium 0.922 0.473 0.449 Latent CMA-ES GFP-hard 0.912 0.5 0.412 Latent CMA-ES AAV-medium 0.75 0.628 0.122 Latent CMA-ES AAV-hard 0.683 0.512 0.171 LatProtRL GFP-medium 0.989 0.921 0.068 LatProtRL GFP-hard 0.929 0.823 0.106 LatProtRL AAV-medium 0.753 0.67 0.083 LatProtRL AAV-hard 0.718 0.644 0.074 µSearch GFP-medium 0.809 0.699 0.11 µSearch GFP-hard 0.766 0.715 0.051 µSearch AAV-medium 0.741 0.617 0.124 µSearch AAV-hard 0.727 0.604 0.123 DPO (ZymCTRL) GFP-medium 0.814 0.78 0.034 DPO (ZymCTRL) GFP-hard 0.503 0.429 0.074 DPO (ZymCTRL) AAV-medium 0.732 0.699 0.033 DPO (ZymCTRL) AAV-hard 0.644 0.621 0.023 DPO (ProtGPT2) GFP-medium 0.67 0.52 0.15 DPO (ProtGPT2) GFP-hard 0.365 0.234 0.131 DPO (ProtGPT2) AAV-medium 0.442 0.338 0.104 DPO (ProtGPT2) AAV-hard 0.447 0.345 0.102 Figure 3. Oracle-guided Top and median fitness under the matched 15 × 256 query budget. Methods keep the GFP-medium Top ranking across all tasks; bar scales stay fixed and retain negative medians. Every comparison so far assumed an honest grader: the ground-truth oracle, answering every query. The second axis from the setup is what happens when the grader is an approximation instead, and that turns out to move the ranking more than anything else in this study. The leaderboard depends on which model closed the loop For each method and task we computed the empirical regime gap: the oracle-guided result minus the surrogate-guided result, same method, same budget. Figure 01 Same search. Different feedback. Different outcome. Track the three in-house decoding paths under both feedback regimes. GFP-medium oracle-guided Reference fitness ↑ 00.250.50.751 151015 Optimization round Fixed-length (CE)0.503 ± 0.12 Autoregressive (AR)0.925 ± 0.02 Edit-based (LevT)0.427 ± 0.02 Round 15: supplied thesis endpoint. View values for GFP-medium · oracle-guided GFP-medium · oracle-guided. Mean ± population standard deviation where supplied. Round Fixed-length (CE) Autoregressive (AR) Edit-based (LevT) Source 1 0.1096 ± 0.0026 0.1109 ± 0.0076 0.1215 ± 0.0042 Seed aggregate 2 0.1236 ± 0.0022 0.5407 ± 0.092 0.1648 ± 0.0051 Seed aggregate 3 0.134 ± 0.003 0.8092 ± 0.02 0.1967 ± 0.0069 Seed aggregate 4 0.143 ± 0.0053 0.8665 ± 0.0157 0.2309 ± 0.0132 Seed aggregate 5 0.1581 ± 0.013 0.8819 ± 0.0101 0.2581 ± 0.0199 Seed aggregate 6 0.191 ± 0.0381 0.8933 ± 0.0075 0.2805 ± 0.0228 Seed aggregate 7 0.2285 ± 0.0725 0.9005 ± 0.0045 0.3022 ± 0.0244 Seed aggregate 8 0.2697 ± 0.1031 0.9069 ± 0.002 0.3216 ± 0.0258 Seed aggregate 9 0.3075 ± 0.1242 0.9105 ± 0.0018 0.3407 ± 0.0263 Seed aggregate 10 0.3448 ± 0.1502 0.915 ± 0.0029 0.3597 ± 0.0279 Seed aggregate 11 0.3855 ± 0.1537 0.9179 ± 0.0035 0.3743 ± 0.0258 Seed aggregate 12 0.4126 ± 0.1493 0.9204 ± 0.0023 0.3872 ± 0.0265 Seed aggregate 13 0.4466 ± 0.1365 0.9219 ± 0.0022 0.3999 ± 0.0246 Seed aggregate 14 0.4703 ± 0.1256 0.9239 ± 0.0027 0.4142 ± 0.0228 Seed aggregate 15 0.503 ± 0.12 0.925 ± 0.02 0.427 ± 0.02 Thesis endpoint GFP-medium surrogate-guided Reference fitness ↑ 00.250.50.751 151015 Optimization round Fixed-length (CE)0.526 ± 0.12 Autoregressive (AR)0.868 ± 0.01 Edit-based (LevT)0.1 ± 0.01 Round 15: supplied thesis endpoint. View values for GFP-medium · surrogate-guided GFP-medium · surrogate-guided. Mean ± population standard deviation where supplied. Round Fixed-length (CE) Autoregressive (AR) Edit-based (LevT) Source 1 0.0707 ± 0.0024 0.1017 ± 0.0051 0.0882 ± 0.0034 Seed aggregate 2 0.0744 ± 0.0035 0.3696 ± 0.0789 0.0899 ± 0.0043 Seed aggregate 3 0.077 ± 0.0047 0.7404 ± 0.0358 0.092 ± 0.0038 Seed aggregate 4 0.0888 ± 0.0091 0.8116 ± 0.0171 0.0934 ± 0.004 Seed aggregate 5 0.1073 ± 0.0234 0.8364 ± 0.0184 0.096 ± 0.0032 Seed aggregate 6 0.1552 ± 0.0714 0.8405 ± 0.019 0.0968 ± 0.0034 Seed aggregate 7 0.2303 ± 0.1039 0.8563 ± 0.0189 0.0975 ± 0.0032 Seed aggregate 8 0.289 ± 0.1236 0.8585 ± 0.0128 0.0995 ± 0.0045 Seed aggregate 9 0.3217 ± 0.1185 0.861 ± 0.0101 0.1018 ± 0.0064 Seed aggregate 10 0.3664 ± 0.1317 0.8623 ± 0.0121 0.1009 ± 0.0052 Seed aggregate 11 0.4019 ± 0.1345 0.862 ± 0.016 0.1 ± 0.0025 Seed aggregate 12 0.4366 ± 0.1485 0.8682 ± 0.0119 0.1003 ± 0.0024 Seed aggregate 13 0.4686 ± 0.1444 0.8684 ± 0.0094 0.0994 ± 0.0035 Seed aggregate 14 0.4949 ± 0.1445 0.8708 ± 0.0069 0.0991 ± 0.0044 Seed aggregate 15 0.526 ± 0.12 0.868 ± 0.01 0.1 ± 0.01 Thesis endpoint GFP-hard oracle-guided Reference fitness ↑ 00.250.50.751 151015 Optimization round Fixed-length (CE)0.782 ± 0.01 Autoregressive (AR)0.914 ± 0.01 Edit-based (LevT)0.278 ± 0.01 Round 15: supplied thesis endpoint. View values for GFP-hard · oracle-guided GFP-hard · oracle-guided. Mean ± population standard deviation where supplied. Round Fixed-length (CE) Autoregressive (AR) Edit-based (LevT) Source 1 0.6863 ± 0.0166 0.6979 ± 0.0425 -0.0079 ± 0.0035 Seed aggregate 2 0.6057 ± 0.0183 0.6983 ± 0.0399 0.0185 ± 0.0058 Seed aggregate 3 0.691 ± 0.0035 0.7693 ± 0.0342 0.0409 ± 0.0058 Seed aggregate 4 0.7186 ± 0.0053 0.825 ± 0.0086 0.0603 ± 0.0069 Seed aggregate 5 0.7316 ± 0.0064 0.8465 ± 0.0085 0.0838 ± 0.0116 Seed aggregate 6 0.7413 ± 0.0048 0.8702 ± 0.0037 0.1044 ± 0.0111 Seed aggregate 7 0.7513 ± 0.0059 0.8849 ± 0.0051 0.1258 ± 0.015 Seed aggregate 8 0.7571 ± 0.0052 0.8935 ± 0.0034 0.1469 ± 0.019 Seed aggregate 9 0.763 ± 0.0031 0.9005 ± 0.002 0.1702 ± 0.0198 Seed aggregate 10 0.7678 ± 0.0048 0.9069 ± 0.0014 0.1892 ± 0.0218 Seed aggregate 11 0.7702 ± 0.0055 0.9084 ± 0.0011 0.2076 ± 0.0182 Seed aggregate 12 0.7742 ± 0.0072 0.91 ± 0.0017 0.2268 ± 0.0178 Seed aggregate 13 0.7785 ± 0.0058 0.9115 ± 0.0016 0.2459 ± 0.0154 Seed aggregate 14 0.7804 ± 0.0055 0.9131 ± 0.0022 0.2604 ± 0.0154 Seed aggregate 15 0.782 ± 0.01 0.914 ± 0.01 0.278 ± 0.01 Thesis endpoint GFP-hard surrogate-guided Reference fitness ↑ 00.250.50.751 151015 Optimization round Fixed-length (CE)0.69 ± 0.02 Autoregressive (AR)0.771 ± 0.02 Edit-based (LevT)0 ± 0 Round 15: supplied thesis endpoint. View values for GFP-hard · surrogate-guided GFP-hard · surrogate-guided. Mean ± population standard deviation where supplied. Round Fixed-length (CE) Autoregressive (AR) Edit-based (LevT) Source 1 0.6863 ± 0.0166 0.6979 ± 0.0425 0 ± 0 Seed aggregate 2 0.5991 ± 0.0139 0.7009 ± 0.0461 0 ± 0 Seed aggregate 3 0.6441 ± 0.0271 0.6726 ± 0.035 0 ± 0 Seed aggregate 4 0.6591 ± 0.022 0.7245 ± 0.0351 0 ± 0 Seed aggregate 5 0.6551 ± 0.017 0.7186 ± 0.0502 0 ± 0 Seed aggregate 6 0.6564 ± 0.0163 0.701 ± 0.0464 0 ± 0 Seed aggregate 7 0.6648 ± 0.0181 0.7144 ± 0.0603 0 ± 0 Seed aggregate 8 0.6633 ± 0.0169 0.7235 ± 0.049 0 ± 0 Seed aggregate 9 0.6699 ± 0.024 0.7263 ± 0.0449 0 ± 0 Seed aggregate 10 0.6743 ± 0.0266 0.7311 ± 0.0448 0 ± 0 Seed aggregate 11 0.6784 ± 0.0235 0.7495 ± 0.032 0.0003 ± 0.0006 Seed aggregate 12 0.6855 ± 0.0279 0.7556 ± 0.0092 0 ± 0 Seed aggregate 13 0.6855 ± 0.029 0.7643 ± 0.0168 0 ± 0 Seed aggregate 14 0.6926 ± 0.0238 0.7696 ± 0.0178 0 ± 0 Seed aggregate 15 0.69 ± 0.02 0.771 ± 0.02 0 ± 0 Thesis endpoint AAV-medium oracle-guided Reference fitness ↑ 00.250.50.751 151015 Optimization round Fixed-length (CE)0.534 ± 0.01 Autoregressive (AR)0.685 ± 0.01 Edit-based (LevT)0.555 ± 0.02 Round 15: supplied thesis endpoint. View values for AAV-medium · oracle-guided AAV-medium · oracle-guided. Mean ± population standard deviation where supplied. Round Fixed-length (CE) Autoregressive (AR) Edit-based (LevT) Source 1 0.2181 ± 0.0104 0.3885 ± 0.0072 0.2786 ± 0.008 Seed aggregate 2 0.3253 ± 0.0077 0.4918 ± 0.0116 0.3333 ± 0.0139 Seed aggregate 3 0.3796 ± 0.0089 0.5377 ± 0.0063 0.3772 ± 0.0146 Seed aggregate 4 0.403 ± 0.0103 0.5697 ± 0.0063 0.4165 ± 0.0186 Seed aggregate 5 0.422 ± 0.0092 0.5966 ± 0.012 0.4434 ± 0.0186 Seed aggregate 6 0.4354 ± 0.0078 0.6169 ± 0.0146 0.4646 ± 0.0141 Seed aggregate 7 0.4457 ± 0.0098 0.6326 ± 0.0123 0.4785 ± 0.0119 Seed aggregate 8 0.4568 ± 0.0097 0.6466 ± 0.0094 0.4944 ± 0.0128 Seed aggregate 9 0.4694 ± 0.0089 0.6551 ± 0.0085 0.5036 ± 0.0129 Seed aggregate 10 0.4817 ± 0.0075 0.6613 ± 0.0069 0.5125 ± 0.0134 Seed aggregate 11 0.492 ± 0.0086 0.6673 ± 0.0069 0.5224 ± 0.0137 Seed aggregate 12 0.5032 ± 0.0102 0.6731 ± 0.0061 0.5307 ± 0.0154 Seed aggregate 13 0.5142 ± 0.0117 0.6773 ± 0.0071 0.5402 ± 0.0171 Seed aggregate 14 0.5241 ± 0.0138 0.6815 ± 0.0085 0.5476 ± 0.015 Seed aggregate 15 0.534 ± 0.01 0.685 ± 0.01 0.555 ± 0.02 Thesis endpoint AAV-medium surrogate-guided Reference fitness ↑ 00.250.50.751 151015 Optimization round Fixed-length (CE)0.483 ± 0.02 Autoregressive (AR)0.605 ± 0.01 Edit-based (LevT)0.466 ± 0.01 Round 15: supplied thesis endpoint. View values for AAV-medium · surrogate-guided AAV-medium · surrogate-guided. Mean ± population standard deviation where supplied. Round Fixed-length (CE) Autoregressive (AR) Edit-based (LevT) Source 1 0.2181 ± 0.0104 0.372 ± 0.0045 0.2749 ± 0.0069 Seed aggregate 2 0.265 ± 0.0091 0.4181 ± 0.0174 0.3036 ± 0.008 Seed aggregate 3 0.3347 ± 0.0121 0.4437 ± 0.0171 0.3215 ± 0.0085 Seed aggregate 4 0.3619 ± 0.0092 0.4469 ± 0.0363 0.3422 ± 0.0094 Seed aggregate 5 0.3797 ± 0.0086 0.4699 ± 0.0437 0.3584 ± 0.012 Seed aggregate 6 0.3927 ± 0.0038 0.5134 ± 0.043 0.3778 ± 0.0176 Seed aggregate 7 0.4081 ± 0.0041 0.5441 ± 0.0208 0.4041 ± 0.0268 Seed aggregate 8 0.4193 ± 0.0086 0.5604 ± 0.0078 0.4097 ± 0.0271 Seed aggregate 9 0.4327 ± 0.0119 0.5705 ± 0.0052 0.4215 ± 0.0255 Seed aggregate 10 0.4493 ± 0.0183 0.5788 ± 0.0042 0.4278 ± 0.0289 Seed aggregate 11 0.4631 ± 0.017 0.5836 ± 0.0026 0.4388 ± 0.0273 Seed aggregate 12 0.4695 ± 0.0187 0.5887 ± 0.0023 0.4516 ± 0.0148 Seed aggregate 13 0.4746 ± 0.0184 0.5938 ± 0.0014 0.4581 ± 0.011 Seed aggregate 14 0.479 ± 0.0173 0.5984 ± 0.0049 0.4629 ± 0.0122 Seed aggregate 15 0.483 ± 0.02 0.605 ± 0.01 0.466 ± 0.01 Thesis endpoint AAV-hard oracle-guided Reference fitness ↑ 00.250.50.751 151015 Optimization round Fixed-length (CE)0.525 ± 0.02 Autoregressive (AR)0.683 ± 0.01 Edit-based (LevT)0.531 ± 0.01 Round 15: supplied thesis endpoint. View values for AAV-hard · oracle-guided AAV-hard · oracle-guided. Mean ± population standard deviation where supplied. Round Fixed-length (CE) Autoregressive (AR) Edit-based (LevT) Source 1 0.2771 ± 0.0043 0.3173 ± 0.0047 0.2844 ± 0.0058 Seed aggregate 2 0.3014 ± 0.0059 0.3679 ± 0.0051 0.322 ± 0.0076 Seed aggregate 3 0.3255 ± 0.0106 0.4056 ± 0.0037 0.3472 ± 0.0063 Seed aggregate 4 0.3487 ± 0.0095 0.4393 ± 0.0053 0.3678 ± 0.0103 Seed aggregate 5 0.3689 ± 0.0044 0.4671 ± 0.0134 0.3882 ± 0.0086 Seed aggregate 6 0.3861 ± 0.0044 0.4965 ± 0.0216 0.4089 ± 0.0098 Seed aggregate 7 0.4027 ± 0.0079 0.525 ± 0.0209 0.4256 ± 0.0118 Seed aggregate 8 0.4239 ± 0.0138 0.5483 ± 0.0233 0.4419 ± 0.013 Seed aggregate 9 0.441 ± 0.0171 0.5693 ± 0.0239 0.4554 ± 0.0134 Seed aggregate 10 0.4612 ± 0.0197 0.588 ± 0.0208 0.4681 ± 0.0121 Seed aggregate 11 0.4751 ± 0.0219 0.6052 ± 0.0137 0.4829 ± 0.0128 Seed aggregate 12 0.4895 ± 0.0252 0.6182 ± 0.0105 0.4938 ± 0.0128 Seed aggregate 13 0.5028 ± 0.0274 0.6283 ± 0.008 0.5058 ± 0.0118 Seed aggregate 14 0.5147 ± 0.0285 0.6372 ± 0.006 0.5183 ± 0.012 Seed aggregate 15 0.525 ± 0.02 0.683 ± 0.01 0.531 ± 0.01 Thesis endpoint AAV-hard surrogate-guided Reference fitness ↑ 00.250.50.751 151015 Optimization round Fixed-length (CE)0.388 ± 0.01 Autoregressive (AR)0.581 ± 0.01 Edit-based (LevT)0.371 ± 0.03 Round 15: supplied thesis endpoint. View values for AAV-hard · surrogate-guided AAV-hard · surrogate-guided. Mean ± population standard deviation where supplied. Round Fixed-length (CE) Autoregressive (AR) Edit-based (LevT) Source 1 0.2771 ± 0.0043 0.3161 ± 0.0052 0.2816 ± 0.0055 Seed aggregate 2 0.2926 ± 0.0064 0.3416 ± 0.0023 0.2985 ± 0.0063 Seed aggregate 3 0.2961 ± 0.005 0.366 ± 0.004 0.3042 ± 0.0078 Seed aggregate 4 0.299 ± 0.0039 0.3947 ± 0.009 0.3092 ± 0.0114 Seed aggregate 5 0.3089 ± 0.0092 0.4137 ± 0.0133 0.3212 ± 0.0117 Seed aggregate 6 0.3267 ± 0.0132 0.4375 ± 0.018 0.3246 ± 0.017 Seed aggregate 7 0.3424 ± 0.0121 0.4667 ± 0.015 0.3315 ± 0.0239 Seed aggregate 8 0.3536 ± 0.008 0.4964 ± 0.0118 0.3351 ± 0.021 Seed aggregate 9 0.364 ± 0.0065 0.5262 ± 0.0168 0.3377 ± 0.021 Seed aggregate 10 0.3679 ± 0.007 0.5433 ± 0.0143 0.3432 ± 0.0234 Seed aggregate 11 0.3726 ± 0.0088 0.562 ± 0.0113 0.3494 ± 0.0258 Seed aggregate 12 0.3762 ± 0.0074 0.5685 ± 0.0125 0.3512 ± 0.0276 Seed aggregate 13 0.3813 ± 0.0096 0.5717 ± 0.0115 0.3588 ± 0.0254 Seed aggregate 14 0.3844 ± 0.0099 0.5782 ± 0.0109 0.3661 ± 0.0227 Seed aggregate 15 0.388 ± 0.01 0.581 ± 0.01 0.371 ± 0.03 Thesis endpoint Figure 1. CE, AR, and LevT substitution trajectories. Bands show the supplied mean ±1 standard deviation across five seeds. The author’s summary marks round-15 values as thesis endpoints; these are retained separately from seed-derived rounds. Comparing the two feedback panels for a task shows what swapping the evaluator costs each path. The autoregressive curve barely moves between regimes on GFP-medium, while the edit path drops from a steady climb to a flat line at zero on GFP-hard. What a method loses between regimes tracks how far it can travel from the predictor’s training data. Latent-space methods lose least. Generative and edit-based paths lose most. On GFP-medium the gap is -0.023 for the fixed-length cross-entropy decoder, 0.057 for the autoregressive path, and 0.327 for the edit-based path. Some gaps are negative. Latent CMA-ES beats its own oracle-guided result by 0.208 on GFP-medium. Both endpoints are scored by the same ground truth, so the predictor is not grading its own homework here. The likely reason is that a restricted predictor smooths a rugged objective, steering the search toward broad basins instead of narrow peaks. We did not measure that directly. Either way, the oracle-guided leaderboard cannot be read as a forecast of performance under realistic feedback. Preference tuning shows the same dependence from another angle. Under oracle guidance, DPO on ZymCTRL reaches 0.780 on GFP-medium and 0.699 on AAV-medium; the same optimization rule on ProtGPT2 reaches 0.520 and 0.338. The rule is shared, and the prior decides which high-reward region is reachable at all. Everything up to here also assumed the search could only substitute residues, never change how long the sequence is. Most of these methods cannot insert or delete anything The standard benchmarks admit substitutions only, which excludes the operation that matters in much of real design work: loop length, insertion-tolerant capsid windows, anything where the answer is not the same length as the question. So we built two length-changing paths on top of the framework and tested them where length can actually move. Both are driven by PPO. The autoregressive path adapts the native ProtT5 decoder through low-rank parameters on a shared latent scaffold. The edit-based path uses a Levenshtein Transformer, with four heads choosing keep, replace, delete and gap-indexed insertion operations, and the edit itself compressed into the latent rather than the target sequence. On an insertion-bearing AAV window (28 to 44 residues, from ProteinGym), the edit path leads under ground-truth guidance by 0.124 fitness on medium and 0.117 on hard, winning on every matched seed. The edit path had been the weaker of the two on fixed-length substitution. Given room to change length, it is the stronger complete system. Its fixed-length weakness has a specific and fixable cause, which is worth separating from the architecture. An edit step changes at most four residues per round, so fifteen rounds cover a meaningful fraction of a 28-residue AAV window but almost none of a 237-residue protein. Under the restricted GFP predictor the path sits at 0.100 fitness on medium and 0.000 on hard, with novelty near two mutations: too few residues moved for the search signal to register at all. Each of our three paths hit a different ceiling, and this is the only one addressable without touching the model. The autoregressive path is bounded by the quality of its prior, the fixed-length decoder by what it can express. The same budget spent on more edits per round, instead of more rounds, should reach further. We did not run that configuration, so it is a recommendation, not a result. Figure 02 When the predictor improves, does the design? On AAV, compare held-out oracle fitness with the predictor’s own score. AAV-medium oracle-guided Held-out oracle / predictor score ↑ 0.20.30.40.50.60.7 151015 Optimization round Autoregressive (AR) · oracle0.48 ± 0.02 Edit-based (LevT) · oracle0.603 ± 0.04 Round 15: supplied thesis endpoint. View values for AAV-medium · oracle-guided AAV-medium · oracle-guided. Mean ± population standard deviation where supplied. Round Autoregressive (AR) · oracle Edit-based (LevT) · oracle Source 1 0.2548 ± 0.0024 0.2651 ± 0.0006 Seed aggregate 2 0.2708 ± 0.0022 0.3088 ± 0.0055 Seed aggregate 3 0.2935 ± 0.004 0.3485 ± 0.0054 Seed aggregate 4 0.3145 ± 0.0067 0.3788 ± 0.0099 Seed aggregate 5 0.3374 ± 0.01 0.4086 ± 0.0186 Seed aggregate 6 0.3583 ± 0.0126 0.4363 ± 0.0204 Seed aggregate 7 0.377 ± 0.016 0.4632 ± 0.0191 Seed aggregate 8 0.3929 ± 0.0187 0.4849 ± 0.0211 Seed aggregate 9 0.4068 ± 0.0197 0.5017 ± 0.0241 Seed aggregate 10 0.42 ± 0.0209 0.5176 ± 0.0238 Seed aggregate 11 0.4349 ± 0.0202 0.5355 ± 0.028 Seed aggregate 12 0.4472 ± 0.0206 0.5586 ± 0.0349 Seed aggregate 13 0.4595 ± 0.0223 0.5761 ± 0.0361 Seed aggregate 14 0.4692 ± 0.0228 0.5911 ± 0.0373 Seed aggregate 15 0.48 ± 0.02 0.603 ± 0.04 Thesis endpoint AAV-medium surrogate-guided Held-out oracle / predictor score ↑ 0.20.30.40.50.60.7 151015 Optimization round Autoregressive (AR) · oracle0.306 ± 0.02 Autoregressive (AR) · predictor0.3504 Edit-based (LevT) · oracle0.293 ± 0.02 Edit-based (LevT) · predictor0.3662 Round 15: supplied thesis endpoint. View values for AAV-medium · surrogate-guided AAV-medium · surrogate-guided. Mean ± population standard deviation where supplied. Round Autoregressive (AR) · oracle Autoregressive (AR) · predictor Edit-based (LevT) · oracle Edit-based (LevT) · predictor Source 1 0.2548 ± 0.0024 0.3256 0.2595 ± 0.0036 0.3277 Seed aggregate 2 0.2632 ± 0.0014 0.327 0.272 ± 0.0068 0.3333 Seed aggregate 3 0.269 ± 0.0034 0.3299 0.2832 ± 0.0077 0.3375 Seed aggregate 4 0.2743 ± 0.0048 0.3325 0.2856 ± 0.0105 0.341 Seed aggregate 5 0.2755 ± 0.0029 0.3348 0.297 ± 0.0054 0.3442 Seed aggregate 6 0.2751 ± 0.0048 0.337 0.2977 ± 0.0044 0.347 Seed aggregate 7 0.279 ± 0.0048 0.3387 0.2935 ± 0.0046 0.3494 Seed aggregate 8 0.2795 ± 0.0053 0.3404 0.2922 ± 0.0048 0.3517 Seed aggregate 9 0.2833 ± 0.0041 0.3418 0.2904 ± 0.0097 0.3539 Seed aggregate 10 0.2862 ± 0.0048 0.3435 0.2904 ± 0.012 0.356 Seed aggregate 11 0.2879 ± 0.0086 0.3452 0.2971 ± 0.0168 0.3579 Seed aggregate 12 0.2919 ± 0.014 0.3468 0.2981 ± 0.0102 0.3599 Seed aggregate 13 0.2939 ± 0.0196 0.3481 0.298 ± 0.0123 0.3621 Seed aggregate 14 0.299 ± 0.0191 0.3492 0.2991 ± 0.0135 0.3641 Seed aggregate 15 0.306 ± 0.02 0.3504 0.293 ± 0.02 0.3662 Thesis endpoint AAV-hard oracle-guided Held-out oracle / predictor score ↑ 0.20.30.40.50.60.7 151015 Optimization round Autoregressive (AR) · oracle0.523 ± 0.01 Edit-based (LevT) · oracle0.64 ± 0.02 Round 15: supplied thesis endpoint. View values for AAV-hard · oracle-guided AAV-hard · oracle-guided. Mean ± population standard deviation where supplied. Round Autoregressive (AR) · oracle Edit-based (LevT) · oracle Source 1 0.288 ± 0.0015 0.2901 ± 0.0041 Seed aggregate 2 0.3039 ± 0.0025 0.3494 ± 0.0104 Seed aggregate 3 0.3333 ± 0.0008 0.4029 ± 0.0069 Seed aggregate 4 0.3573 ± 0.0038 0.4409 ± 0.0055 Seed aggregate 5 0.3804 ± 0.0026 0.48 ± 0.0067 Seed aggregate 6 0.3996 ± 0.0079 0.5089 ± 0.0041 Seed aggregate 7 0.4183 ± 0.0106 0.539 ± 0.0062 Seed aggregate 8 0.4345 ± 0.0109 0.5569 ± 0.0073 Seed aggregate 9 0.4504 ± 0.0128 0.5714 ± 0.0076 Seed aggregate 10 0.463 ± 0.0107 0.5832 ± 0.0082 Seed aggregate 11 0.4733 ± 0.0097 0.5963 ± 0.0088 Seed aggregate 12 0.4872 ± 0.0075 0.6063 ± 0.0101 Seed aggregate 13 0.5008 ± 0.0114 0.6173 ± 0.0129 Seed aggregate 14 0.5114 ± 0.0121 0.6299 ± 0.0159 Seed aggregate 15 0.523 ± 0.01 0.64 ± 0.02 Thesis endpoint AAV-hard surrogate-guided Held-out oracle / predictor score ↑ 0.20.30.40.50.60.7 151015 Optimization round Autoregressive (AR) · oracle0.314 ± 0.02 Autoregressive (AR) · predictor0.306 Edit-based (LevT) · oracle0.27 ± 0.02 Edit-based (LevT) · predictor0.3432 Round 15: supplied thesis endpoint. View values for AAV-hard · surrogate-guided AAV-hard · surrogate-guided. Mean ± population standard deviation where supplied. Round Autoregressive (AR) · oracle Autoregressive (AR) · predictor Edit-based (LevT) · oracle Edit-based (LevT) · predictor Source 1 0.288 ± 0.0015 0.2779 0.2874 ± 0.0043 0.278 Seed aggregate 2 0.2994 ± 0.0021 0.2805 0.3277 ± 0.0106 0.2844 Seed aggregate 3 0.304 ± 0.0037 0.2837 0.3399 ± 0.009 0.2899 Seed aggregate 4 0.3122 ± 0.0068 0.2868 0.3307 ± 0.0092 0.2945 Seed aggregate 5 0.3235 ± 0.0056 0.2897 0.3128 ± 0.0154 0.2987 Seed aggregate 6 0.3307 ± 0.0074 0.2918 0.3021 ± 0.0186 0.3027 Seed aggregate 7 0.3328 ± 0.009 0.2939 0.2975 ± 0.0325 0.3063 Seed aggregate 8 0.3308 ± 0.0157 0.2957 0.2835 ± 0.0345 0.3102 Seed aggregate 9 0.3261 ± 0.0152 0.2975 0.2803 ± 0.0291 0.3143 Seed aggregate 10 0.3234 ± 0.02 0.2992 0.2761 ± 0.0272 0.3181 Seed aggregate 11 0.3212 ± 0.0211 0.3008 0.2686 ± 0.0213 0.3226 Seed aggregate 12 0.3157 ± 0.0188 0.3022 0.2738 ± 0.0268 0.3278 Seed aggregate 13 0.3146 ± 0.0175 0.3035 0.2732 ± 0.0249 0.3326 Seed aggregate 14 0.3123 ± 0.0196 0.3048 0.2733 ± 0.018 0.3378 Seed aggregate 15 0.314 ± 0.02 0.306 0.27 ± 0.02 0.3432 Thesis endpoint Figure 2. Insertion-aware AAV trajectories. Solid lines and uncertainty bands show held-out oracle fitness; dashed lines show the predictor’s own score. Round-15 values use the supplied thesis endpoints. The ordering then reverses under the restricted predictor, and the per-round diagnostics show how. The bottom-right panel is the one to look at: the predictor’s own score climbs steadily while the held-out oracle curve for the same designs turns over and falls. Rescoring every round with the held-out oracle, the edit path on the hard task peaks at 0.340 by round three and then falls to 0.270 by round fifteen. The predictor over-values its selections by a consistent margin, those selections re-seed the frontier, and the search walks steadily away from true fitness while its own reward curve still looks healthy. The path that gains most from an honest evaluator is the one that loses most when you swap the evaluator out. That is the evaluator axis breaking down over many rounds. The next failure mode does not need a bad evaluator at all, just one with an exploitable rule. A scoring function will hand you shortcuts, and some policies take them The last experiment optimizes an antibody’s CDR-H3 loop (11 to 20 residues), the stretch that does most of the work of recognizing a target, against chain A of PDB 1ADQ, the human IgG4 Fc fragment recognized by the rheumatoid-factor antibody RF-AN. Fitness is negated binding energy from Absolut!, a lattice-based structural oracle. No learned predictor is involved. Absolut! scores the best contiguous 11-mer inside the loop. A longer loop therefore gets more chances at a favorable contact window, and a policy can raise its score by growing the loop instead of designing a better one. Figure 05 Better binding, or just a longer loop? Follow optimization, then inspect which loop lengths each method selects. Antibody CDR-H3 optimization Negated binding energy · higher is better ↑ 8090100110 115304562 Optimization round Best screened loop: 103.46 Autoregressive (AR) · median99.27 ± 1.3022 Autoregressive (AR) · best 16102.6564 Edit-based (LevT) · medianNot observed Edit-based (LevT) · best 16Not observed Five seeds; bands show ±1 population standard deviation. View values for Antibody CDR-H3 optimization Antibody CDR-H3 optimization. Mean ± population standard deviation where supplied. Round Autoregressive (AR) · median Autoregressive (AR) · best 16 Edit-based (LevT) · median Edit-based (LevT) · best 16 Source 1 83.26 ± 0.24454 84.82274 84.359 ± 0.42155 90.27514 Seed aggregate 2 83.003 ± 0.210324 85.3704 86.522 ± 0.701659 95.37274 Seed aggregate 3 82.729 ± 0.335327 86.01576 90.028 ± 1.211654 98.34736 Seed aggregate 4 82.69 ± 0.246252 86.67674 93.06 ± 1.3031 99.95574 Seed aggregate 5 82.794 ± 0.378489 87.45552 94.956 ± 1.045143 101.54924 Seed aggregate 6 83.12 ± 0.592874 88.1055 96.904 ± 1.02764 103.06088 Seed aggregate 7 83.54 ± 0.566101 88.9405 98.519 ± 0.972221 104.00312 Seed aggregate 8 83.966 ± 0.548948 90.0954 99.752 ± 1.077806 104.90402 Seed aggregate 9 84.193 ± 0.593941 91.31136 100.771 ± 0.751475 105.35924 Seed aggregate 10 84.405 ± 0.502514 92.03362 101.806 ± 0.802661 105.6436 Seed aggregate 11 84.625 ± 0.428112 92.98862 102.255 ± 0.763125 105.81476 Seed aggregate 12 84.959 ± 0.451114 94.05 102.765 ± 0.734282 106.0625 Seed aggregate 13 85.269 ± 0.558609 94.70076 103.116 ± 0.81168 106.2085 Seed aggregate 14 85.547 ± 0.693351 95.16 103.593 ± 0.874761 106.33938 Seed aggregate 15 86.256 ± 1.198275 95.50438 103.69 ± 0.874254 106.44586 Seed aggregate 16 86.649 ± 1.247728 95.6775 103.744 ± 0.862916 106.52976 Seed aggregate 17 87.093 ± 1.630738 95.93488 104.001 ± 0.899736 106.65712 Seed aggregate 18 87.366 ± 1.916566 96.038 104.137 ± 0.781458 106.773 Seed aggregate 19 87.847 ± 2.34779 96.12562 104.269 ± 0.645294 106.86698 Seed aggregate 20 88.679 ± 3.185008 96.22822 104.488 ± 0.69216 106.96326 Seed aggregate 21 89.004 ± 3.351165 96.28136 104.996 ± 0.920236 107.08174 Seed aggregate 22 89.475 ± 3.937453 96.36148 105.132 ± 0.918725 107.09436 Seed aggregate 23 89.909 ± 4.062802 96.41312 105.419 ± 0.845609 107.1051 Seed aggregate 24 90.044 ± 4.175172 96.47948 105.582 ± 1.015178 107.12536 Seed aggregate 25 90.266 ± 4.205298 96.535 105.644 ± 1.056231 107.22224 Seed aggregate 26 90.959 ± 4.338905 96.61586 105.77 ± 1.048795 107.26926 Seed aggregate 27 91.036 ± 4.303663 96.64362 105.88 ± 1.16691 107.27776 Seed aggregate 28 91.584 ± 4.40199 96.75938 105.88 ± 1.16691 107.279 Seed aggregate 29 91.866 ± 4.500126 96.77388 105.88 ± 1.16691 107.28026 Seed aggregate 30 92.22 ± 4.506812 96.87014 105.88 ± 1.16691 107.28026 Seed aggregate 31 92.562 ± 4.41413 96.94324 105.887 ± 1.158868 107.28376 Seed aggregate 32 92.728 ± 4.349474 97.08324 105.94 ± 1.219869 107.2965 Seed aggregate 33 93.067 ± 4.314632 97.24148 105.948 ± 1.210957 107.30438 Seed aggregate 34 93.333 ± 4.298141 97.49512 106.026 ± 1.143282 107.31526 Seed aggregate 35 93.652 ± 4.146568 97.66014 106.078 ± 1.112468 107.32388 Seed aggregate 36 94.372 ± 4.214719 98.12874 106.146 ± 1.076844 107.329 Seed aggregate 37 94.78 ± 4.292301 98.547 106.169 ± 1.052846 107.33938 Seed aggregate 38 94.969 ± 4.193567 98.96688 106.242 ± 1.090599 107.33938 Seed aggregate 39 95.27 ± 3.801106 99.70086 106.319 ± 1.107106 107.34774 Seed aggregate 40 95.52 ± 3.616132 100.19852 106.508 ± 1.118041 107.36662 Seed aggregate 41 95.732 ± 3.45787 100.55788 106.508 ± 1.118041 107.39538 Seed aggregate 42 95.945 ± 3.426205 100.75338 106.526 ± 1.107513 107.42812 Seed aggregate 43 96.042 ± 3.301616 100.85714 106.535 ± 1.099127 107.44574 Seed aggregate 44 96.213 ± 3.148659 100.90426 106.566 ± 1.097863 107.47486 Seed aggregate 45 96.322 ± 3.167677 100.96178 106.566 ± 1.097863 107.48098 Seed aggregate 46 96.501 ± 2.974028 101.1614 106.6 ± 1.091329 107.48774 Seed aggregate 47 96.596 ± 2.813628 101.3525 106.653 ± 1.06047 107.5065 Seed aggregate 48 96.714 ± 2.683631 101.56612 106.68 ± 1.056314 107.55912 Seed aggregate 49 96.819 ± 2.56574 101.61976 106.772 ± 1.098497 107.56812 Seed aggregate 50 97.044 ± 2.385746 101.84438 106.772 ± 1.098497 107.57774 Seed aggregate 51 97.186 ± 2.307246 101.88164 106.786 ± 1.083819 107.595 Seed aggregate 52 97.52 ± 2.262185 102.063 106.794 ± 1.075669 107.60436 Seed aggregate 53 97.693 ± 2.188412 102.23902 106.794 ± 1.075669 107.61336 Seed aggregate 54 97.774 ± 2.211365 102.329 106.822 ± 1.038102 107.64262 Seed aggregate 55 97.944 ± 1.937809 102.434 106.838 ± 1.040373 107.65238 Seed aggregate 56 97.998 ± 1.933263 102.48248 Not observed Not observed Seed aggregate 57 98.419 ± 1.418078 102.48722 Not observed Not observed Seed aggregate 58 98.722 ± 1.183709 102.5276 Not observed Not observed Seed aggregate 59 99.038 ± 1.223587 102.55262 Not observed Not observed Seed aggregate 60 99.099 ± 1.230416 102.59126 Not observed Not observed Seed aggregate 61 99.159 ± 1.25037 102.62712 Not observed Not observed Seed aggregate 62 99.27 ± 1.302198 102.65636 Not observed Not observed Seed aggregate Five seeds at every plotted round. Autoregressive runs stop at round 62; edit-based runs stop at round 55, the shortest supplied run for each method. Dashed lines show the best-16 mean. Which loop lengths make the selection? Bars show share of each method’s supplied selection. Counts and average negated energy stay beside each bar. LengthAutoregressive (AR)335 designsEdit-based (LevT)640 designs 11residues Autoregressive (AR)7 (2.1%)Mean energy 89.41 Edit-based (LevT)91 (14.2%)Mean energy 101.89 12residues Autoregressive (AR)18 (5.4%)Mean energy 89.7 Edit-based (LevT)37 (5.8%)Mean energy 101.08 13residues Autoregressive (AR)13 (3.9%)Mean energy 89.72 Edit-based (LevT)70 (10.9%)Mean energy 101.99 14residues Autoregressive (AR)22 (6.6%)Mean energy 89.93 Edit-based (LevT)49 (7.7%)Mean energy 102.04 15residues Autoregressive (AR)32 (9.6%)Mean energy 90.27 Edit-based (LevT)58 (9.1%)Mean energy 101.62 16residues Autoregressive (AR)24 (7.2%)Mean energy 91.93 Edit-based (LevT)79 (12.3%)Mean energy 102.81 17residues Autoregressive (AR)47 (14%)Mean energy 91.98 Edit-based (LevT)48 (7.5%)Mean energy 101.78 18residues Autoregressive (AR)71 (21.2%)Mean energy 97.36 Edit-based (LevT)52 (8.1%)Mean energy 101.14 19residues Autoregressive (AR)48 (14.3%)Mean energy 95.73 Edit-based (LevT)59 (9.2%)Mean energy 101.8 20residues Autoregressive (AR)53 (15.8%)Mean energy 95.03 Edit-based (LevT)97 (15.2%)Mean energy 102.68 View selection counts and mean energies Supplied selections contain 335 autoregressive and 640 edit-based designs. Percentages use each method’s own denominator. Method Length Count Total Share (%) Mean negated energy Autoregressive (AR) 11 7 335 2.089552 89.405714 Autoregressive (AR) 12 18 335 5.373134 89.705 Autoregressive (AR) 13 13 335 3.880597 89.723077 Autoregressive (AR) 14 22 335 6.567164 89.932273 Autoregressive (AR) 15 32 335 9.552239 90.266875 Autoregressive (AR) 16 24 335 7.164179 91.931667 Autoregressive (AR) 17 47 335 14.029851 91.977234 Autoregressive (AR) 18 71 335 21.19403 97.364225 Autoregressive (AR) 19 48 335 14.328358 95.734792 Autoregressive (AR) 20 53 335 15.820896 95.025283 Edit-based (LevT) 11 91 640 14.21875 101.892857 Edit-based (LevT) 12 37 640 5.78125 101.07973 Edit-based (LevT) 13 70 640 10.9375 101.989429 Edit-based (LevT) 14 49 640 7.65625 102.037551 Edit-based (LevT) 15 58 640 9.0625 101.617069 Edit-based (LevT) 16 79 640 12.34375 102.812785 Edit-based (LevT) 17 48 640 7.5 101.784104 Edit-based (LevT) 18 52 640 8.125 101.139808 Edit-based (LevT) 19 59 640 9.21875 101.803051 Edit-based (LevT) 20 97 640 15.15625 102.678866 Figure 5. Antibody CDR-H3 optimization and the length composition of supplied selected designs. Energy is shown with its sign reversed, so higher is better. Shading is ±1 population standard deviation across five seeds; the reference is the best loop in the 1,200-sequence screen. The length breakdown above is where this shows up most clearly. The autoregressive path takes the shortcut: half its selected designs are 18 residues or longer, and mean negated energy jumps from about 90 below length 17 to between 95 and 97 at lengths 18 to 20. The edit path does not. Its mean energy stays between 101 and 103 at every permitted length, fewer than a third of its designs reach 18 residues, and it finds comparable quality at the shortest and longest loops alike. The antibody runs are longer than the substitution benchmarks and were not round-matched: seeds ran between 55 and 70 rounds. We compare at round 55, the last round every seed of both methods reached: the mean per-seed median is 106.8 for the edit path against 97.9 for the autoregressive path. Only the edit path beats the single best loop in the 1,200-sequence initialization screen, crossing it on best-16 at round seven and on the median at round fourteen. Both paths exceed the screen median of 81.2, so both are doing real work. But one of them is partly being paid for length, and no fitness column would have surfaced that. You need the score stratified along whatever axis the assay rewards for free. On comparing to published numbers: our best designs reach -109.04 (edit) and -105.43 (autoregressive) raw binding energy, against -112.59 for Structured Q-learning and -112.58 for Stable online RL. Those entries are not budget-matched or search-space matched. The published methods use 1,000 proposals per seed in a fixed 11-residue space, while our paths search lengths 11 through 20 and count a 1,200-sequence screen against their budget. We report the row for context, not as a win or a loss. Every check so far has come from the same family of model: a learned predictor, or a hand-built scoring function with its own blind spots. The last check comes from somewhere else entirely, a structure model that was never trained on any of this fitness data. What AlphaFold confidence does and does not tell you We folded five sequences per task, method and regime (the three highest-fitness designs and the two most diverse) and read two AlphaFold confidence scores as diagnostics: pLDDT, 0 to 100, how reliably each residue is placed, and PAE, the model’s estimate of error between residue pairs. The useful signal turned out to be an association with distance rather than with fitness. Designs within roughly 5% of a sequence length from a measured high-fitness variant have median pLDDT 92.5. At 10% it drops to about 84, at 20% to 72, and designs nearly a full sequence length away land in the fifties. That association has a biological reading as well as a methodological one. AlphaFold’s confidence depends in part on the depth and quality of the multiple sequence alignment it can assemble, and a design far from any natural homolog has a shallower alignment to work from. Low pLDDT on a distant design can therefore mean the model has little evolutionary evidence to condition on, not that the sequence fails to fold. We cannot separate those two explanations from confidence scores alone. For a campaign it does not matter which is true. A design far from anything measured is harder for AlphaFold to judge, and less likely to work in the first place, since neither evolution nor the assay has been there. The trend flags designs that need experimental attention; it does not filter them out. The reverse does not hold. De novo designs sit far from any natural homolog and AlphaFold is often confident about them, so pLDDT is a poor read on evolutionary distance. The distance worth acting on is the one to a measured high-fitness variant, which is what High tracks. Structure and function stay distinct, and reporting only top-scoring designs hides things. On surrogate-guided GFP-hard, AdaLead’s diverse selections average pLDDT 29.9 against 92.9 for its top-fitness ones, a structural-confidence collapse in part of the batch that a top-only table would never show. PEX reaches pTM 0.917 (AlphaFold’s own estimate of overall fold confidence, 0 to 1) and pLDDT 92.2 with fitness of -0.046, while AdaLead has fitness 0.027 at pLDDT 29.9. A structural filter would not reproduce the functional ranking. Figure 06 Structural confidence tells a different story. Compare the supplied mean and best pTM scores across method/task/regime groups. GFP237 residues Median 0.9133 00.250.50.751 pTM score · 0 to 1 88 mean/best observations from 44 groups AAV28-residue window Median 0.3397 00.250.50.751 pTM score · 0 to 1 88 mean/best observations from 44 groups Group meanGroup bestMedian of displayed scores Hover, tap, or focus a point to see its method, task, feedback regime, and score. View all supplied pTM group summaries Supplied group summaries; each contributes one mean and one best value to the distribution. Method Task Feedback Mean pTM Best pTM Autoregressive (AR) AAV-hard oracle 0.346 0.37 Autoregressive (AR) AAV-hard surrogate 0.3313 0.38 Autoregressive (AR) AAV-medium oracle 0.368 0.39 Autoregressive (AR) AAV-medium surrogate 0.322 0.36 Autoregressive (AR) GFP-hard oracle 0.904 0.91 Autoregressive (AR) GFP-hard surrogate 0.9087 0.91 Autoregressive (AR) GFP-medium oracle 0.912 0.92 Autoregressive (AR) GFP-medium surrogate 0.9093 0.91 AdaLead AAV-hard oracle 0.2847 0.34 AdaLead AAV-hard surrogate 0.154 0.23 AdaLead AAV-medium oracle 0.252 0.36 AdaLead AAV-medium surrogate 0.3393 0.37 AdaLead GFP-hard oracle 0.92 0.92 AdaLead GFP-hard surrogate 0.9207 0.93 AdaLead GFP-medium oracle 0.9267 0.93 AdaLead GFP-medium surrogate 0.9167 0.92 Bayesian optimization AAV-hard oracle 0.224 0.35 Bayesian optimization AAV-hard surrogate 0.1813 0.28 Bayesian optimization AAV-medium oracle 0.3307 0.37 Bayesian optimization AAV-medium surrogate 0.2647 0.37 Bayesian optimization GFP-hard oracle 0.774 0.79 Bayesian optimization GFP-hard surrogate 0.9093 0.92 Bayesian optimization GFP-medium oracle 0.9093 0.92 Bayesian optimization GFP-medium surrogate 0.9013 0.93 Fixed-length (CE) AAV-hard oracle 0.3133 0.39 Fixed-length (CE) AAV-hard surrogate 0.2287 0.36 Fixed-length (CE) AAV-medium oracle 0.2493 0.35 Fixed-length (CE) AAV-medium surrogate 0.31 0.37 Fixed-length (CE) GFP-hard oracle 0.9033 0.91 Fixed-length (CE) GFP-hard surrogate 0.9053 0.92 Fixed-length (CE) GFP-medium oracle 0.9133 0.92 Fixed-length (CE) GFP-medium surrogate 0.9133 0.92 CMA-ES AAV-hard oracle 0.295 0.42 CMA-ES AAV-hard surrogate 0.314 0.4 CMA-ES AAV-medium oracle 0.3347 0.4 CMA-ES AAV-medium surrogate 0.3033 0.37 CMA-ES GFP-hard oracle 0.1627 0.2 CMA-ES GFP-hard surrogate 0.46 0.78 CMA-ES GFP-medium oracle 0.5327 0.92 CMA-ES GFP-medium surrogate 0.474 0.92 Latent CMA-ES AAV-hard oracle 0.2267 0.37 Latent CMA-ES AAV-hard surrogate 0.34 0.36 Latent CMA-ES AAV-medium oracle 0.312 0.36 Latent CMA-ES AAV-medium surrogate 0.3373 0.37 Latent CMA-ES GFP-hard oracle 0.91 0.91 Latent CMA-ES GFP-hard surrogate 0.91 0.91 Latent CMA-ES GFP-medium oracle 0.916 0.92 Latent CMA-ES GFP-medium surrogate 0.9107 0.92 DPO (ProtGPT2) AAV-hard oracle 0.248 0.37 DPO (ProtGPT2) AAV-medium oracle 0.4087 0.45 DPO (ProtGPT2) GFP-hard oracle 0.896 0.92 DPO (ProtGPT2) GFP-medium oracle 0.8793 0.92 DPO (ZymCTRL) AAV-hard oracle 0.2093 0.36 DPO (ZymCTRL) AAV-medium oracle 0.4327 0.46 DPO (ZymCTRL) GFP-hard oracle 0.92 0.92 DPO (ZymCTRL) GFP-medium oracle 0.9253 0.93 LatProtRL AAV-hard oracle 0.3507 0.39 LatProtRL AAV-hard surrogate 0.348 0.37 LatProtRL AAV-medium oracle 0.3333 0.38 LatProtRL AAV-medium surrogate 0.332 0.37 LatProtRL GFP-hard oracle 0.9107 0.92 LatProtRL GFP-hard surrogate 0.91 0.91 LatProtRL GFP-medium oracle 0.9107 0.92 LatProtRL GFP-medium surrogate 0.9113 0.92 Edit-based (LevT) AAV-hard oracle 0.2513 0.38 Edit-based (LevT) AAV-hard surrogate 0.2513 0.4 Edit-based (LevT) AAV-medium oracle 0.2187 0.33 Edit-based (LevT) AAV-medium surrogate 0.212 0.28 Edit-based (LevT) GFP-hard oracle 0.9147 0.92 Edit-based (LevT) GFP-hard surrogate 0.9253 0.93 Edit-based (LevT) GFP-medium oracle 0.864 0.87 Edit-based (LevT) GFP-medium surrogate 0.902 0.91 PEX AAV-hard oracle 0.2327 0.31 PEX AAV-hard surrogate 0.2873 0.42 PEX AAV-medium oracle 0.2373 0.34 PEX AAV-medium surrogate 0.3307 0.37 PEX GFP-hard oracle 0.9207 0.93 PEX GFP-hard surrogate 0.9173 0.93 PEX GFP-medium oracle 0.92 0.92 PEX GFP-medium surrogate 0.916 0.92 µSearch AAV-hard oracle 0.281 0.33 µSearch AAV-hard surrogate 0.2173 0.26 µSearch AAV-medium oracle 0.337 0.382 µSearch AAV-medium surrogate 0.3013 0.36 µSearch GFP-hard oracle 0.883 0.89 µSearch GFP-hard surrogate 0.8967 0.91 µSearch GFP-medium oracle 0.897 0.9 µSearch GFP-medium surrogate 0.9187 0.93 Figure 6. Mean and best pTM values from the supplied method/task/regime group summaries, pooled into GFP and AAV. Vertical lines mark the median of displayed mean/best scores. Vertical point placement only separates overlaps; it carries no data. On the 28-residue AAV window, pTM sits in a uniformly low band, 0.15 to 0.46 across all methods, and resolves nothing. That is the expected mismatch between a global topology score and an isolated fragment, and it is why we report those columns as window-level diagnostics rather than capsid-level validation. Caveats Everything here is in silico. Learned fitness values indicate resemblance to labelled high-fitness regions rather than measured function, Absolut! energies are lattice calculations, and AlphaFold outputs are confidence estimates rather than experimental validation. The insertion-aware oracle has a rank correlation (Spearman) of 0.863 with true fitness on the full landscape, but only 0.301 and 0.196 on the restricted medium and hard bands, so it supports comparisons under a shared scoring model and does not establish that any individual design is good. Query budgets are matched within a regime; initialization procedures and internal computation are not. We kept each method’s native initialization, because forcing a common one would alter the published algorithms, which does mean part of a measured distance can reflect the starting set rather than the search rule. Five seeds cannot resolve narrow differences. Several oracle-guided runs are still improving at round 15, so those margins are budget-dependent lower bounds. Wall-clock time was not recorded for the baseline sweeps, so nothing here ranks methods by computational efficiency. One scope limit is worth stating plainly, because it is the gap between this study and a real campaign. Every experiment optimizes a single fitness objective at a time. Actual protein engineering balances activity against stability, solubility and developability, and a design that wins on one axis can be useless on another. The framework has the multi-objective machinery built, with reward providers that combine several components behind the same interface, but we never exercised it. No result in this work is a multi-objective result. We expect the evaluator-dependence reported above to get worse under combined rewards, not better: each additional component is another approximation with its own exploitable weaknesses. That makes calibration and shortcut analysis more important, not less. What we would tell anyone benchmarking a sequence optimizer Re-run, do not cite. Published numbers are point estimates under each paper’s own protocol. The regime gap, the single most informative quantity we computed, needs both regimes for the same method under one budget. It cannot be assembled from the literature. Report both feedback regimes, separately. A method’s oracle-guided ranking does not predict its surrogate-guided ranking, and the realistic setting is the second one. Averaging them, or reporting only the first, hides the failure mode you will actually hit. Rescore every round with the held-out oracle. Endpoint fitness cannot distinguish a search that improved from one that peaked at round three and ended below that peak. The trajectory shows the difference; the final number does not. Carry the distance diagnostics. Fitness alone cannot separate productive extrapolation from evaluator exploitation. Novelty paired with distance to a measured variant can. Stratify by whatever your assay rewards for free. If the scoring function has a shortcut, whether length, composition or a contact window, some policy will find it. Report the score broken down along that axis, not only in aggregate. The thesis, “Guided Generative Protein Design Using Reinforcement Learning,” was completed at Instituto Superior Técnico, Universidade de Lisboa, in collaboration with Loka, supervised by Prof. Mário Figueiredo, Eng.ª Patrícia Rocha and Eng.º Telmo Felgueira."},{"href":"/checking-llm-answers-against-tool-results-without-blowing-up-context/","title":"Checking LLM Answers Against Tool Results Without Blowing Up Context","description":"Guilherme Ribeiro compares five grounding checks across 32 synthetic test cases, measuring accuracy, latency, and token use as tool-result evidence grows.","abstract":"Guilherme Ribeiro compares five grounding checks across 32 synthetic test cases, measuring accuracy, latency, and token use as tool-result evidence grows.","tags":["AI Agents","Amazon Bedrock","Strands Agents","LLM Evaluation","Grounding","Benchmarks"],"topics":["agents","benchmarks"],"authors":["Guilherme Ribeiro"],"text":"How do you keep a cheap, fast grounding check reliable when the evidence it has to read keeps growing? The setup Say you’re building an assistant that answers questions about a patient’s medications. It has tools like get_medications, and it calls them as needed to answer things like “what is this patient currently taking?”. Because this kind of assistant is one hallucinated detail away from misleading a clinician, suggesting conflicting medications, or affecting a patient’s treatment, every response needs a grounding guardrail: a check that verifies the assistant’s answer is actually backed by the tool results it was given. To run that check on every single turn without tanking latency or cost, the natural choice is a small, fast model like Anthropic Claude Haiku. Not the frontier model generating the answer itself. That works fine at first. The trouble starts as sessions get longer. More tool calls, more paginated results, more history and the evidence grows well past what a small model can reliably reason over in one pass. The problem: splitting evidence breaks multi-fact answers The first instinct is to split the evidence into chunks and check each one in parallel. Each chunk gets checked independently, and the verdicts get combined at the end. This has a problem: if a response is grounded by two different facts that happen to live in two different chunks, each chunk only ever sees half the picture. For example: “[…] this patient is currently taking medication A for blood pressure and medication B for cholesterol.” Medication A’s record lives in one page of tool results; medication B’s lives in another. If the guardrail checks each chunk against the whole response, chunk 1 only ever confirms half of it, chunk 2 only confirms the other half. A naive logic like “every chunk must fully confirm the response” fails the whole thing, even though the two chunks together fully support it. Why independent chunk checks fail User questionWhat is this patient taking? Call get_medicationsTool results arrive in separate pages. Page 1Medication A Page 2Medication B Assistant responseThe patient is taking medication A and medication B. Each check gets the whole answer but only its own page Chunk 1 checkConfirms medication A only. Chunk 2 checkConfirms medication B only. Naive reduce: rejectNeither chunk confirms the complete answer on its own. The answer needs both pages. Each isolated check sees only one medication, so requiring every chunk to confirm the whole answer rejects a supported response. We built and tested five approaches to this problem, using Strands agents on Amazon Bedrock with Claude Haiku 4.5 as the judge model, and ran each one against 32 synthetic test cases. The approaches The code snippets below show the structure of each approach; parallel execution and implementation details are omitted. A. Per-claim map, code reduce First, one LLM call breaks the response into atomic claims. Each chunk then gets the full claim list but only its own slice of evidence. Instead of returning one verdict for the whole response, the judge model returns a verdict per claim: supported, contradicted, or not_addressed. A plain code reduce step then combines the per-claim verdicts across chunks. No extra LLM call. A · Per-claim map, code reduce Assistant responseThe answer to verify. Extract atomic claimsOne model call creates the shared claim list. Parallel checks · full claim list + local evidence Judge chunk 1Supported, contradicted, or not_addressed per claim. Judge chunk 2Supported, contradicted, or not_addressed per claim. Combine labels in codeFor each claim: at least one support, no contradiction. Final verdictGrounded only if every claim passes. Every judge receives the same claims and one evidence slice. Code combines the per-claim labels across chunks; there is no final model call. def verify_response(response, evidence_chunks): claims = extract_claims(response) # one LLM call: list of atomic claims votes = {claim: [] for claim in claims} for chunk in evidence_chunks: # run in parallel chunk_verdicts = judge_model.run( PER_CLAIM_PROMPT, claims=claims, evidence=chunk ) # -> {claim: \"supported\" | \"contradicted\" | \"not_addressed\"} for claim, verdict in chunk_verdicts.items(): votes[claim].append(verdict) # a claim is grounded if ANY chunk supports it and NONE contradict it grounded = { claim: \"contradicted\" not in v and \"supported\" in v for claim, v in votes.items() } return all(grounded.values()) A claim is grounded if any chunk supports it and none contradict it. So evidence for medication A and evidence for medication B can live in different chunks and still both count. Pros Tied with B as the fastest of the five (5.9s avg). All judge calls run in parallel, and the reduce step is plain code with no extra LLM call. Cons Its misses come in two shapes. The first is a claim that depends on finding or assembling evidence within a very large record set, such as a single fact among 1,500 encounter records. Each chunk only votes on the slice it can see, so when no single chunk holds enough of the picture, the OR-reduce comes up empty even though the response is correct. The second is a later record that cancels or replaces an earlier one by ID only. That chunk looks unrelated on its own, so it votes not_addressed, and the OR-reduce keeps the earlier “supported”. B. Extractive map, single reduce Each chunk doesn’t render a verdict at all. It extracts relevant quotes and reasoning. All extractions get concatenated, and one final call makes the actual judgment call over the combined evidence. B · Extractive map, single reduce Assistant responseShared with every extraction call. Parallel extraction · one evidence slice per call Extract from chunk 1Relevant quotes and reasoning; no verdict. Extract from chunk 2Relevant quotes and reasoning; no verdict. Concatenate extractionsPlain code gathers the evidence into one context. Single final judgeReads the answer and all extracted evidence. Final verdictOne grounding decision. Extraction happens in parallel, without a verdict. One final judge sees the evidence collected from all chunks together. def verify_response(response, evidence_chunks): extractions = [ judge_model.run(EXTRACT_PROMPT, response=response, evidence=chunk) for chunk in evidence_chunks # run in parallel, no verdict yet ] combined_evidence = \"\\n\".join(extractions) verdict = judge_model.run( FINAL_JUDGMENT_PROMPT, response=response, evidence=combined_evidence ) return verdict.is_grounded Pros Its single final reduce call sees every chunk’s extracted evidence at once, so it can assemble claims that span chunks. It’s also one of only two approaches to pass the hardest long-range case in the set: a 150-point noisy lab trend spread across 44 tool-result pages. Cons Unlike approach A, where the judge labels each claim as supported, contradicted, or not_addressed, B’s extractions are free-form, so nothing in them separates “not covered by this chunk” from “disputed by this chunk”. That shows up as silence being read as a problem: in one case, B rejected a correct response because the extracted evidence had no medication names, and concluded the claims could not be supported. It also doesn’t fully escape the problem it was meant to solve. The final call reads every chunk’s extraction at once, so as responses carry more claims and evidence spreads across more chunks, that single call grows with them. That puts the small judge model back where the article started: reasoning over more context than it can reliably handle in one pass. C. Code-executing agent Instead of reading the tool results as raw text, an agent queries them with code. It has exactly one tool: run arbitrary Python against the real tool-result data, which is already loaded in a sandbox as ordinary variables (lists, dicts, tables). For each claim in the response, the agent writes a small snippet, such as filtering rows, counting items, or cross-referencing two fields. The sandbox runs it, and only the short printed output goes back to the agent, so the raw data never enters the model’s context. Once it has checked everything, the agent writes a plain-text summary of what it found, and that summary is all the final judge call ever sees. C · Code-executing agent Assistant responseThe claims the agent must verify. Full tool-result datasetLoaded as variables in the sandbox. Query loop Agent ↔ Python sandboxThe agent writes code. Python queries the full dataset and returns short printed results.Repeat as needed within the step budget Plain-text evidence summaryThe agent summarizes what it checked. Final judgeReads the answer and the summary. Final verdictOne grounding decision. The complete dataset stays in the Python sandbox. The agent sees query results, and the final judge sees only the agent’s summary. def verify_response(response, tool_results): agent = Agent( tools=[run_python_against(tool_results)], system_prompt=CODE_AGENT_SYSTEM_PROMPT, ) summary = agent.run( f\"Verify every claim in this response against the underlying data:\\n{response}\" ) verdict = judge_model.run( FINAL_JUDGMENT_PROMPT, response=response, evidence=summary ) return verdict.is_grounded Pros The lowest input-token count of the five (~5,884 avg), and on the four production-scale test cases, roughly 4.5–25× fewer input tokens than the next-cheapest approach. It never splits the evidence: the code runs against the entire dataset at once, so medication A on page 1 and medication B on page 2 are just two rows in the same Python object. Because it queries the data instead of reading it, its cost follows how much exploration a claim needs rather than how much data exists. That’s also why it handles the 150-point lab trend case, which breaks three of the other four approaches (A, D and E). Cons Slower than A and B. Each step in the agent loop is a full round trip: the model writes a snippet, the sandbox runs it, and the model reads the output before deciding what to check next, and those steps can’t run in parallel. More importantly, it only verifies what it decides to query. Its misses are the cases where a later record invalidates an earlier one by ID, date or snapshot: the agent confirms the medication in the medication list and never queries the other tool’s data, where the cancellation lives. Its step budget is also a design risk: a claim that needs a long, many-step investigation could run out of steps before the agent has the full picture. D. Embedding-retrieval evidence selection Instead of splitting tool data into arbitrary sequential chunks, embed the response’s claims and the tool-result data, then retrieve only the top_k most relevant spans per claim before verification. This targets the split-fact problem head-on: retrieval can pull both medication A’s span and medication B’s span into the same evidence set for a single claim, regardless of where they originally sat. D · Embedding retrieval Assistant responseThe answer to verify. Tool-result recordsAll available evidence. Extract atomic claimsCreate one list of factual claims. Embed and indexPrepare searchable evidence once per turn. Retrieve top-k spans per claimSelected spans can cross page boundaries. One check per claim Judge claim 1Read its retrieved evidence. Judge claim 2Read its retrieved evidence. Combine claim verdictsGrounded only if every claim is supported. Retrieval selects the top-k spans for each claim, even when they come from different original pages. Every claim is then judged on its selected evidence. def verify_response(response, tool_results): claims = extract_claims(response) index = build_embedding_index(tool_results) # chunk + embed once per turn grounded = {} for claim in claims: relevant_spans = index.search(claim, top_k=3) # can cross chunk boundaries verdict = judge_model.run( PER_CLAIM_PROMPT, claim=claim, evidence=relevant_spans ) grounded[claim] = verdict.is_supported return all(grounded.values()) Pros Works well for claims that rest on a few specific facts, and has the lowest output-token cost of the five (~564 avg), since each per-claim call returns one short verdict. Cons 75% accuracy, and its main limitation is choosing k. Claims draw on very different amounts of evidence, and a fixed k, or even a similarity threshold, can’t adapt to that: too small and claims that span many records can’t be verified, too large and the judge wades through irrelevant spans. It also makes by far the most calls of any approach (367.4 on average), because it embeds every record separately, which keeps its latency (11.9s) well above A and B. E. Refine / iterative sequential chain Process chunks one at a time, carrying forward a running verdict that gets revised, not just OR’d, as each new chunk arrives. Closer to the “refine” pattern used in iterative summarization than to classic map-reduce. This targets approach A’s mechanical-OR blind spot, since a later chunk can walk back an earlier chunk’s incorrect “supported” verdict instead of only ever adding to it. E · Sequential refine Assistant responseThe answer to verify. Extract atomic claimsOne model call creates the claim list. Initialize per-claim labelsEvery claim starts as not_addressed. Sequential · one chunk after another Refine the running verdictRead the next chunk with the previous labels. Revise each claim as new evidence arrives.Carry revised labels into the next step Final verdictGrounded only if every final label is supported. Each chunk can upgrade or downgrade earlier labels. The chain carries per-claim verdicts forward, rather than the underlying evidence. def verify_response(response, evidence_chunks): claims = extract_claims(response) # one LLM call: list of atomic claims running_verdict = {claim: \"not_addressed\" for claim in claims} for chunk in evidence_chunks: # sequential, not parallel running_verdict = judge_model.run( REFINE_PROMPT, claims=claims, evidence=chunk, previous_verdict=running_verdict, ) # can upgrade OR downgrade any claim's verdict return all(v == \"supported\" for v in running_verdict.values()) Pros Its running verdict can walk back an earlier “supported” when a later chunk changes the picture, which a mechanical OR-reduce cannot do. We saw this happen: a later note discontinued “the medication started on 2026-01-10” without naming it, and E downgraded the claim that A’s OR-reduce kept as supported. And unlike D, its call count doesn’t scale with record count: it processes one chunk per call regardless of how many records that chunk contains. Cons 75% accuracy, one case more than A, which isn’t enough to call it more accurate. The running verdict carries forward per-claim labels rather than the evidence behind them, so claims that need many records seen together stay out of reach, and so do invalidations that only make sense next to the earlier record’s details. It’s also the slowest and most input-heavy approach of the five (18.0s avg, ~23,759 input tokens), since each refine call depends on the last and none can run in parallel. What we measured We ran a 160-run sweep (32 test cases × 5 approaches). The test cases include a category where a later record invalidates an earlier one using only an ID, date or snapshot, such as an order cancelled by order number, a superseded prescription, a medication list that turns out to be an archived snapshot, or vitals from a previous encounter. Approach AccuracyHigher is better Average latencyLower is better Average input tokensLower is better APer-claim map, code reduce Accuracy72% Average latency5.9 s Average input tokens~22,622 BExtractive map, single reduce Accuracy81% Average latency6.0 s Average input tokens~18,183 CCode-executing agent Accuracy84% Average latency8.6 s Average input tokens~5,884 DEmbedding retrieval Accuracy75% Average latency11.9 s Average input tokens~19,614 ERefine sequential chain Accuracy75% Average latency18.0 s Average input tokens~23,759 All bars start at zero. Scales: accuracy 0–100%; latency 0–20 s; input tokens 0–25,000. View all benchmark values, including output tokens Approach Accuracy Latency Input tokens Output tokens A: Per-claim map, code reduce 72% 5.9 s ~22,622 ~2,716 B: Extractive map, single reduce 81% 6.0 s ~18,183 ~812 C: Code-executing agent 84% 8.6 s ~5,884 ~775 D: Embedding retrieval 75% 11.9 s ~19,614 ~564 E: Refine sequential chain 75% 18.0 s ~23,759 ~2,426 32 synthetic cases per approach. Latency and token counts are averages; token counts are approximate. No repeated runs or confidence intervals were supplied. In Conclusion The split-fact scenario we started with turned out to be a good first test: all five approaches handle it once they stop judging each chunk in isolation. The experiments pointed to two harder problems. The first is claims that have to be assembled from a large evidence set rather than confirmed by one localized fact, where the approaches differ most in accuracy and in cost. The second is records that invalidate earlier ones by reference only. Three of those cases, a cancelled order, a superseded prescription, and an archived snapshot, were missed by all five approaches. A (per-claim map, code reduce) is tied for fastest. It works well when each claim can be confirmed by a fact within a single chunk, and breaks when evidence is spread across a large record set or when a later record invalidates an earlier one by ID only. B (extractive map, single reduce) is tied for fastest and can assemble claims that span chunks, because one final call sees all the extracted evidence. Its free-form extractions can read silence as a problem, and that final call grows as the evidence does. C (code-executing agent) uses the fewest input tokens by a wide margin, especially on the largest cases, because it queries the data instead of reading it. It only verifies what it chooses to query, so it can miss invalidations that live in another tool’s data, and its step budget limits how far it can explore. D (embedding retrieval) works well for claims that rest on a few facts and has the lowest output-token cost. Its weakness is choosing k: a fixed window, even with thresholding, can’t adapt to how much evidence each claim needs. It also makes by far the most calls. E (refine) can walk back an earlier “supported” verdict when a later chunk changes the picture. But it carries labels forward rather than evidence, and it’s the slowest and most input-heavy approach of the five. No approach wins on every axis, so here’s what we’d pick. For grounding checks over large tool results, the code-executing agent is the best value of the five: the highest accuracy in our tests, on par with B, at a fraction of the input tokens, roughly 4.5–25× fewer than the next-cheapest approach on the largest cases. It comes with two limitations. It’s slower than A and B (8.6s against 5.9–6.0s), and it only checks what it decides to query, so it can miss a cancellation or a superseded record that lives in another tool’s data. If latency matters most and your claims usually rest on facts within a single page of results, the per-claim map (A) or the extractive map (B) are fast, simpler alternatives. And if your data has records that invalidate others by reference only, none of these approaches is enough on its own yet. If you’ve built something similar, tried a different chunking strategy or reduce logic, or taken a completely different route, we’d like to hear about it. Email Guilherme. References RAG Faithfulness — definition and measurement, Deepchecks Ragas metrics explained: faithfulness and claim decomposition, Saulius Šlekys Self-Correcting RAG: Enhancing Faithfulness via MMKP Context Selection and NLI-Guided MCTS, arXiv:2604.10734 HalluciNot: Hallucination Detection Through Context and Common Knowledge Verification, arXiv:2504.07069 VISTA: Verification In Sequential Turn-based Assessment, arXiv:2510.27052 awesome-hallucination-detection, EdinburghNLP — curated list of hallucination-detection research Summarization with LangChain — Stuff, Map-Reduce, Refine, Abonia Sojasingarayar — background on the refine-chain pattern behind Approach E"},{"href":"/knowledge-graph-alignment-at-scale/","title":"Knowledge graph alignment at scale: fast, cheap, and (sometimes) right","description":"Four AI judges, 8,524 entity pairs, and two domains: where decision models compete with reasoning LLMs, and how a threshold can turn good rankings into a human-review backlog.","abstract":"Four AI judges, 8,524 entity pairs, and two domains: where decision models compete with reasoning LLMs, and how a threshold can turn good rankings into a human-review backlog.","tags":["Knowledge Graphs","Entity Alignment","Decision Models","Jev","Benchmarks"],"topics":["benchmarks"],"authors":["Alexandre Domingues"],"text":"Can a cheap, fast decision model stand in for a reasoning LLM? We tested two decision models (Jev and Strands Decider) against Claude Haiku and Claude Sonnet on a real entity-alignment pipeline: 8,524 pairs across two domains. We rebuilt a knowledge-graph-alignment pipeline so that the judging step is a pluggable component, then ran the same 8,524 candidate pairs, from two domains, through four AI judges. Two are decision models: they return a structured probability directly, without writing any text. The other two are general-purpose reasoning models that generate their answer as text. The best decision model, Jev, matched the strongest reasoning model on the final merge decision on one dataset and came within a few points on the other, at more than 100 times lower cost. Against the cheapest reasoning model in this comparison, Jev was cheaper and about 5 times faster than Claude Haiku; the draft’s conflicting Haiku cost figures are noted below. Not every decision model is there yet: the open-weight Strands Decider scored barely above a baseline with no language model on one dataset, and below it on the other. And one reasoning model’s F1 collapsed on one dataset, not because it judged badly but because of how its decision threshold was chosen. Below are the results, what they mean for anyone running judgments at high volume, and where reasoning models still earn their keep. The problem: merging two things that say almost the same thing Any organization that works with more than one knowledge source eventually ends up with multiple taxonomies, ontologies or product catalogs and no clean mapping between them. Is “Software Developer” in one system the same job as “Applications Programmer” in another? Is “DOID:0050741” the same disease concept as “NCIT:C34798”? At the scale of a real taxonomy, answering this takes thousands to millions of pairwise judgments. Each one needs more than a yes or no: is it an exact match, is one broader or narrower than the other, are they merely related, or are they unrelated? The two standard approaches have limits. Lexical and rule-based matching (string similarity, shared keywords) are fast and free, but brittle. Both miss paraphrases and synonyms, and can’t separate an exact match from a related but distinct concept without a lot of hand-tuned logic. The newer default is to put an LLM in the loop: show it both entities and ask it to judge the relationship. That works well, but cost and latency grow linearly with the number of candidate pairs, and exhaustive alignment between two sources requires the product of their entity counts in candidate comparisons. A newer category of model targets that gap. Decision models like TypeSafe’s Jev and the open-weight Strands Decider turn a prompt directly into a typed judgment: a probability distribution over relation types, returned in a single step, with no generated text to parse. If one of them can match a reasoning model’s judgment quality at a fraction of the cost and latency, high-volume judging pipelines get much cheaper to run. So we tested it. We built kgalign, a knowledge-graph-alignment pipeline with a swappable judging stage, and ran the same entity pairs through Jev, Strands Decider, Claude Haiku and Claude Sonnet. The question was whether a decision model can do a reasoning model’s job on a real task, at a fraction of the cost. The short answer is yes for one of them, with caveats worth knowing. Meet the four judges Judge Type Model Cost per 1k pairs Typical latency Where it runs Jev Decision model jev-1.13.0 (TypeSafe) ~$0.04 ~0.25 s Cloud API Strands Decider Decision model strands-decider-2B-hobson-v19, open-weight (Apache-2.0), LoRA + classifier head on Qwen3.5-2B-Base $0 API fees‡ ~2.5-2.9 s on a laptop GPU* Local / on-device Claude Haiku 5.5 Reasoning Bedrock, general-purpose LLM ~$1.7† ~1.3 s Cloud API Claude Sonnet 5.5 Reasoning Bedrock, strongest reasoning in this lineup ~$4.1-4.3 ~1.8 s Cloud API *Decider’s latency isn’t a fair comparison: it ran on a low-end consumer laptop GPU, while the others ran on dedicated cloud infrastructure. It’s included for completeness and shouldn’t be read as a ranking. The table shows the cost gap before any accuracy numbers come in. Jev is more than 100 times cheaper than Sonnet on the draft’s reported figures. Decider has no API fees; local hardware and electricity still have a cost. The Haiku cost figures conflict, so we do not calculate a cost ratio for it. The question is what you give up for that. We also ran a simple logistic-regression baseline, fit on lexical and embedding similarity scores. It isn’t a fifth contender. It shows how far you get with no language model at all. We chose entity alignment as the testbed on purpose. Every answer is a typed label that can be checked against real gold data, so we can score accuracy and relation type directly. The task also needs calibrated confidence, because the downstream pipeline uses a probability threshold to decide whether to auto-merge a pair, send it to human review, or reject it. And it runs at a volume where differences in cost and latency matter. 01 / The experiment One pipeline. Four ways to judge. Only the judging stage changes. The pairs and evaluation rule stay the same. 01 Two knowledge sources Occupation catalogs or disease ontologies. Different words, potentially the same concept. Entities + descriptions 02 Retrieve candidates Lexical and embedding similarity narrow the search to plausible pairs. 8,524 shared pairs 03 Swap the judge Jev · Strands Decider · Claude Haiku · Claude Sonnet Same input, four judges 04 Apply a frozen cutoff Choose the merge threshold on development data, then apply it to the test split. 99% dev precision target RejectHuman reviewAuto-merge Candidate retrieval reduces the search space; the judge supplies a match probability and relation type. A lower cutoff separates rejection from review. Methodology: same pairs, same rules, two domains We used two public datasets whose text reads very differently: ESCO ↔ O*NET (occupations). ESCO is the European Commission’s multilingual classification of skills, competences and occupations. O*NET is the US Department of Labor’s occupational database. The European Commission publishes an official crosswalk between the two that labels each occupation pair as an exact, broader, narrower or close match. We used ESCO v1.2.1 (3,027 occupations) and O*NET 31.0 (1,016 occupations). The labels are descriptive and often paraphrased (“Software Developer” vs. “Applications Programmer”), so a judge has to understand what a job involves, not just compare titles. Bio-ML NCIT ↔ DOID (diseases). Bio-ML is the biomedical track of the Ontology Alignment Evaluation Initiative (OAEI), a long-running benchmark for ontology-matching systems. The NCIT ↔ DOID pair aligns the US National Cancer Institute Thesaurus with the Human Disease Ontology. We used the 2024 release (Zenodo, CC BY 4.0), restricted to the classes marked for alignment: 6,835 in NCIT and 8,448 in DOID. The vocabulary is dense, literal and hierarchical, and most DOID classes in this release have no text definition, only a name. Both ship with official gold-standard alignments, allowing the same candidate pairs to be scored against reference labels. No confidence intervals or significance tests were supplied for this comparison. Every judge saw the same candidate pairs and the same input text, so none got an easier or richer description than another. For each judge, we selected the decision threshold (the probability cutoff for auto-merging a pair) once on a held-out development split and then froze it. We scored the test split once against those frozen thresholds and never tuned on the data we report. Both Claude models ran with extended thinking turned off (their lowest thinking setting) and answered through the same structured tool call. Sonnet doesn’t accept a forced tool call, so it was told to answer with the tool, and it did every time. The runs covered 2,913 pairs on ESCO↔O*NET and 5,611 on Bio-ML NCIT↔DOID, 8,524 in total, each scored by all four judges and the baseline. The draft reports total spend of $46 and a Jev cost of $0.30 across both datasets. Its itemized costs do not reconcile with that total; see the reporting note below. Decider and the baseline incur no API fees. How we scored the judges For every pair, each judge returns a probability that the two entities are the same thing, plus its best guess at the relation type. Turning that probability into an action takes a threshold. The pipeline auto-merges a pair when the probability is at or above a merge cutoff, rejects it when it falls below a lower cutoff, and sends everything in between to human review. We set each judge’s merge cutoff with one rule: the lowest value that gives at least 99% precision on the development split, so auto-merges are almost never wrong. That cutoff is then frozen and applied unchanged to the test split. For the match metrics, a pair counts as positive when its gold label is an exact match. Pairs the ESCO crosswalk labels “close” are left out, and candidate pairs with no gold label count as non-matches. F1 at the merge cutoff (decision quality). Precision is the share of auto-merged pairs that really are exact matches. Recall is the share of real exact matches that got auto-merged. F1 is their harmonic mean, so it’s only high when both are. It scores the decision the pipeline makes, so it depends on the judge and on the cutoff. AUPRC (ranking quality). Sort all pairs by the judge’s probability and lower the cutoff step by step, tracking precision and recall at each step. AUPRC is the area under the resulting precision-recall curve. A score of 1.0 means every true match is ranked above every non-match. Because it covers every possible cutoff, it measures how well the judge orders pairs, independent of the threshold. Relation-typing macro-F1. On pairs with a gold relation, we compare the judge’s predicted relation (exact, broader, narrower, related or unrelated) with the gold one, compute F1 for each relation type that occurs in the dataset’s gold labels, and average them with equal weight. Those types are exact and narrower on Bio-ML, plus broader on ESCO. Equal weighting stops a judge from scoring well by handling only the common type. A judge that predicts a type absent from the gold labels, such as “related”, is still penalized, because that pair counts as a miss for its true type. ECE and Brier score (calibration). These check whether the probabilities can be taken literally. ECE groups pairs into 15 bins by predicted probability and measures, on average, how far each bin’s predicted probability is from the share of true matches in it. Brier score is the mean squared difference between the predicted probability and the actual outcome (1 for a match, 0 otherwise). Lower is better for both. Results: no single winner, and one surprise No judge wins everywhere. On ESCO↔O*NET, Jev and both reasoning models have close point estimates on the final merge decision (F1 0.811 for Sonnet, 0.808 for Jev, 0.797 for Haiku). Sonnet has the best ranking quality (AUPRC 0.887) and the best relation typing (macro-F1 0.693). On Bio-ML NCIT↔DOID, Sonnet leads Jev on F1 by 0.042 F1 (0.853 against 0.811). Strands Decider and the baseline trail far behind on every metric that involves getting the relationship type right. Dataset Judge F1 AUPRC Relation macro-F1 ECE ↓ Brier ↓ ESCO↔O*NET Jev 0.808 0.829 0.572 0.079 0.068 ESCO↔O*NET Claude Haiku 0.797 0.854 0.585 0.047 0.048 ESCO↔O*NET Claude Sonnet 0.811 0.887 0.693 0.046 0.037 ESCO↔O*NET Strands Decider 0.333 0.746 0.204 0.096 0.093 ESCO↔O*NET Baseline (no LLM) 0.499 0.769 0.221 0.057 0.063 Bio-ML NCIT↔DOID Jev 0.811 0.981 0.943 0.026 0.021 Bio-ML NCIT↔DOID Claude Haiku 0.440 0.976 / 0.9976† 0.940 0.039 0.024 Bio-ML NCIT↔DOID Claude Sonnet 0.853 0.990 0.955 0.036 0.016 Bio-ML NCIT↔DOID Strands Decider 0.658 0.919 0.407 0.145 0.112 Bio-ML NCIT↔DOID Baseline (no LLM) 0.615 0.878 0.395 0.078 0.082 Bold marks the best unambiguous value in each column for each dataset (lowest for ECE and Brier). Bio-ML AUPRC has no highlighted winner because the two supplied Haiku values imply different rankings. 02 / Compare the judges The winner depends on what you measure. Explore merge decisions, relation typing, and calibration across both domains. Merge F1 · Higher is better. The decision at the frozen merge cutoff. ESCO ↔ O*NET2,913 pairs JevDecision model 0.808 Claude HaikuReasoning model 0.797 Claude SonnetReasoning model 0.811 Strands DeciderDecision model · local 0.333 BaselineNo language model 0.499 NCIT ↔ DOID5,611 pairs JevDecision model 0.811 Claude HaikuReasoning model 0.440 Claude SonnetReasoning model 0.853 Strands DeciderDecision model · local 0.658 BaselineNo language model 0.615 View all numeric data Dataset / judge Merge F1 Relation macro-F1 Calibration · ECE Brier score ESCO ↔ O*NET / Jev 0.808 0.572 0.079 0.068 ESCO ↔ O*NET / Claude Haiku 0.797 0.585 0.047 0.048 ESCO ↔ O*NET / Claude Sonnet 0.811 0.693 0.046 0.037 ESCO ↔ O*NET / Strands Decider 0.333 0.204 0.096 0.093 ESCO ↔ O*NET / Baseline 0.499 0.221 0.057 0.063 NCIT ↔ DOID / Jev 0.811 0.943 0.026 0.021 NCIT ↔ DOID / Claude Haiku 0.440 0.940 0.039 0.024 NCIT ↔ DOID / Claude Sonnet 0.853 0.955 0.036 0.016 NCIT ↔ DOID / Strands Decider 0.658 0.407 0.145 0.112 NCIT ↔ DOID / Baseline 0.615 0.395 0.078 0.082 Values from the supplied draft’s results table. Bars use a fixed 0–1 scale for every metric. AUPRC and cost are omitted here because the draft contains conflicting values. No confidence intervals or repeated runs were supplied. Reporting note: conflicting figures in the supplied draft † Haiku’s Bio-ML AUPRC is 0.9976 in the results table and 0.976 in the narrative. Neither is treated as confirmed here. The judge table reports about $1.70 per 1,000 Haiku pairs, while the closing paragraph reports $1.50 for all 8,524 pairs. The claimed 5× cost ratio therefore cannot be reconciled with the per-1,000 table. Reported itemized totals ($0.30 Jev + $1.50 Haiku + $35.50 Sonnet) sum to $37.30, versus the stated $46 total. No raw benchmark results were supplied to resolve these differences. The new figures use only values that agree across the draft’s text and tables. ‡ Zero API fees excludes hardware and electricity. The original embedded charts also conflict with the text and table; they are preserved with the source draft in the repository, rather than reproduced as authoritative results. Ranking quality and decision quality are different things Look at Claude Haiku on Bio-ML. Its F1 is 0.440, by far the lowest score either reasoning model produced, on a dataset where Sonnet and Jev both score above 0.81. One might incorrectly assume it’s a capability issue. However, both reported values for Haiku’s AUPRC on the same dataset are high (see the reporting note). If you sort the pairs by Haiku’s score, the true matches sit almost entirely at the top. The ranking works, but the final selection failed. The cause is how Haiku reports probabilities. A reasoning model writes its confidence as a number in its answer, and Haiku sticks to a limited set of round values. On the development split, its most common score for true matches was 0.93 (18 of the 50), but one non-match also scored 0.93. That puts precision at 0.93 at 96.9%, short of the 99% target, so the rule moved up to the next score Haiku gave: 0.95. Only 13 dev pairs scored that high. All 13 were correct, which satisfied the rule, but the cutoff now sat above most of Haiku’s true matches. The test set repeated the pattern. 552 of the 1,402 true matches scored exactly 0.93, and, therefore, the 0.95 cutoff excluded them. Haiku auto-merged only 396 pairs. Every one of them was correct, but recall fell to 28% and F1 to 0.440. With the cutoff at 0.90, the same judgments would have scored an F1 of 0.859. The true matches it didn’t merge weren’t thrown away: below the merge cutoff, a pair goes to human review unless it scores under the lower unlink cutoff. 990 of Haiku’s missed matches landed in the review queue and only 16 were rejected. The cost of the bad cutoff was work for people: Haiku sent 1,880 pairs to review, against 604 for Jev. The failure came from how the threshold was chosen, not from the model, and the lesson applies to any judge, decision model or reasoning model. When a judge’s scores cluster on a few values, a strict precision target on a small development set can land on a cutoff that sends most of the correct answers to human review instead of merging them. Looking only at F1, you’d conclude that Haiku can’t handle biomedical text. AUPRC, which ignores the cutoff, tells a different story: both supplied values indicate strong ranking quality, although their disagreement prevents a precise comparison with Jev and Sonnet. What failed was the one cutoff the rule picked from its clustered scores; with a cutoff of 0.90, the same answers score an F1 of 0.859. It’s probably possible to get finer-grained probabilities out of Haiku, for example by changing the prompt or averaging several sampled answers, and the threshold rule itself could be tuned too. But the same kind of per-model tuning could be applied to every judge, Jev included, and once you start, the comparison stops being like for like. We ran every judge with the same setup and the same threshold rule, and left per-model optimization out of scope. 03 / The threshold trap A good ranking can still create a review queue. Claude Haiku on Bio-ML · what happened to the 1,402 true matches. Frozen cutoff0.95 Only 13 development pairs cleared it. All 13 were correct. True matches scored 0.93552 These test pairs sat just below the auto-merge boundary. F1 at that cutoff0.440 Perfect merge precision, but only 28% recall on test data. 396 Auto-merged 990 Sent to review 16 Rejected Total review queue · all candidate pairs 1,880 Haiku vs. 604 Jev 3.1×as many reviews What if the cutoff were 0.90? The draft reports F1 of 0.859 for the same Haiku judgments at a cutoff of 0.90. This is a post-hoc comparison, not the frozen evaluation result. It illustrates sensitivity to the cutoff; it does not establish that 0.90 would satisfy the 99% development-precision target. The stacked bar contains only gold exact matches. The total review queues include non-matches too. Counts and the counterfactual F1 come from the draft’s threshold discussion; the 3.1× ratio is calculated as 1,880 ÷ 604. The rest of the picture Claude Sonnet has the lowest Brier score on both datasets. On ECE, the picture depends on the dataset. On the occupation data, Jev is clearly worse calibrated than both reasoning models (ECE 0.079, against 0.046 for Sonnet and 0.047 for Haiku). On the biomedical data, Jev is the best calibrated of the three (0.026, against 0.036 for Sonnet and 0.039 for Haiku). That matters if your pipeline needs probabilities it can trust on top of correct final labels. Strands Decider is the only language-model judge in this comparison that runs locally without an API key, but zero API fees do not guarantee strong judgments. It has the weakest relation typing of all five on ESCO (macro-F1 0.204), and when it’s unsure it tends to fall back on “related” instead of committing to a specific relationship. The baseline is a floor. With no LLM at all you get roughly 0.50 to 0.62 F1, which shows how much of the lift comes from language understanding on top of similarity scoring. All of these numbers come from a single test-split run in October 2026, with no repeats or cross-validation. When a decision model is enough Our results make a practical case for decision models. Jev’s merge F1 was close to Claude Sonnet’s on the occupation data and came within a few points on the disease data (F1 0.811 against 0.853), at more than 100 times lower cost and about 7 times lower latency. For a pipeline that has to judge hundreds of thousands of candidate pairs, a gap that size decides whether you can afford to judge every pair with the strongest model or only a sample. The cheapest reasoning model also deserves consideration. Claude Haiku’s merge F1 was close to Jev’s on the occupation data, and it ran about 5 times slower. The conflicting cost figures prevent a precise cost comparison: a decision model is still cheaper and faster, but the case for it rests as much on fixed-label output, with nothing to parse, and on scores you can threshold reliably. Reasoning models still earn their cost in some places. Sonnet made better merge decisions on the disease data, typed relationships better on the occupation data, and gave better-calibrated probabilities there. A pipeline that depends on the exact relationship (broader vs. narrower), or on probabilities it can read literally, may want Sonnet, at least for the pairs a decision model is unsure about. Of the judges tested here, the reasoning models can also generate explanations when a pipeline needs them. Not every decision model is a drop-in replacement yet. Strands Decider was free to run, but on this task it scored about the same as a simple baseline with no language model, and worse on one dataset. Test a candidate model on your own data before you switch. Whichever judge you use, measure ranking quality (AUPRC) separately from the F1 at your chosen threshold, and look at how the scores are spread. A judge whose scores cluster on a few round values can land on a cutoff that fails badly at production volume, as Haiku’s did here. What’s next We’re open-sourcing the kgalign pipeline that produced these numbers. The results use only the two public datasets (ESCO/O*NET occupation data and Bio-ML’s OAEI 2024 NCIT↔DOID biomedical ontologies). No private or client data went into this benchmark. Since we ran this benchmark, Jev has gone from a single product to the first of a new category, usually called decision models (TypeSafe’s own name is “System One” models). In the weeks after Jev’s launch, AWS released Strands Decider with open weights, Cloudflare launched its open-source Clef and Clef-flash models on Workers AI, and Ollama added a decision-model API so models like Nimble, Tev1 and Clef can run locally. Several of them deliberately copy Jev’s interface, so switching between them is mostly a matter of changing the endpoint. They share one idea. Keep what large language models learned about language and the world, and drop the expensive part, which is generating text. A decision model reads the input once and returns probabilities over a fixed set of answers, so classification gets most of an LLM’s understanding at a small fraction of the cost and latency. Our own numbers show how large that gap is. Jev answered in about a quarter of a second, against roughly 1.3 seconds for Haiku and 1.8 seconds for Sonnet. Across all 8,524 pairs, the draft reports $0.30 for Jev and $35.50 for Sonnet. The Haiku totals remain unresolved. Against the strongest model in this lineup, a decision model can judge every candidate pair in a large alignment job for what a small sample would cost. Our results suggest the idea holds for entity alignment, with a caveat that applies to every model in the category: as the Haiku result shows, a probability is only as useful as the threshold you apply to it. The open-weight models add one more advantage: weak spots like Decider’s relation typing can be fixed with a fine-tune, without per-call costs."},{"href":"/stop-writing-tools/","title":"Stop Writing Tools","description":"In August 2025 I built a personal assistant out of nine agents and around 40 tools. A year later I rebuilt it as a folder of instructions, a shell and a few CLIs, and ran both on the same requests.","abstract":"In August 2025 I built a personal assistant out of nine agents and around 40 tools. A year later I rebuilt it as a folder of instructions, a shell and a few CLIs, and ran both on the same requests.","tags":["AI Agents","Claude Code","Strands Agents","Agent Architecture"],"topics":[],"authors":["Petar Kalinovski"],"text":"Tools are functions that let an LLM act as an agent. Calculating a sum or getting today’s date are the classic examples. They have been useful for a long time, and they’re still the most common way to build an agent. At Loka, most agentic projects use them. Say you’re building a personal assistant. You’d use an agent framework and build tools for it to use. To check your calendar. To add items to it. If there are too many tools, you might define “agents as tools” that work as subagents under an orchestrator. And this would work. I remember the first time I did it. It felt great. Giving your chatbot agency, so it can do more than just write text. Old Charon In August 2025, I built a personal assistant called Charon as my internship capstone project. It was a three-layer agent architecture: an orchestrator with two subagents, each with three subagents of its own. Nine agents and around 40 tools all in all (including the GitHub MCP). It managed my calendar, kept a journal, recommended newsfeeds, movies and books, and read me code (local and on GitHub). The reason for this many agents was that back then, models were far more likely to pick the wrong tool or mangle the input, especially the more tools you added. Old Charon’s welcome screen, rendered from the capstone’s own banner code. Click for full size. This behemoth genuinely worked. I used Sonnet 4, but because it was too expensive, sometimes I also used Devstral Medium (talk about a trip down memory lane), and when I tested it, it generally worked. And yet if you made this today and showed it to a serious person, you’d get laughed out of the room. project-charon/src/agents big_boss_orchestrator ··········· journal · sleep tracking (4) ├── task_agent │ ├── file_search_agent ······· file_read · find_folder_from_name │ ├── google_calendar_agent ··· create_event · get_events │ └── github_agent ············ the GitHub MCP server └── home_agent ·················· create_event · get_events ├── books_agent ············· search · add · mark read · list (4) ├── movies_agent ············ OMDb · add · mark watched · list (4) └── recommender_agent ······· Substack + YouTube feeds (6) # every edge in this tree is a tool as well: eight *_agent_query tools # that pass a request down and a summary back up Old Charon's nine agents, read from the capstone code. Tools are listed next to the agent that owns them. Every tool was a predetermined action. The model never had to do anything other than know which button to press (with the correct parameters, of course). That is what tools are for. They let a weak model look competent by having predetermined actions. They also make the model unable to do anything I hadn’t written a tool for. What changed The issue here is that recent models have been far from weak, starting almost an entire year ago. With the jump in capability that came with models like Opus 4.5, Claude Code and Codex finish hour-long tasks on their own. The idea that you need a hand-built tool that specifically does one job is wasteful at best and a limitation to the model at worst. So, how did we get here? Anthropic hasn’t published it, so this is my guess, but I think it’s a credible one. Think about your past experiences with Claude Code. Up until mid-2025, you would ask for a feature, and the model would begin building it. But the experience was a bit different than it is now. The user would intervene constantly. Either to suggest other improvements. Or to point out issues and problems. Now imagine you removed the human turns from this transcript and used it as training data. So, train the model to reach the end state by the path it took with the user. Just fully autonomously. Give negative rewards if it doesn’t reach the end state, or if it treats some of the intermediate steps as end goals, and that way you end up with a model with far better scores on long-horizon tasks. a session in mid-2025 > add a session switcher to the CLI ⏺ Added a sessions command and a table > it crashes when there are no sessions ⏺ Handled the empty case, added a test > show the description next to each id ⏺ Added a description column. Done. as training data? task: add a session switcher to the CLI ⏺ Added a sessions command and a table ✗ stopping here is penalised > it crashes when there are no sessions ⏺ Handled the empty case, added a test > show the description next to each id ⏺ Added a description column. Done. ✓ end state reached: reward My guess, not a published method: take a session where a person kept steering, strike out the person's turns, and reward only reaching the end state. What does “better” mean? I want to quantify this “the models got better” claim. More so than pointing out how today’s models can break out of their eval environments and take over parts of Hugging Face and OpenAI. Or how they can now solve Millennium Prize problems. I think the following two benchmarks matter most for our use case. ARC-AGI ARC-AGI is a benchmark that tests the model’s ability to generalize by giving it novel puzzles. The idea is to see if the model can acquire a skill it hasn’t been trained on. When OpenAI o3 scored 75.7% on ARC-AGI-1 in December 2024 (87.5% with 172 times the compute), vs GPT-4o’s single digits, it was read across the field as a sign that scaling reasoning hadn’t hit a wall. Since then we have moved on to a harder successor, ARC-AGI-2. ARC-AGI-2 (%) Opus 4 (May '25) 8.6 Sonnet 4.5 (Sep '25) 13.6 Opus 4.5 (Nov '25) 37.6 Sonnet 4.6 (Feb '26) 60.4 Opus 4.6 (Feb '26) 69.2 Opus 4.7 (Apr '26) 75.8 Opus 4.8 (May '26) 72.1 Fable 5 (Jun '26) 89.2 Opus 5 (Jul '26) 90.4 View numeric chart data Series Category ARC-AGI-2 score (%) ARC-AGI-2 Opus 4 (May '25) 8.6% ARC-AGI-2 Sonnet 4.5 (Sep '25) 13.6% ARC-AGI-2 Opus 4.5 (Nov '25) 37.6% ARC-AGI-2 Sonnet 4.6 (Feb '26) 60.4% ARC-AGI-2 Opus 4.6 (Feb '26) 69.2% ARC-AGI-2 Opus 4.7 (Apr '26) 75.8% ARC-AGI-2 Opus 4.8 (May '26) 72.1% ARC-AGI-2 Fable 5 (Jun '26) 89.2% ARC-AGI-2 Opus 5 (Jul '26) 90.4% ARC-AGI-2 scores for Claude models. The two jumps are highlighted: Opus 4.5 in November 2025, and Fable 5 in June 2026, the first Mythos-class model Anthropic released for general use. The dashed line marks the Mythos Preview announcement on April 7, 2026. Each score is the model's best setting on the ARC Prize leaderboard (Semi-Private set): Opus 4.7, Fable 5 and Opus 5 at Max effort; Sonnet 4.6, Opus 4.6 and Opus 4.8 at High. You can see the November jump, from 13.6% to 37.6%. (You can probably see this new post-Mythos jump too.) So this benchmark tells us that the models have become much better at generalizing. Much better at understanding structures they have never seen (I am not even mentioning GPT-6 Astra and how it has saturated ARC-AGI-3). So models have become much better at solving things not in the training data. Like being able to navigate your previously unseen CLI without needing tools for it. METR Long Horizon The METR Long Horizon benchmark measures how long a task, in human expert hours, the model can finish. At the 50% horizon, Opus 4 (May 2025) is at 1.7 hours, Opus 4.5 (November) is at about 4.9 hours and Opus 4.6 (February 2026) at about 12 hours. Claude Mythos Preview (April 2026) came in at “at least 16 hours”, beyond what METR’s task suite can reliably measure (it saturated the benchmark). Since then, models like Mythos 5.1 and especially GPT-6 Astra (which has saturated a bunch of benchmarks) have become even more powerful. This is what I mean when I say models have become much more powerful since the summer of 2025. 50% time horizon ( h) Opus 4 (May '25) 1.7 Opus 4.5 (Nov '25) 4.9 Opus 4.6 (Feb '26) 12 Mythos Preview (Apr '26) 16 View numeric chart data Series Category Hours 50% time horizon Opus 4 (May '25) 1.7 h 50% time horizon Opus 4.5 (Nov '25) 4.9 h 50% time horizon Opus 4.6 (Feb '26) 12 h 50% time horizon Mythos Preview (Apr '26) 16 h METR 50% time horizon, in human expert hours. Mythos Preview's 16 hours is a lower bound: it went past what METR's task suite can reliably measure. Anthropic’s own usage data shows that Claude Code’s longest turns (the 99.9th percentile) nearly doubled between October 2025 and January 2026, from under 25 minutes to over 45. Also, internally at Anthropic from August to December, Claude Code’s success rate on the hardest tasks doubled while human interventions per session fell from 5.4 to 3.3. BeforeAfter Longest Claude Code turns99.9th percentile, Oct 2025 → Jan 2026 <25 min → >45 min Success rate on the hardest tasksinternal, Aug → Dec 2025 1× → 2× Human interventions per sessioninternal, Aug → Dec 2025 5.4 → 3.3 From Anthropic's Measuring agent autonomy. The success rate is only reported as a ratio, so its row shows it doubling. We don’t need that anymore The issues with forcing a competent model to follow a tool structure are plentiful. It can’t chain two tools without a round trip through its context. It can’t save an intermediate result to disk and come back to it. It can’t do anything other than what I anticipated. Everything it can do is predetermined by the person who wrote the tools. And everything has to be explained. And coded. old Charon, request 1 > What's new from my Substacks and YouTube channels? Pick two. big_boss_orchestrator journal ×3└── home_agent get_events asked once └── recommender_agent asked 6 timesget_all_newsletters ×5get_all_monitored_youtube_channelsget_recent_posts_from_newsletter ×9get_recent_youtube_videos ×5 31 tool calls · 24 model calls · 99 s ⏺ My two picks from this week are both YouTube interviews: 1. Ezra Klein Show: \"Jensen Huang Thinks A.I. Alarmism Has Gone Too Far\" (1h47m, Sep 23). […] 2. The Rest Is Politics: Leading, \"Can AI Stay Under Human Control?\" with Mustafa Suleyman (1h04m, Sep 28). […] new Charon, request 1 > What's new from my Substacks and YouTube channels? Pick two. ⏺ Bash cat ~/Documents/Vault/Charon/follows.md; ls …/journal | tail -5 → the 5 newsletters and 5 channels I follow⏺ Bash for u in <5 feeds>; do curl -sL \"$u/feed\" -o …xml & done; for c in <5 channels>; do yt-dlp … & done; wait → blocked: inline loops need my approval⏺ Write /tmp/charon/fetch_follows.sh → the same loop, as a script⏺ Bash bash /tmp/charon/fetch_follows.sh → all 10 saved to /tmp/charon/feeds⏺ Write /tmp/charon/summarize_feeds.py⏺ Bash python3 /tmp/charon/summarize_feeds.py → this week's posts from every feed⏺ Write /tmp/charon/yt_dates.sh⏺ Bash bash /tmp/charon/yt_dates.sh → upload dates and lengths 8 tool calls · 9 model calls · 85 s ⏺ My two picks: First, Ezra Klein with Jensen Huang, \"Jensen Huang Thinks A.I. Alarmism Has Gone Too Far\", an hour and 47 minutes. […] Second, Dwarkesh with Sarah Paine, \"Why wars are so difficult to end\", 52 minutes. […] Request 1 from the comparison below, on Opus 5.5. Old Charon's logs record tool names without arguments, so its calls are grouped by the agent that owns them. Both versions picked the same first episode. What the assistant would look like today I remade Charon the way I would make it today, to compare a year-old app with a brand-new one. The idea here is to replace every tool with a CLI, a curl from a public endpoint, or lastly just bash for reading and writing local files. The new Charon is a folder: charon petar@loka:~/Documents/charon$ tree charon/ ├── AGENTS.md 44 # who Charon is, where my data lives, which CLIs to use ├── CLAUDE.md 2 # two lines: @AGENTS.md and my preferences file ├── .agent/skills/planning/ │ └── SKILL.md 45 # the scheduling and estimation playbook └── .claude/ └── settings.json 51 # the boundary New Charon. The yellow numbers are line counts. AGENTS.md holds short instructions for what it can use: - Calendar: `gcalcli` (timezone Europe/Skopje). `gcalcli agenda \"today\" \"7 days from now\" --tsv` for reading. `gcalcli add` to create events. Always confirm before creating, moving or deleting an event. - GitHub: `gh` (logged in as PetarKalinovski). - Books: Open Library, e.g. `curl -s 'https://openlibrary.org/search.json?title=piranesi&limit=3&fields=title,author_name,first_publish_year,number_of_pages_median,subject'` - Movies and shows: OMDb, `curl -s \"https://www.omdbapi.com/?apikey=$OMDB_API_KEY&t=severance\"` - Substack: every newsletter has an RSS feed at `<newsletter url>/feed`. - YouTube: `yt-dlp --flat-playlist -I 1:5 --print '%(title)s | %(url)s' <channel url>/videos` That’s roughly 3,080 lines of agents, tools, prompts and schemas, replaced by 89 lines of instructions and a 51-line settings file, mostly permission rules. Old Charon3,080 lines New Charon140 lines Old Charon: tools 1,211 · prompts 898 · agents 706 · schemas 265New Charon: instructions (AGENTS.md + skill) 89 · settings.json 51 One square is ten lines. Comparing the two versions I ran both versions on the same four requests. First on Opus 5.5, then on Sonnet 5.5 (closer to what Charon was originally built for). The old one ran on Strands through OpenRouter, while the new one ran in Claude Code headless mode (claude -p). Old CharonNew Charon Model calls Opus 5.5 72 → 31 Sonnet 5.5 53 → 29 Tool calls Opus 5.5 116 → 25 Sonnet 5.5 82 → 23 Time Opus 5.5 7.8 min → 3.1 min Sonnet 5.5 4.4 min → 1.2 min Cost Opus 5.5 ≈$7.35 → $0.88 Sonnet 5.5 $0.45 → $0.31 All four requests together. Each row is scaled to old Charon's total, so the solid dot shows how much of it new Charon needed. Sonnet 5.5 totals add up the mean of three runs per request. Old Charon · Opus 5.5 New Charon · Opus 5.5 Old Charon · Sonnet 5.5 New Charon · Sonnet 5.5 Feeds: pick two 31 8 23 5 Book + sleep 8 3 9 3 Two free hours 11 5 19 8 Estimate + schedule 66 9 31 7 View numeric chart data Series Category Tool calls Old Charon · Opus 5.5 Feeds: pick two 31 Old Charon · Opus 5.5 Book + sleep 8 Old Charon · Opus 5.5 Two free hours 11 Old Charon · Opus 5.5 Estimate + schedule 66 New Charon · Opus 5.5 Feeds: pick two 8 New Charon · Opus 5.5 Book + sleep 3 New Charon · Opus 5.5 Two free hours 5 New Charon · Opus 5.5 Estimate + schedule 9 Old Charon · Sonnet 5.5 Feeds: pick two 23 Old Charon · Sonnet 5.5 Book + sleep 9 Old Charon · Sonnet 5.5 Two free hours 19 Old Charon · Sonnet 5.5 Estimate + schedule 31 New Charon · Sonnet 5.5 Feeds: pick two 5 New Charon · Sonnet 5.5 Book + sleep 3 New Charon · Sonnet 5.5 Two free hours 8 New Charon · Sonnet 5.5 Estimate + schedule 7 Tool calls per request. Opus 5.5 is one run per request; Sonnet 5.5 is the mean of three. Old Charon · Opus 5.5 (s) New Charon · Opus 5.5 (s) Old Charon · Sonnet 5.5 (s) New Charon · Sonnet 5.5 (s) Feeds: pick two 99 85 53 19 Book + sleep 60 23 39 11 Two free hours 75 31 51 17 Estimate + schedule 236 45 118 26 View numeric chart data Series Category Seconds Old Charon · Opus 5.5 Feeds: pick two 99s Old Charon · Opus 5.5 Book + sleep 60s Old Charon · Opus 5.5 Two free hours 75s Old Charon · Opus 5.5 Estimate + schedule 236s New Charon · Opus 5.5 Feeds: pick two 85s New Charon · Opus 5.5 Book + sleep 23s New Charon · Opus 5.5 Two free hours 31s New Charon · Opus 5.5 Estimate + schedule 45s Old Charon · Sonnet 5.5 Feeds: pick two 53s Old Charon · Sonnet 5.5 Book + sleep 39s Old Charon · Sonnet 5.5 Two free hours 51s Old Charon · Sonnet 5.5 Estimate + schedule 118s New Charon · Sonnet 5.5 Feeds: pick two 19s New Charon · Sonnet 5.5 Book + sleep 11s New Charon · Sonnet 5.5 Two free hours 17s New Charon · Sonnet 5.5 Estimate + schedule 26s Wall-clock time per request, in seconds. Old Charon · Opus 5.5 New Charon · Opus 5.5 Feeds: pick two 1.89 0.23 Book + sleep 0.24 0.14 Two free hours 0.38 0.19 Estimate + schedule 4.84 0.32 View numeric chart data Series Category USD Old Charon · Opus 5.5 Feeds: pick two 1.89 Old Charon · Opus 5.5 Book + sleep 0.24 Old Charon · Opus 5.5 Two free hours 0.38 Old Charon · Opus 5.5 Estimate + schedule 4.84 New Charon · Opus 5.5 Feeds: pick two 0.23 New Charon · Opus 5.5 Book + sleep 0.14 New Charon · Opus 5.5 Two free hours 0.19 New Charon · Opus 5.5 Estimate + schedule 0.32 Cost per request on Opus 5.5, in US dollars. Old Charon's costs are approximate. The full table below has the Sonnet 5.5 costs. Full results, old → new Request Model Model calls Tool calls Time Cost What’s new from my Substacks and YouTube channels? Pick two. Opus 5.5 24 → 9 31 → 8 99s → 85s ≈$1.89 → $0.23 Sonnet 5.5 13 → 6 23 → 5 53s → 19s $0.145 → $0.062 Add Piranesi to my reading list. How did I sleep last week? Opus 5.5 9 → 4 8 → 3 60s → 23s ≈$0.24 → $0.14 Sonnet 5.5 9 → 4 9 → 3 39s → 11s $0.035 → $0.053 I have 2 hours free tonight. What should I do? Opus 5.5 9 → 7 11 → 5 75s → 31s ≈$0.38 → $0.19 Sonnet 5.5 13 → 10 19 → 8 51s → 17s $0.104 → $0.098 How long will a session viewer for project-charon take, and when can I fit it in? Opus 5.5 30 → 11 66 → 9 236s → 45s ≈$4.84 → $0.32 Sonnet 5.5 18 → 9 31 → 7 118s → 26s $0.163 → $0.101 Total Opus 5.5 72 → 31 116 → 25 7.8 min → 3.1 min ≈$7.35 → $0.88 Sonnet 5.5 53 → 29 82 → 23 4.4 min → 1.2 min $0.45 → $0.31 How the comparison was run Old Charon is the August 2025 capstone code on Strands Agents, with all nine agents pointed at the same model through OpenRouter. New Charon runs in Claude Code’s headless mode (claude -p --output-format stream-json). Opus 5.5 is one run per request. Sonnet 5.5 is three runs per request, and the table shows the mean. Nobody approves anything in a headless run, so writes were refused on both sides: old Charon’s calendar inserts and GitHub write tools, and new Charon’s ask rules. Model calls count every call across old Charon’s nine agents, and Claude Code’s turns for new Charon. Tool calls count every tool use, blocked ones included. Old Charon’s Opus costs are approximate: the $8.60 OpenRouter bill for five runs (the four requests plus one rerun of the first) split by each run’s token-priced cost at $4 and $20 per million input and output tokens. Its Sonnet costs are token-priced at $2 and $10. Claude Code’s first call in every run already carried about 20,000 input tokens (19.9k on Opus, 21.9k on Sonnet): its system prompt, tool definitions and Charon’s own instructions. New Charon’s costs are what Claude Code reports, and they include prompt caching. Priced at the full input rate instead, new Charon would have cost about $2.42 on Opus (against $7.35) and $1.14 on Sonnet (against $0.45). Answer quality was comparable on both new and old Charon. But you can see old Charon had different issues. Issues with old Charon You can see the huge cost and latency margins here. But more than that, the issue is structural. In the fourth task, old Charon made 66 tool calls: 35 GitHub MCP calls (29 of them reading files) and 22 local read calls of the same repo, because the local agent and the GitHub agent read it separately. Old Charon66 tool calls New Charon9 tool calls GitHub MCP: read a file · 29 → 0GitHub MCP: other · 6 → 0Reading the repo locally · 22 → 2Routing to another agent · 4 → 0Calendar, journal and other · 5 → 4Blocked by a permission check · 0 → 3 Every tool call in the fourth request on Opus 5.5, in the order they ran. Hover a square for the tool name. New Charon read the repo with two shell commands. The whole task was 9 tool calls instead of 66 (3 of them blocked by Claude Code’s permission checks), and it took a fifth of the time it took old Charon. This is one of the big recurring issues with structuring subagents as tools. Stuff gets constantly re-read. It is a fundamental problem in agents as tools. Subagents get sent what the orchestrator decides. A summary, or a description of the task. It almost invites this token waste because the system is set up to lose context. request 4, old Charon you │ the whole conversation ▼ big_boss_orchestrator │ a task description ▼ task_agent ├──────────────────────────┐ │ a task description │ a task description ▼ ▼ file_search_agent github_agent 22 × file_read 29 × get_file_contents │ │ ▼ ▼ project-charon (local) project-charon (GitHub) └────── the same repo ─────┘ # neither agent knows what the other read, and the orchestrator # can't tell the GitHub agent to skip the repo Each layer only gets what the layer above decided to send. The orchestrator has the conversation with the user, so it has full context on what the user asks. The subagent has the specialized tool results. But the orchestrator doesn’t know what the local files agent read, so it can’t tell the GitHub agent to skip the repo. There can also be a case where the subagent misinterprets instructions from the orchestrator. In any case, when an instruction from the orchestrator is unclear to the specialist, it can ask a clarifying question, or it can try to gain as much context as possible itself. And given the way models are post-trained, gathering as much information as possible is practically demanded of them. And it’s something we as users like. Maybe I can fix this one case by grouping the subagents differently. So instead of a GitHub and a local files agent, I make one repo-reader agent. But that only works because I have seen the overlap. Grouping them this way will most likely create the same problem in a different place. It will be a constant battle to make this way of scaffolding work, when in truth you probably don’t have to. It is the same problem as with the tools. It can’t do stuff you didn’t plan for. Better on old Charon The small requests were genuinely good on the old version too. And it was only slightly worse on the bigger requests. Also, because Claude Code starts every run with 20k tokens of system prompt, one request was actually cheaper on old Charon. The tasks on a personal assistant like this are easy for most models. I never expected there to be any big difference in the quality of the answers. Just like I said above, this has worked since I first made it. It’s all of the other things, excluding the quality of the answer, that can be worse. The main problem with this new design The upside, as I have stated, to removing rails is that the agent has more freedom in solving the task, which tends to lead to better results (on non-trivial tasks), latency and cost. But there is also a downside. I removed rails. The old agent had a create_event tool. It was the only way to write to my calendar. In new Charon, Claude has to ask me before it runs a gcalcli command that adds, changes or deletes an event. The issue here is that the new agent can, in theory, write a Python script to a scratch folder and run it without asking, and that script could call the Calendar API directly. It can do far more than that. Once you give the agent the ability to run scripts it wrote, it can bypass a lot of safeguards you might have implemented. I honestly don’t really care about this for a personal assistant. But not all projects are personal assistants. calendar writes # old Charon ⏺ create_event(title, start, end) the only code that writes to the calendar # new Charon, .claude/settings.json \"ask\": [\"Bash(gcalcli add *)\", \"Bash(gcalcli edit *)\", \"Bash(gcalcli delete *)\", …] \"allow\": [ …, \"Edit(//tmp/charon/**)\", \"Bash(python3 /tmp/charon/*)\" ] # new Charon, what those settings let through ⏺ Bash(gcalcli add …) asks me first ⏺ Write(/tmp/charon/add_event.py) allowed ⏺ Bash(python3 /tmp/charon/add_event.py) allowed: Calendar API, no question asked The settings lines are copied from new Charon. The last two steps never happened in a run, but nothing in the settings stops them. A client project Let’s think of a typical client project where the issue I just described matters much more than it does for my personal assistant. Let’s say a company wants users to be able to query multiple databases in different systems, all in plain English. There needs to be a chat front end, and different users need to see different types of data. The most common way to design this is to make an orchestrator agent that picks the domain and routes to specialist agents, one per data source, each with their own tools for each of the tasks. And perhaps, before a query gets routed to the orchestrator, an authentication layer that decides what subagents the user might have access to. This is the old Charon of B2B. This is also writing scaffolding where the model’s thinking is done for it. The existence of a tool for each task is us making the steps in advance, and the existence of every specialist (as an agent as tool) creates a bottleneck where information gets passed along. How good a job the specialist does depends on the words the orchestrator sends. Let’s remove the orchestrator. Each specialist becomes a skill. A skill that will be read when a question needs that information. The tool per task becomes a CLI with good --help instructions. And let’s keep a workspace per user, so the files the agent created are always there. The agent should also have access to bash, so it can read the skills and write any logs or documentation. The usual design Chat front end Authentication layerdecides which specialists you get Orchestrator agentpicks the domain a task description Sales DBagent, a tool per task CRMagent, a tool per task Warehouseagent, a tool per task Sales DB CRM Warehouse Without the orchestrator Chat front end login Identity provideryour login maps to a database role Sandbox, one workspace per user One agent with bash Skillsone per data source, read when needed CLIswith good --help Fileslogs, notes and results that stay SQL through a CLI, the only way out Data proxyholds the real credentialsread-only rolelogin → DB rolelogs every query Sales DB CRM Warehouse The same product, two ways. On the right, the agent can't reach anything except the proxy, and the proxy can't write. And because changing your entire architecture can be a bit challenging, at least for starting out, I recommend using the Strands harness. How do you safeguard something that has this level of agency? So how do we stop the agent from editing or deleting parts of the database? You cannot give it access to the database itself. Ever. The main idea here is to make a data proxy (a small web service outside of the sandbox). So the agent can’t connect to the database. It can only send queries to a middleman. It writes SQL and sends it through a CLI. Then the proxy, which has the real credentials, forwards that to the DB. And the proxy connects with a read-only role, so an update or delete fails automatically. If the credentials were kept in the sandbox, the agent could connect directly and bypass the proxy’s identity checks and audit logs. Database-enforced read-only permissions would still apply. The sandbox can also reach the proxy and nothing else. That keeps the proxy the only way to the database, and it stops the agent from sending data anywhere else, by mistake or because something it read told it to. Even Strands, the framework old Charon is built on, now says this in the docs for its new harness: “To isolate what the agent can touch, run it under a sandbox rather than trying to restrict the tools themselves.” Besides making sure the agent can’t change the DB, we need to make sure that we know who is querying the DB, and we need to know what the agent did. We do the first thing by checking the login from the identity provider and mapping it to a database role, which decides which tables and rows that user can see. That replaces the authentication layer that picked subagents. We do the second thing by just logging the queries themselves when they reach the proxy. Give it a year At the start I said you’d get laughed out of the room for building old Charon today. I wonder what this folder will look like in a year. As I write this, skills are one year and four days old. A year ago they didn’t exist, and now half of new Charon’s instructions are one. AGENTS.md, skills, permission files. I wonder how much will change in a year. I wonder what models will outgrow. Will it be most of what we do today? Or almost nothing? Will we have specialized swarms? Will specialized subagents be viable again? I don’t know what changes next. I think the guardrails give out last. The proxy. The sandbox. But a year ago I wouldn’t have guessed correctly either. I’ll let new Charon have the last word. One of the four requests asked how I slept last week. This is what it said: charon > Add Piranesi to my reading list. How did I sleep last week? ⏺ I added Piranesi to your reading list. […] Your sleep data stops on 7 August 2025, more than a year ago. The last week on record runs from 1 to 7 August. […] Nothing has been logged since, so I can't tell you how you sleep now. If you want trends that mean something, start logging again. That was the last week of my internship. References GitHub. GitHub MCP Server. github.com/github/github-mcp-server OpenAI (2026). OpenAI – Hugging Face Incident Technical Report. On agents in a cyber evaluation escaping their sandbox and compromising parts of Hugging Face’s production infrastructure in July 2026. cdn.openai.com Hugging Face (2026). Security incident disclosure, July 2026. 16 July 2026. huggingface.co/blog OpenAI (2026). Navier–Stokes announcement. 8 September 2026. A Lean-checked proof that the 3D Navier–Stokes equations can blow up in finite time under a smooth external force. openai.com Scientific American (2026). Did OpenAI Solve the Wrong Navier-Stokes Problem? 21 September 2026. scientificamerican.com ARC Prize (2024). OpenAI o3 Breakthrough High Score on ARC-AGI-Pub. 20 December 2024. arcprize.org ARC Prize Foundation (2025). ARC-AGI-2. Benchmark description and paper (arXiv:2505.11831). arcprize.org/arc-agi/2 Anthropic (2026). Claude Fable 5 and Claude Mythos 5. 9 June 2026. Describes Fable 5 as a Mythos-class model made safe for general use. anthropic.com/news Anthropic (2026). Project Glasswing. 7 April 2026. Announces Claude Mythos Preview. anthropic.com/glasswing ARC Prize. ARC-AGI Leaderboard. Semi-Private set, accessed 19 October 2026. arcprize.org/leaderboard ARC Prize (2026). OpenAI’s GPT-6 Astra on ARC-AGI-3. 3 September 2026. arcprize.org METR (2025). Measuring AI Ability to Complete Long Software Tasks. arXiv:2503.14499. arxiv.org/abs/2503.14499 METR. Time horizons of frontier models (Time Horizon 1.1). Opus 4 1.67 h, Opus 4.5 4.88 h, Opus 4.6 11.98 h. Accessed 19 October 2026. metr.org/time-horizons METR (2026). Time horizon estimate for an early version of Claude Mythos Preview. Post on X, May 2026. x.com/METR_Evals Anthropic (2026). Claude Fable and Mythos 5.1. 1 September 2026. anthropic.com Anthropic (2026). Measuring agent autonomy. 18 February 2026. anthropic.com/research gcalcli: Google Calendar command line interface. github.com/insanum/gcalcli GitHub. GitHub CLI. cli.github.com Open Library. Search API. openlibrary.org OMDb API: the Open Movie Database. omdbapi.com yt-dlp. github.com/yt-dlp/yt-dlp Strands Agents. Open-source agent SDK. strandsagents.com OpenRouter. openrouter.ai Anthropic. Claude Code headless mode. code.claude.com/docs Strands Agents (2026). Introducing Strands harness: frontier performance with 28% lower token cost. 21 September 2026. strandsagents.com/blog Strands Agents. Harness: shell and files. Quoted from the section “Everything routes through the sandbox”. strandsagents.com/docs Anthropic (2025). Introducing Agent Skills. 16 October 2025. claude.com/blog/skills"},{"href":"/celebrating-the-release-of-torchneuron/","title":"Celebrating the release of TorchNeuron","subtitle":"Our journey at Loka with AWS silicon and Annapurna Labs, and why this moment matters to us","description":"Bojan Jakimovski shares Loka's journey from BEVFusion on AWS silicon to native PyTorch with TorchNeuron, ESMC on Trainium2, and the AWS Trainium Frontier Competition.","abstract":"Bojan Jakimovski shares Loka's journey from BEVFusion on AWS silicon to native PyTorch with TorchNeuron, ESMC on Trainium2, and the AWS Trainium Frontier Competition.","tags":["TorchNeuron","AWS Trainium","PyTorch","Annapurna Labs"],"topics":["trainium","llm-training"],"authors":["Bojan Jakimovski"],"text":"TorchNeuron is here, and we’re excited about what we can build with it. At Loka, we’re already bringing its native PyTorch workflow into our research and client work. Our journey on AWS Silicon started with real customer workloads and took us through custom kernels, applied research, and conversations with Annapurna Labs about the tools we wanted to use. A native PyTorch backend was high on that list, and now it’s finally here. Getting started with AWS Silicon We got started at the end of 2024 with two client projects on AWS Silicon. Sebastian Gonzalez Aseretto and Nicolás Roldán Fajardo worked on one. On the other project, I worked with Zafir Stojanovski and Henrique Ribeiro Delgado da Silva. Real customer workloads gave us a practical way to learn what these chips could do and where we needed to dig deeper. Zafir, Henrique, and I focused on migrating BEVFusion to AWS Neuron. The Neuron Kernel Interface (NKI) had just become available, so we experimented with NKI kernels and wrote custom C++ operations too. I enjoyed working through those details and getting closer to the hardware. We put what we’d learned into a report and presentation for Annapurna Labs, covering what worked well and where the developer experience could improve. A native PyTorch backend was high on our list: we wanted to bring our models and training code over using the tools we already knew. We sent the deck over, and it started making its way around the team. One moment at AWS Summit New York in 2025 caught me completely off guard. We were talking with the Annapurna Labs team at their booth about our work when they recognized us as the Loka team behind the presentation. Then one of them pulled out his phone and brought up our deck. I was stunned. It was the same presentation Zafir, Henrique, and I had put together, now being shown back to us in the middle of the conversation. I hadn’t expected them to recognize our work, let alone pull up the deck right there. We even have a photo from that moment. Our BEVFusion presentation on a phone at the Annapurna Labs booth, AWS Summit New York 2025, alongside Bojan Jakimovski with the AWS team. Select either photo to view the original. The native PyTorch workflow we wanted We stayed in touch after New York, and Annapurna Labs gave us early access to the first TorchNeuron beta. And trust me, the appeal was immediate. With TorchNeuron’s native backend installed, we can move a supported model and its input tensors onto the Neuron device with .to(\"neuron\") and start experimenting in eager mode. For compiled workloads, we keep that device placement and use torch.compile(model, backend=\"neuron\"). We’re working through our training and inference code with familiar PyTorch tooling, without an XLA-specific execution loop. After our conversations in 2024 and 2025, getting to run our own code this way felt especially satisfying. That extends to distributed training. TorchNeuron supports the PyTorch distributed APIs, including DDP, FSDP, and DTensor, with sharding configured for the NeuronCores we use. A sketch of the native TorchNeuron workflow, from device placement to eager execution, compilation, and distributed training. Putting TorchNeuron to work We’ve been putting that workflow to use in our applied research. One experiment I especially enjoyed was post-training Tiny ESMC in pure PyTorch, which worked like a charm. We’ve also been experimenting with SAM3, GENA-LM, and Boltz 2.2.1. ESMC-300M gave us a concrete example of that workflow. For zero-shot protein-variant scoring, we kept the model in PyTorch, switched off Flash Attention to use the standard attention path, and compiled the transformer blocks with torch.compile. No model rewrite was needed. A single Trainium2 instance reached 490.8 variants per second, enough to score roughly 42.4 million a day at that rate. At batch size 16 and sequence length 512, that was 18.6% higher throughput than our H100 baseline, with nearly identical ROC-AUC. The cost per variant was about 60% lower at the Capacity Block reservation rates we used in August 2026. For the code, setup, and full benchmarks, take a look at our ESMC-on-Trainium2 post. João Correia, Telmo Felgueira, Tiago Gonçalves, and I wrote it with Jim Burtoft and Louise Ping, our friends at AWS’s Annapurna Labs. Tiago took that ESMC work to Sword AI Summit 2026 in Portugal. In his talk, “Foundation Models on AWS Trainium,” he shared our experience running the model on Trainium2. Tiago Gonçalves presenting “Foundation Models on AWS Trainium” at Sword AI Summit 2026, Portugal. What’s next And we’re still cooking. Alongside our applied research, we’re working with two major clients, one in food delivery and one in streaming entertainment. We’re stress-testing ranking models in native PyTorch with one and preparing to work on LLMs with the other. The early ranking-model results have us excited. Our next steps are to keep testing the inference code, compare serving configurations, and get the LLM work underway. Tiago and I are now competing in Phase 2 of the AWS Trainium Frontier Competition with The Optimal Batch @ Loka. As of October 19, 2026, we’re third out of ten teams on the public leaderboard. It’s exciting to see how far we’ve come, and we’re still pushing to improve our results. Phase 2 leaderboard as of October 19, 2026: The Optimal Batch @ Loka is third out of ten teams. Select the image to view the full-size screenshot. What excites me now is how much more we can explore with the PyTorch tools we already know, whether we’re testing a research idea or building for a client. There’s still hardware-specific work to do, from checking compatibility to tuning performance, and we’re eager to get into it. I’m grateful to everyone at Loka and Annapurna Labs who’s been part of this journey since 2024. We’ll keep sharing what we learn as the client work and the competition progress. Give TorchNeuron a try on AWS Silicon. And if you’d like a hand bringing your own models and workloads over, reach out to us at Loka. We’d love to help you get them running. Let’s put TorchNeuron to work."},{"href":"/picking-mcp-tools-with-semantic-search-and-jev/","title":"Your Agent Doesn't Need 138 Tools: Picking MCP Tools with Semantic Search and Jev","description":"Mario Petkoski compares all 138 MCP tools with semantic search and Jev on 89 MCP-Atlas tasks, measuring answer quality, cost, and latency with a 12-tool budget.","abstract":"Mario Petkoski compares all 138 MCP tools with semantic search and Jev on 89 MCP-Atlas tasks, measuring answer quality, cost, and latency with a 12-tool budget.","tags":["AI Agents","Model Context Protocol","Amazon Bedrock","Semantic Search","Embeddings","Jev","Benchmarks"],"topics":["agents","benchmarks"],"authors":["Mario Petkoski"],"text":"An agent connected to many MCP servers sends every tool definition with every model call. I tested sending only a small set per request, chosen by semantic search or by Jev, on MCP-Atlas tasks. Both more than halved the median cost per task. Semantic search was the faster and cheaper of the two, and Jev’s answers were on par with loading every tool in the context. Connecting an agent to MCP servers is easy. Connecting it to many of them gets expensive quickly. Each server brings its own tools, and each tool’s name, description and parameter schema is sent to the model on every call, whether the request needs it or not. In this experiment, 20 MCP servers came to 138 tools and about 30,000 tokens of tool definitions per model call, before the model had even read a word of the user’s question. So the problem is clear: the more capable you make the agent, the more each call costs and the more tools the model has to sort through. At the same time, I wanted to try Jev from TypeSafeAI. It’s one of the new, popular things in AI right now, and most of the examples I found were vague. I didn’t want to build another generic demo. I wanted a real problem I could measure, where the result would be useful whichever way it came out. Tool picking matched exactly what I was looking for. Deciding which tools can help with a request is a question about meaning, and Jev is built to answer typed questions like that about a piece of context. There’s also a clear baseline to compare against: embeddings plus keyword search, usually referred to as “semantic search”, which is what most people build first. The idea came from Claude’s built-in tool search. In the Claude API (directly or on Amazon Bedrock) you can mark tools as deferred, and Claude searches for the ones it needs instead of seeing every definition upfront. The MCP client best practices recommend the same approach under the name “Progressive Tool Discovery”. I wanted to see how well that idea works when the selection is done via semantic search or via Jev. To make the results mean something, I needed a benchmark. MCP-Atlas from Scale AI fits well: It runs real MCP servers in one Docker container: Wikipedia, arXiv, PubMed, clinical trials, OpenStreetMap, weather, filesystem, git, code runners and more. Its tasks are written by people and never name a tool. “Which food type in my local food consumption data…” doesn’t say “use filesystem_read_text_file”. Every task comes with answer facts and a reference solution, so answers can be graded against something fixed. Atlas has 36 servers total, but only 20 run without API keys. These 20 servers provide 138 tools combined, which can solve 89 of the 500 public tasks. They need a median of 4 tools and 3 answer facts each. That gave me one question to answer: Can you give the model 12 tools instead of 138 without losing quality, and which picker does it best? Why 12? MCP-Atlas’s own hand-picked tool lists hold a median of 12 of the available tools for these 89 tasks, so 12 is roughly what a person would choose. It also cuts the tool definitions from about 30,000 tokens to about 4,000. I fixed the number before any run and gave both pickers the same budget, so they compete on equal terms. Three setups I compared three ways of giving the model its tools, from the most obvious to the newest. 1. All tools Connect every server and give the model all 138 tools on every call. This is what you get by default, and it’s the quality baseline: every tool is always in view, so the model never misses one because it wasn’t shown. 2. Semantic search (embeddings + BM25) Before each request, rank the tools by how well their text matches the request and load the top 12. The embeddings come from Amazon Nova 2 multimodal embeddings on Bedrock, with 1,024 dimensions; Nova beat Titan Text Embeddings V2 in my first tests. Embeddings alone miss exact words, so the ranking fuses them with BM25 keyword scores. This is the standard retrieval recipe, and it’s a strong baseline. Many retrieval setups add a third step: a reranker model that reads the request next to each tool and reorders the list. Jev could also fill that role, rescoring only semantic search’s top results instead of all 138 tools. At this stage, both were unnecessary: I wanted to compare the simplest version of each picker. 3. Jev Same budget of 12 tools, but Jev scores them. Jev takes a state (the user’s request) and answers typed questions about it with calibrated probabilities. I pinned the version (jev-1.13.0) so results stay comparable. Jev can ask this in two ways: Noul asks one yes/no question per tool: “Would calling tool help an assistant answer request?” The criteria spell out what yes and no mean: yes if the tool “looks up or returns information that request asks for, or is a step toward getting it”, no if it’s “for a different service, resource, or task”. Each tool gets its own probability, so several tools can score high at the same time. Choice asks one pick-one question over all 138 tools: “Which tool should an assistant call first to answer request?” The probabilities add up to 1, so tools compete for a single spot. What each picker sends and gets back The two pickers look similar from the outside: a request goes in, 12 tools come out. They move very different data to get there. Embeddings: the tools are processed once, and each request is a single small call The tools are embedded ahead of time, not per request. Each tool becomes one short text: its name, the first 600 characters of its description, and its parameter names. Nova takes one text per call, so indexing is 138 Bedrock calls (8 in parallel), each returning a vector of 1,024 numbers. The vectors are cached on disk and only recomputed when a tool’s text changes. The BM25 keyword index is built locally from the full descriptions. For each request, only the request needs to be embedded: one Bedrock call of about 80 tokens, which returns one vector. Everything else happens locally: Compare the request’s vector with each of the 138 tool vectors (a dot product). Score the request’s words against each tool with BM25. Fuse the two rankings with reciprocal rank fusion: each tool gets 1 / (60 + its position) from each list, and the sums decide the order. Load the top 12. The request and the tools are never read together. Each is turned into a vector separately, and the picker only compares vectors. However, it also means a tool can rank high because its description shares words with the request even when it can’t help, and the right tool can rank low because it shares none. Jev: no index, and every pick is one request that carries everything With Noul, each pick is one call to Jev’s API that contains the state and all 138 questions, one per tool, keyed by the tool’s name. Each question includes that tool’s name, the first 600 characters of its description, its parameter names, the question and the yes/no criteria. In simplified form: state = {\"request\": \"Which food type in my local food consumption data…\"} questions = { tool.name: Noul( instructions={ \"tool\": {\"name\": tool.name, \"description\": tool.description[:600], \"parameters\": tool.parameter_names}, \"question\": \"Would calling `tool` help an assistant answer `request`?\", }, criteria=NoulCriteria(true=\"…\", false=\"…\"), ) for tool in tools # all 138 in the same request } response = client.system_one(state=state, questions=questions, model=\"jev-1.13.0\") scores = {name: answer.noul for name, answer in response.nouls.items()} top_12 = sorted(scores, key=scores.get, reverse=True)[:12] That’s about 23,300 input tokens per pick, within Jev’s documented limit of 64k tokens per request. For a larger set of tools, the code splits the questions into several requests and sends them in parallel. Jev returns one probability per tool, and the picker keeps the 12 highest. Choice takes a different approach. Instead of 138 separate yes/no questions, it sends the same state with a single multiple-choice question, “Which tool should an assistant call first to answer request?”, with the 138 tools as the options. Jev returns one probability distribution across all of them that adds up to 1, and the picker keeps the 12 most likely. Descriptions are shortened only if all the options wouldn’t fit; with these 138 tools they didn’t need to be. Comparing the two approaches Both return a probability for every tool, so either list can be sorted to take the top 12. What differs is what those probabilities mean. A Choice question has exactly one right answer, and its probabilities add up to 1. That’s why its question asks for the first tool: “which tools would help?” has several right answers, and a one-answer question can’t express that. As a result, Choice’s probabilities measure “is this the first step?”, not “is this useful?”. If one tool is the obvious first step, it takes most of the probability, and tools needed later, such as running code after reading a file, get small shares even when the task can’t be done without them. Noul asks about each tool on its own, so four useful tools can all score close to 1. That matches what the top 12 should contain, so the real run used Noul. So where embeddings compare two vectors that were made separately, Jev reads the request next to each tool and judges them as a pair. That costs about 290 times as many input tokens per pick and takes longer, but it means a tool is judged by whether it would help with the request, not by how similar its wording is. Because Jev’s scores are probabilities, a fixed cutoff such as “load every tool above 0.5” means the same thing on every request. That lets the agent load a different number of tools for each request, for example 3 for a simple question and 10 for a complex one. Embedding scores don’t allow that: a similarity of 0.6 can be a good match for one request and a poor one for another, so one cutoff doesn’t work across requests. I still used a fixed 12 tools so both pickers got the same budget. The find_tools fallback Both pickers also load a find_tools tool. If the model needs something it can’t see, it describes the capability (“read a CSV file”) and the same picker adds matching tools. So a bad first pick can be fixed, but each fix costs an extra round trip. Model and run settings Agent: Strands Agents on Amazon Bedrock with Claude Sonnet 4.6 at temperature 0, max_tokens 32,000, and a limit of 100 tool calls per answer. I chose Sonnet 4.6 because it still accepts a temperature setting; newer models reject sampling parameters, and temperature 0 keeps the three setups as comparable as possible. Judge: also Sonnet 4.6 at temperature 0, using Atlas’s own per-fact rubric. Each answer scores 1 (fulfilled), 0.5 (partly) or 0 (missed). Coverage is the mean, and a task passes at 75% coverage. Every answer is graded the same way, including the all-tools ones. Fairness: each answer uses a fresh one-shot agent. The sandbox caches tool results, so the same tool call returns the same data in all three setups. Bedrock’s prompt cache only helps a request that starts with exactly the same tool definitions as an earlier one. The all-tools setup sends 138 tools and the pickers send 12, so the pickers can never reuse its cache. The two pickers can pick the same 12 tools for a task, so the run waits 5.5 minutes before the second picker, long enough for semantic search’s cache entries to expire. All 89 tasks were answered three times, once per setup. Quality setup passed mean coverage tool tokens per call used find_tools total cost all tools 61/89 81% 29.8k – $51.97 semantic search 52/89 70% 4.5k 36 tasks $36.34 Jev (Noul) 60/89 78% 3.7k 12 tasks $31.98 Jev performed similarly to loading every tool: 60 passes against 61, and mean coverage 2.6 percentage points lower. Coverage is the share of a task’s answer facts that the answer got right, with half credit for partly right ones, averaged over all 89 tasks. Semantic search clearly fell behind: 52 passes and coverage 10.4 points lower. The first pick explains most of the difference. On average, Jev’s first 12 tools included 59% of each task’s reference tools; semantic search’s included 32%. It also shows in the fallback: the semantic-search agent reached for find_tools on 36 tasks, the Jev agent on 12. Is the gap real, or luck in which tasks were tested? 89 tasks is a small sample. A different set of 89 tasks would give different gaps. To estimate how much they could move, I used a bootstrap: For each of the 89 tasks, subtract all tools’ coverage from the picker’s coverage. That gives 89 differences. Draw 89 of those differences at random, allowing the same task to be drawn more than once, and average them. This mimics testing on a different set of 89 tasks. Repeat step 2 a total of 10,000 times, which gives 10,000 averages. Sort the averages and drop the lowest 2.5% and the highest 2.5%. The middle 95% is the range the gap would likely fall in on a different set of tasks. A negative number means the picker scored lower than all tools; a positive number means it scored higher. Jev: −7.9 to +2.5 points. The range includes zero, so these 89 tasks can’t show whether Jev is worse than loading every tool, equal to it, or better. Jev could plausibly be up to 7.9 points worse or up to 2.5 points better. Semantic search: −17.0 to −4.4 points. The whole range is below zero, and 9,999 of the 10,000 averages were below zero, so semantic search’s lower score is not luck. When the right tools share no words with the request The gap isn’t spread evenly. On the other 39 tasks, mostly about public information (museums, web search, Wikipedia, books, maps and so on), all three setups scored 72–75% coverage. On the 50 tasks about the user’s local files, all tools scored 85%, Jev 83%, and semantic search 69%. One task illustrates it best. It asks: “Which food type in my local food consumption data has the most satisfaction ratings of 5, and which beverage types accompany it when the rating is 5?” The reference solution lists the allowed directories, lists a directory, reads a text file and runs code. Apart from words like “the” and “and”, none of those four tools shares a word with the request. Semantic search’s 12 tools held none of the four. Instead they included map, weather and meeting-point tools whose descriptions share words like “type” and “data”, and that answer covered none of the answer facts. Jev’s 12 held three of the four, including the file-reading and code tools, and that answer covered all of them. On seven tasks, the semantic-search agent answered without calling any tool at all. Embeddings and keywords measure how similar the words are. Jev’s question asks whether the tool would help. When the words point one way and the meaning another, that difference decides the result. Cost Both pickers cut tool tokens per model call by 85–88% and the median cost per task by 56% ($0.20 → $0.09). The total bill fell less: 30% for semantic search and 38% for Jev. A few answers drive much of the cost: the 10 most expensive make up 38% of the bill with all tools, 54% with semantic search and 68% with Jev. They read whole directory trees, open many files at once, or loop through 50–95 model calls. Most of their tokens are file contents and long conversations rather than tool definitions, so picking tools saves proportionally less on them. Savings per call don’t turn directly into savings on the bill. Picking tools costs very little either way. Across all 89 tasks, Jev’s picks cost $0.096 and the embedding picks $0.0012. In total Jev’s picks cost about 80 times more, but that’s still around 0.3% of the bill, and Jev’s total came out $4.36 lower than semantic search. Speed setup picking tools, median model time, median whole answer, median all tools – 20.6 s 25.0 s semantic search 0.48 s 20.7 s 25.8 s Jev (Noul) 2.21 s 20.6 s 26.5 s Speed was the least interesting result: fewer tools didn’t make the agent faster. Median model time was 20.6–20.7 seconds in all three setups. Most of an answer’s time is the model’s own time, and the tool definitions are served from the prompt cache after the first call, so a shorter tool list likely changes little. The difference is in the pick itself. Jev takes 2.2 seconds at the median (6.1 s at the 90th percentile), against 0.5 seconds for embeddings. For a chat agent answering in 25 seconds that doesn’t matter much. For something latency-sensitive, it does. Caveats Sample size. 89 tasks is small; treat differences of a few tasks as noise. Of the 30 tasks also answered in an earlier run, pass counts barely moved (all tools 23 → 23, semantic search 19 → 19, Jev 23 → 24), but 2–6 individual tasks per setup flipped between pass and fail. LLM grading. Answers are graded by Claude against fixed facts, not by exact matching. Stale facts. Some answer facts were written against 2025 data (repository stars, domain records, live listings) and may have changed since. Failed runs. Each picker had 2 answers that hit the output token limit; all tools had none. Those answers count as failed with 0% coverage, but their cost isn’t in the cost totals. One Jev request failed with a server error, and that turn fell back to loading every tool. A leftover example. The description of find_tools’s parameter still carried an example from an earlier version of the agent (“list CloudWatch alarms”). The pickers’ agents saw it and the all-tools agent didn’t. It has since been removed. Duplicate tools. The sandbox’s Wikipedia server lists its 11 tools twice under two names. Reference solutions use the first names. One budget, one model. I tested only 12 tools on Sonnet 4.6. Other budgets, models or tool collections could come out differently. Not Claude’s tool search. find_tools is my own, built on each picker. I didn’t benchmark Anthropic’s built-in tool search tool. Conclusion Back to the question: yes, you can give the model 12 tools instead of 138. With a good picker you lose little or no quality and cut the bill by more than a third. The picker matters a lot, though. approach use it when All tools You have a handful of servers, quality matters most, and token cost isn’t a concern for you yet. It’s the simplest setup and the baseline to beat. Semantic search Your tools cover clearly separate areas with distinct wording, and you need picks that are fast (about 0.5 s) and nearly free. Watch out if the same words appear across different areas of your tools. Jev You have many overlapping tools, and your users don’t phrase requests in the tools’ vocabulary. You get close to all-tools quality at picker cost, and you pay about 2 seconds per pick. What this means for your agent Stop sending every tool. With the right picker, 12 tools did the work of 138. Quality held, and the median task cost less than half as much. Users don’t speak in your tools’ words. Someone asking about “my local food consumption data” needs a file reader and a code runner, but never says “file” or “code”. Your picker has to understand what the request needs, not just match its words. Your token count isn’t your bill. An 88% cut in tool tokens became a 38% cut in cost, because a few long answers make up much of what you pay. Measure the whole bill. What I’d test next: larger collections of tools, other budgets than 12, and Claude’s built-in tool search as a fourth setup. By default, an agent sends its whole toolbox with every call: here, 138 tools and 30,000 tokens, for a task that typically needed 4. Your agent doesn’t need 138 tools. It needs the four that answer the question, and a picker smart enough to find them."},{"href":"/running-large-language-models-fully-offline-on-mobile-with-react-native/","title":"Running Large Language Models Fully Offline on Mobile with React Native","description":"Paolo Pecis explores fully offline speech-to-text and LLM summarization on iOS and Android with React Native, whisper.rn, llama.rn, and the SoloAI app.","abstract":"Paolo Pecis explores fully offline speech-to-text and LLM summarization on iOS and Android with React Native, whisper.rn, llama.rn, and the SoloAI app.","tags":["React Native","LLM","Machine Learning","Mobile Development","Offline AI"],"topics":[],"authors":["Paolo Pecis"],"text":"In the last few years, running Machine Learning models locally has become increasingly viable, even on constrained devices like smartphones. With the right tradeoffs, it’s now possible to run speech-to-text, text generation, and other ML workloads directly on a mobile device without relying on cloud APIs. This approach enables offline-first experiences and privacy-by-design applications, where sensitive data is processed entirely on the user’s device. In this article, I’ll walk through my research on running local LLMs on mobile using React Native (a cross platform development framework based on TypeScript), the libraries I evaluated, the limitations I encountered, and how all of this materialized into a real showcase app called SoloAI. Why Local ML on Mobile? Running models locally has a few major advantages: Offline-first experiences User privacy, no data sent to third parties Lower operational costs, no inference servers Lower latency, especially for short tasks The obvious downside is that mobile devices have limited CPU, memory, storage, and battery. The challenge is finding the right balance between model size, performance, accuracy, and user experience. Evaluated Libraries TensorFlow Lite via react-native-fast-tflite I initially explored react-native-fast-tflite, a performant React Native bridge for TensorFlow Lite models. I tested some models sourced from Kaggle: Spam detection classifiers MobileBERT for question answering EfficientDet for object detection using the device camera Spam detection with TensorFlow Lite Question answering with MobileBERT Object detection with EfficientDet on Android This setup worked, but the results for visual object detection were inconsistent and not always accurate enough for a polished product. Performance also varied significantly across devices. Moreover, these TFLite models are also harder to manage compared to the Whisper and LLaMA-based approaches described later because each model needs to be analyzed and checked: which inputs and outputs it requires, how to parse tokens, and various other constraints. The preparation code is quite extensive: import { loadTensorflowModel } from 'react-native-fast-tflite'; //Load the model from local path const handleLoadModel = async () => { setLoading(true); try { const loadedModel = await loadTensorflowModel(mobileBertModel); setModel(loadedModel); setModelInfo(modelToString(loadedModel)); } catch (e) { Alert.alert('Error', 'Failed to load MobileBERT model'); } finally { setLoading(false); } }; //Run and parse the model const handleRun = useCallback(async () => { if (!model || !question.trim() || !passage.trim()) { Alert.alert('Error', 'Please provide both question and passage'); return; } try { const inputs = prepareInputs(question, passage); // MobileBERT typically expects 3 inputs: input_ids, attention_mask, token_type_ids const modelInputs = [ inputs.inputIds, inputs.attentionMask, inputs.tokenTypeIds, ]; const results = await model.run(modelInputs); const result = processModelOutputs(results, inputs); setOutput(result); } catch (error) { Alert.alert('Error', `Failed to run model: ${error}`); setOutput(null); } }, [model, question, passage]); //Helper only for MobileBERT input/output mapper import RAW_VOCAB from '@assets/vocab.json'; const VOCAB = RAW_VOCAB as Record<string, number>; export const MAX_SEQ_LENGTH = 384; // Standard for BERT models export const MAX_QUERY_LENGTH = 64; export interface QAResult { answer: string; confidence: number; startIndex: number; endIndex: number; } export interface ModelInputs { inputIds: Int32Array; attentionMask: Int32Array; tokenTypeIds: Int32Array; passageStartIndex: number; passageTokens: number[]; } // Build a reverse lookup map once const REVERSE_VOCAB: Record<number, string> = Object.entries(VOCAB).reduce( (acc, [token, id]) => { acc[id] = token; return acc; }, {} as Record<number, string>, ); // 2) Tokenizer: split on whitespace and map to IDs via your full VOCAB export const tokenize = (text: string): number[] => { // lower-case, strip punctuation (keep only letters/numbers/space), then split const cleaned = text.toLowerCase().replace(/[^\\w\\s]/g, ''); // <-- remove punctuation const words = cleaned.split(/\\s+/); return words.map(w => VOCAB[w] ?? VOCAB['[UNK]']); }; // 3) Prepare BERT inputs exactly as before export const prepareInputs = ( question: string, passage: string, ): ModelInputs => { const CLS = VOCAB['[CLS]']; const SEP = VOCAB['[SEP]']; const PAD = VOCAB['[PAD]']; // tokenize & truncate question const qTokens = tokenize(question).slice(0, MAX_QUERY_LENGTH); let pTokens = tokenize(passage); // limit passage length so total ≤ MAX_SEQ_LENGTH const maxPassageLen = MAX_SEQ_LENGTH - qTokens.length - 3; if (pTokens.length > maxPassageLen) { pTokens = pTokens.slice(0, maxPassageLen); } // build [CLS] + question + [SEP] + passage + [SEP] const inputIdsArr: number[] = [CLS, ...qTokens, SEP, ...pTokens, SEP]; // pad up to MAX_SEQ_LENGTH while (inputIdsArr.length < MAX_SEQ_LENGTH) { inputIdsArr.push(PAD); } // attention mask = 1 for real tokens, 0 for PAD const attentionMaskArr = inputIdsArr.map(id => (id === PAD ? 0 : 1)); // token type IDs: 0 for question segment, 1 for passage segment const tokenTypeIdsArr = new Array<number>(MAX_SEQ_LENGTH).fill(0); const passageStartIndex = qTokens.length + 2; // after [CLS]+question+[SEP] for ( let i = passageStartIndex; i < passageStartIndex + pTokens.length + 1; i++ ) { tokenTypeIdsArr[i] = 1; } return { inputIds: Int32Array.from(inputIdsArr), attentionMask: Int32Array.from(attentionMaskArr), tokenTypeIds: Int32Array.from(tokenTypeIdsArr), passageStartIndex, passageTokens: pTokens, }; }; // 4) Post‐process logits back into text answer export const processModelOutputs = ( results: any[], inputs: ModelInputs, ): QAResult => { if (results.length < 2) { throw new Error('Expected at least 2 outputs (start_logits, end_logits)'); } const startLogits = results[0] as Float32Array; const endLogits = results[1] as Float32Array; let bestScore = -Infinity; let bestStart = inputs.passageStartIndex; let bestEnd = inputs.passageStartIndex; const passageEnd = inputs.passageStartIndex + inputs.passageTokens.length; const maxAnswerLen = 30; // find best span in the passage region for (let i = inputs.passageStartIndex; i < passageEnd; i++) { for (let j = i; j < Math.min(i + maxAnswerLen, passageEnd); j++) { const score = startLogits[i] + endLogits[j]; if (score > bestScore) { bestScore = score; bestStart = i; bestEnd = j; } } } // extract the token IDs for that span (relative to passage) const startOffset = bestStart - inputs.passageStartIndex; const endOffset = bestEnd - inputs.passageStartIndex; const answerIds = inputs.passageTokens.slice(startOffset, endOffset + 1); // map back to tokens and join const answerTokens = answerIds.map(id => REVERSE_VOCAB[id] ?? '[UNK]'); const answerText = answerTokens.join(' ').replace(/##/g, ''); // approximate confidence via sigmoid of bestScore const confidence = 1 / (1 + Math.exp(-bestScore)); return { answer: answerText || 'No answer found', confidence, startIndex: bestStart, endIndex: bestEnd, }; }; // Default sample data export const DEFAULT_PASSAGE = 'France is a country in Western Europe. Paris is the capital and largest city of France. The city has a population of over 2 million people and is known for landmarks like the Eiffel Tower and the Louvre Museum.'; export const DEFAULT_QUESTION = 'What is the capital of France?'; This complexity pushed me toward focusing on text-based and audio-based use cases, where the results were far more reliable and the setup easier. Speech to Text with whisper.rn whisper.rn is a React Native bridge around whisper.cpp, a highly optimized C++ implementation of OpenAI’s Whisper models. It worked well, providing good transcription accuracy, even with small models, fully offline inference, and predictable performance on modern smartphones. For the MVP, I used the ggml-tiny.en.bin model, which is around 77 MB and small enough to be bundled directly with the app. import { initWhisper, TranscribeFileOptions, TranscribeResult, WhisperContext, } from 'whisper.rn/index.js'; //Initialize the whisper model useEffect(() => { const initializeWhisper = async () => { try { whisperContextRef.current = await initWhisper({ filePath: require('../../../../assets/models/ggml-tiny.en.bin'), }); setIsModelLoaded(true); } catch (error) { console.error('Error initializing Whisper model:', error); } }; initializeWhisper(); }, []); //Run the model and get the transcritpion of the audioResoursce const handleTranscribeAudio = useCallback(async (audioResource: string) => { setIsTranscribing(true); const options: TranscribeFileOptions = { language: 'en', prompt: 'Your name is SoloAI, and you are an helpful assistant that transcribes audio files to store them as notes.', }; if (!whisperContextRef.current) { Alert.alert('Error', 'Whisper model is not loaded.'); return; } try { const { promise } = whisperContextRef.current.transcribe( audioResource, options, ); const result = await promise; setTranscription(result.result); } catch (error) { console.error('Error transcribing audio:', error); const errorMessage = error instanceof Error ? error.message : 'Failed to transcribe audio.'; Alert.alert('Error', errorMessage); } finally { setIsTranscribing(false); } }, []); Text Generation with llama.rn For text generation and summarization, I used llama.rn, a React Native binding of llama.cpp. This enables fully offline LLM inference and support for GGUF models (LLaMA, Mistral, etc.) with no dependency on cloud APIs. import { initLlama, LlamaContext, RNLlamaOAICompatibleMessage } from 'llama.rn'; //Initialize the llama model const initializeLlama = useCallback(async () => { setLlamaInitialized(false); try { if (llamaModelPath) { const context = await initLlama({ model: llamaModelPath, use_mlock: true, n_ctx: 2048, n_gpu_layers: 1, }); llamaContextRef.current = context; setLlamaInitialized(true); } } catch (error) { console.error('Error initializing Llama model:', error); setLlamaInitialized(false); } }, [llamaModelPath]); //Run the model and get the summary of the giver transcription const handleSummarization = useCallback(async (transcription: string) => { if (!llamaContextRef.current || !transcription) { console.warn('Llama context or transcription is not available'); return; } try { setIsSummarizing(true); const messages: RNLlamaOAICompatibleMessage[] = [ { role: 'system', content: LLAMA_SUMMARIZATION_PROMPT, }, { role: 'user', content: transcription, }, ]; const result = await llamaContextRef.current?.completion({ messages: [...messages], n_predict: 100, stop: [...stopWords], }); return result.text; } catch (error) { console.error('Error during summarization:', error); } finally { setIsSummarizing(false); } }, []); The model used in the MVP is: Llama-3.2-1B-Instruct-IQ4_XS_imat.gguf This model is approximately 743 MB, which introduces an important constraint. Handling Large Models on Mobile Bundling a 700+ MB model directly inside a mobile app bundle is not realistic because of app store size limits, long install times and the overall poor user experience. The Compromise SoloAI uses a manual model download approach: The app works offline by default. The only time an internet connection is required is when the user downloads the LLaMA model. Once downloaded, the model is stored locally and reused indefinitely. This setup keeps the app app-store friendly, transparent about storage usage and fully offline after initial setup. One-time model download Downloading the LLaMA Model with react-native-fs To handle large file downloads, I used react-native-fs, which provides reliable filesystem access on both iOS and Android. Below is a simplified example of how the LLaMA model is downloaded and stored locally. Example: Model Download Function import RNFS from 'react-native-fs'; const LLAMA_MODEL_URL = 'https://your-cdn-or-storage.com/Llama-3.2-1B-Instruct-IQ4_XS_imat.gguf'; const MODEL_DESTINATION_PATH = `${RNFS.DocumentDirectoryPath}/llama.gguf`; export const downloadLlamaModel = async ( onProgress?: (progress: number) => void, ): Promise<string> => { const download = RNFS.downloadFile({ fromUrl: LLAMA_MODEL_URL, toFile: MODEL_DESTINATION_PATH, progress: (res) => { const progressPercent = (res.bytesWritten / res.contentLength) * 100; onProgress?.(progressPercent); }, progressDivider: 1, }); const result = await download.promise; if (result.statusCode !== 200) { throw new Error('Failed to download LLaMA model'); } return MODEL_DESTINATION_PATH; }; Once downloaded, this path is passed directly to llama.rn when initializing the model context. After this step, the app can run fully offline, including transcription and summarization. Technology Stack Overview The entire project is built using React Native, targeting both iOS and Android from a single TypeScript codebase. The core ML stack is composed of: whisper.rn: offline speech-to-text llama.rn: offline text generation and summarization @simform_solutions/react-native-audio-waveform: audio recording with waveform visualization. A custom patch was applied to support uncompressed .wav format, required by Whisper (the library originally supported only .m4a) @op-engineering/op-sqlite: Used to store all data locally using SQLite Redux: state management App Showcase Onboarding & Login Carousel onboarding shown on first app launch Explains core features and offline benefits Secure access via biometric authentication or PIN Ensures notes and data remain private Offline onboarding and security setup PIN and biometric login Main Dashboard List of all notes with: Category Duration Date Title First lines of transcription Search bar with filtering and sorting to quickly find notes Recordings dashboard and search Recording filters and sorting Record Screen Start and stop voice recording Real-time audio waveform visualization After recording: Modal to choose category Editable note title Voice recording with a live waveform Recording title and category selection Note Detail Screen Full transcription view Generated summary Actions: Edit title Change category Copy transcription or summary Delete note Locally generated transcription Locally generated summary Changing a note’s category Settings & Category Management Change PIN code Terms & Conditions Contact information Delete all notes Manage categories: Create new categories Edit name and color Delete existing categories SoloAI settings Managing note categories Editing category names and colors Conclusion This research demonstrates that running ML models locally on mobile devices is not only feasible, but practical. While there are clear limitations related to performance, precision, and model size, the results show strong potential for fully offline applications, privacy-first user experiences and reduced dependency on cloud infrastructure. SoloAI serves as a concrete example of how local ML can be used to build meaningful, user-facing products that respect user privacy and work even without an internet connection. You can download and test SoloAI App Store: SoloAI by Loka Play Store: SoloAI by Loka"},{"href":"/agentcore-identity/","title":"Everything you need to know about Amazon Bedrock AgentCore Identity","subtitle":"Authentication and authorization for AI agents on AWS","description":"Authentication and authorization for AI agents on AWS. Who is allowed to call your agent, and how your agent proves itself to everything it calls.","abstract":"Authentication and authorization for AI agents on AWS. Who is allowed to call your agent, and how your agent proves itself to everything it calls.","tags":["Amazon Bedrock AgentCore","OAuth","AI Agents","Security"],"topics":[],"authors":["Matheus Dias"],"text":"We build production AI agents on AWS at Loka. I wrote this after losing more than one afternoon to the auth model below. Everything here was checked against the AWS documentation as of September 2026. This is the complete guide. It’s long, and it’s built to be skimmed and bookmarked as much as read straight through. About 90 minutes end to end, or ten if you use the contents menu to find the one section you came for. Every AI agent worth deploying eventually has to touch something private. A user’s Google Drive, a Slack workspace, an internal API with real customer data in it, another agent, an MCP server behind a Gateway, and the list goes on and on. The moment your agent stops being a chatbot and starts being useful, it needs credentials, and you’ve inherited two hard questions. 1.Who is allowed to call your agent? 2.How does your agent prove itself to everything it calls? On AWS the machinery for both is Amazon Bedrock AgentCore, the managed platform for deploying and operating agents, and specifically AgentCore Identity, its auth layer. Those two questions have almost nothing to do with each other. Different components enforce them, and they fail in ways that look nothing alike. Blur them together and you end up debugging the wrong half of the system: an inbound authorizer that was fine all along, when the actual fault was a missing Secrets Manager grant on the outbound side. What the system does is spread across a lot of separate documentation pages, and some of what you need to know isn’t in them at all. That’s why this guide exists in the shape it does: one article, in the order you’d actually build things, with my own test results wherever the docs are silent. Every so often you’ll hit a short “test your understanding” box. If the questions in one are easy, skip ahead; if they aren’t, the section above them is the one to reread. The answers are all collected at the end. The model Every authentication question in AgentCore is one of two questions. Figure 1. Inbound vs. outbound. The two are enforced independently and meet only at user identity. Inbound controls who can invoke your agent. That caller is often a person in a chat app, but it’s just as often a system: a backend service, a cron job, another agent. The authorizer on the Runtime hosting your agent is what enforces it. So inbound is only an AgentCore question when your agent runs on a Runtime. A bare script you run yourself has no AgentCore authorizer in front of it. Whatever calls that script is outside AgentCore’s control completely. (Gateways have their own inbound authorizer, but that one decides who may call the Gateway. Your agent sees a Gateway as a downstream target, so it lands under outbound.) Outbound controls what your agent can reach and on whose behalf. AWS frames it as acting either on behalf of the user or on the agent’s own behalf, in their supported authentication patterns. Outbound has no dependency on the Runtime. The credential providers and the Token Vault (if these names are new to you, don’t worry, you’ll meet them in a minute) work from any process that has AWS credentials. These are not one system, however often they get treated as one. The credential providers and Token Vault exist only for outbound and have zero say in who’s allowed to call your agent. You can run IAM inbound with OAuth outbound, or JWT inbound with IAM outbound. Any combination is legal, because the two sides never consult each other. They’re enforced independently but they do touch at one point, and that point is user identity. If your agent only ever acts as itself, mix inbound and outbound freely. If it acts on behalf of a user, that user’s identity has to reach the outbound call somehow. There are three ways it can arrive: a verified inbound JWT, an unverified header, or a value you assert yourself when self-hosting. Which one you’re in decides a lot, and it gets a section of its own later. When something breaks, ask this before anything else: is the caller failing to get in, or is my agent failing to reach out? There’s a symptom table further down, but asking the question is most of the work. What AgentCore Identity actually is Both directions. On the inbound side it powers the authorizer that decides who may invoke your agent. On the outbound side it manages the credentials your agent uses to reach other systems. The inbound side only exists when your agent runs on an AgentCore Runtime, or when you put a Gateway in front of a target. The inbound authorizer is not a standalone Identity resource you create on its own. It’s configuration you attach to a Runtime or a Gateway, the authorizerConfiguration field on CreateAgentRuntime and CreateGateway. A self-hosted agent has no AgentCore authorizer at all. For that agent, AgentCore Identity is only the outbound half. The outbound pieces are standalone infrastructure that works wherever your code runs. There are three of them, and they differ in who provisions them: the directory is always automatic, credential providers are always yours to create, and workload identities are usually automatic but sometimes yours. The Agent Identity Directory, which you never create The Agent Identity Directory is a per-account registry of workload identities. A workload identity is the underlying identity of an agent or app. There’s exactly one directory per account and it’s created automatically with the first identity. You never call an API to get the directory itself. The identities inside it are a different story. When your agent runs on a Runtime, or when you create a Gateway, that resource gets a service-managed workload identity automatically, and most agents use only that one. Sometimes you create your own with CreateWorkloadIdentity instead, and not only when self-hosting. There are four cases where you’d create one yourself, but they need vocabulary I haven’t introduced yet, so the list is in the reference section. The one you’re most likely to hit has verified code further down. Credential providers, which are always yours to create Credential providers are reusable configs describing how to authenticate to an external service. Register one and AgentCore runs the flows and the refreshes for you. You get 24 built-in vendor integrations (Google, GitHub, Slack, Salesforce, Microsoft, Okta, Auth0, Cognito, Atlassian, LinkedIn and more), a CustomOauth2 escape hatch for any OAuth2 server, and an API-key provider for services that don’t speak OAuth. There’s also a separate payment provider type, CoinbaseCDP and StripePrivy, created through its own create-payment-credential-provider API. Credential providers are outbound only. They represent systems the agent reaches out to. They are not configuration for who may call your agent. If you want your agent to read a user’s Google Drive, you configure a credential provider. If you only want to use Google as an inbound IdP for your agent, you do not need one, you configure a JWT authorizer instead. The Token Vault, also provisioned for you The Token Vault is encrypted storage for the actual credentials. AWS says it “ensures credentials can only be accessed by the specific agent and user combination that originally obtained them,” with KMS encryption at rest and in transit. Tokens are scoped to an agent + user pair for user-delegated access, or to the agent alone for machine-to-machine. An example makes it concrete. Say you have an agent that builds PowerPoint decks and saves them to a user’s Google Drive. You create the Google credential provider. Bob asks the agent to save his deck. The agent runs the OAuth flow, and the access token Google returns lands in the Token Vault. Getting it back out, from inside the agent, is one API call. There are two of them and the credential type picks which: GetResourceOauth2Token for anything OAuth, so Bob’s Google token here, and equally a machine token or an exchanged one. GetResourceApiKey for a stored API key. Both take the name of the credential provider you’re reaching for, plus proof of who’s asking. That proof is the third of the three tokens in the next section, and it’s the piece that makes the Vault return Bob’s row rather than Alice’s. Two things wrap those calls in practice: SDK decorators that make the whole fetch invisible, or the raw calls when you want the control. Both are covered properly later, including the extra step 3LO needs for first-time consent. For now it’s enough to know the Vault has exactly two doors. Think of the Vault as an encrypted key-value store where the key is (agent’s workload identity + user id) and the value is the access token. When Alice asks for the same thing she gets her own row. The Vault itself is never something you stand up or configure. Every API action in this guide The surface is smaller than the documentation makes it look. Everything below appears somewhere in this guide, and it splits cleanly in two: control-plane calls in bedrock-agentcore-control that you make once when setting things up, and data-plane calls in bedrock-agentcore that run on every request. Skim it now for the shape and come back when you need a parameter. One thing to define first, because two of the calls below refer to it. A user-consent flow ends with the provider redirecting the browser back somewhere, and there are two such URLs, which the docs unhelpfully both call a “callback URL.” Call them (a), the AWS-hosted URL you register with Google or whoever the provider is, and (b), an endpoint in your own app that AgentCore redirects to afterwards. The section on first connects does them properly; for now, (a) is AWS’s and (b) is yours. Setup, on the control plane. Mostly one-time, mostly infrastructure-as-code. Call Why you’d make it Parameters that matter What the next call needs from it CreateWorkloadIdentity Register an agent in the Agent Identity Directory yourself, rather than letting a Runtime do it name, allowedResourceOauth2ReturnUrls The identity’s name, which becomes workloadName on every mint call UpdateWorkloadIdentity Register endpoint (b) after the fact, which on a Runtime is the only option, since the identity doesn’t exist until you deploy name, allowedResourceOauth2ReturnUrls Nothing, but 3LO won’t redirect to (b) until this is set ListWorkloadIdentities Find what got created for you, including anything the SDK decorator fabricated maxResults, nextToken The name of the service-managed identity, so you can update it CreateOauth2CredentialProvider Store an OAuth client for Google, Slack, your own IdP name, credentialProviderVendor, oauth2ProviderConfigInput (client id and secret) The provider name → resourceCredentialProviderName, and callbackUrl → endpoint (a), which you paste into the IdP CreateApiKeyCredentialProvider Store a static API key name, apiKey, or apiKeySecretSource + apiKeySecretConfig to point at a secret you own The provider name, plus apiKeySecretArn, the secret your role needs secretsmanager:GetSecretValue on CreateAgentRuntime · CreateGateway Where authorizerConfiguration lives, so this is where inbound auth is decided authorizerConfiguration, and on a Gateway authorizerType A service-managed workload identity, created for you and named after the runtime id Per request, on the data plane. Mint one token, spend it for another. Call Why you’d make it Parameters that matter What it returns GetWorkloadAccessToken Mint with no user in the picture, for an API key or a machine token workloadName workloadAccessToken, agent-only GetWorkloadAccessTokenForJWT Mint from a user’s inbound JWT workloadName, userToken workloadAccessToken, bound to that user GetWorkloadAccessTokenForUserId Mint from an opaque user id, which is the User-Id header path workloadName, userId workloadAccessToken, bound to that user GetResourceOauth2Token Spend it for any OAuth credential: 3LO, M2M, OBO resourceCredentialProviderName, workloadIdentityToken, oauth2Flow, scopes (required even when empty), resourceOauth2ReturnUrl (endpoint b), then sessionUri on the re-call. Also audiences, customState, forceAuthentication accessToken. On a first 3LO connect, authorizationUrl and sessionUri instead GetResourceApiKey Spend it for a stored API key resourceCredentialProviderName, workloadIdentityToken apiKey CompleteResourceTokenAuth Close the 3LO loop from endpoint (b), after checking the browser session sessionUri, userIdentifier (a userToken or a userId, and which one is not a free choice) Nothing useful. Its effect is to write the provider token into the Vault InvokeAgentRuntime Call the agent agentRuntimeArn, payload, runtimeSessionId, and runtimeUserId for the X-Amzn-Bedrock-AgentCore-Runtime-User-Id header Your agent’s response Read down the second table and you have the whole outbound flow. A mint call takes the workloadName from CreateWorkloadIdentity and gives you a workloadAccessToken. A spend call takes that token as workloadIdentityToken, plus the resourceCredentialProviderName from whichever provider you created, and gives you the credential your tool actually sends downstream. First-time 3LO is the one place the chain forks: the spend call hands back an authorizationUrl and a sessionUri rather than a token, and only after endpoint (b) has called CompleteResourceTokenAuth with that sessionUri does re-calling the spend produce an accessToken. Some names you’ll meet in IAM policies aren’t operations at all and have no reference page of their own. bedrock-agentcore:InvokeAgentRuntimeForUser is the permission for invoking with a User-Id header, and bedrock-agentcore:InvokeGateway is the one for reaching a Gateway. You grant them; you don’t call them. secretsmanager:GetSecretValue belongs to Secrets Manager rather than AgentCore, which is exactly why it’s so easy to miss. Three kinds of token There are three completely different tokens in an AgentCore flow. Two OAuth roles are worth naming before the list, because your agent plays both. A resource server holds something protected and has to validate a token before serving it. A client holds a token and presents it to the resource server. Which of the two your agent is depends on the call you’re looking at, and the OAuth primer works that through. Inbound JWT. The token that whatever invokes your agent (the OAuth client) has to present in order to invoke it, whether that’s a chat front end, a backend service, or another agent. The caller’s IdP issues it (Cognito, Auth0, Okta) and it identifies the caller, usually the end user sitting behind that application. Your agent is the resource server here, and its authorizer is what validates the token. There is no inbound JWT when inbound is IAM, because then the caller proves itself with a SigV4 signature instead. Provider access token. The token your agent has to present to an outbound system in order to reach it: Google, Slack, a partner API. Your agent is the client in this exchange, not the resource server, and this is the credential your tool actually puts on the downstream request. The external service issues it, and the Token Vault is what stores it, keyed to your agent and, when there is one, the user. Workload access token. The key your agent uses to get the provider access token out of the Vault. AWS issues it, it represents your agent bound to a user when there is one, and it authorizes AgentCore Identity API calls and nothing else. More on it below, and the full mechanics come later. Keeping them apart is what makes an error message readable: a rejected inbound JWT is an authorizer problem, a rejected provider token is a scope or audience problem at the downstream, and a failure to get a workload access token is almost always IAM. What the workload access token is for AgentCore will not hand you a provider access token unless you first present a workload access token proving which agent, plus which user, is asking. That’s how the Vault knows whose Google credential to return. It exists only to authorize your agent against AgentCore’s own services, the Token Vault and the credential providers. AWS is blunt about the boundary: it’s “exclusively for accessing AWS first-party AgentCore services and cannot be used for external services.” Using it takes two steps. First you mint one from whatever identity you have, with a GetWorkloadAccessToken* call. Then you spend it, passing it as the workloadIdentityToken argument to GetResourceOauth2Token or GetResourceApiKey, and AgentCore returns the provider access token out of the Vault. On a Runtime both steps are automatic. The platform mints the token and injects it into your request, the SDK decorator spends it, and your code never sees it. Self-hosted, you do both yourself. The full mechanics, including all three ways to mint one, come later. What to carry forward Inbound and outbound are separate systems. Inbound lives on the Runtime or the Gateway. Outbound lives in the Token Vault and works anywhere you have AWS credentials. They meet at user identity and nowhere else. You never provision the directory or the Vault. Credential providers you always create yourself. Workload identities sit in between: the Runtime or Gateway usually hands you one, but you’ll create your own when you need a token that a service-managed identity can’t mint. The three tokens are the inbound JWT, the provider access token and the workload access token. Test your understanding What’s the difference between inbound and outbound authorization in AgentCore Identity? What are AgentCore Identity’s core primitives and what’s the purpose of each one? What are the three kinds of token in AgentCore Identity and what is each one used for? Answers Where your agent runs What the Runtime does, and what you take over Start from a claim in the AWS docs: AgentCore Identity’s outbound features are not tied to the AgentCore Runtime at all. AWS is explicit that identity works “whether your agents run on AgentCore Runtime, self-hosted environments, or hybrid deployments” (key features). So if the credential machinery runs fine without a Runtime, it’s worth pinning down what the Runtime actually contributes. What the Runtime does for identity Three things, in order, on every invocation. It validates the caller and extracts an identity. The inbound authorizer checks the JWT and pulls iss and sub out of it, or under IAM inbound reads a header naming the user. It resolves your agent’s workload identity. Created for you when the runtime resource was created, named after the runtime id. It mints a workload access token binding those two together, and injects it into your request as a header. Then it stops. Credential providers, the Token Vault, the SDK’s credential decorators, the whole outbound half: none of that is Runtime machinery. It’s ordinary API calls against AgentCore Identity, and they behave the same whether the caller is a container on a Runtime or a script on your laptop. Everything you inherit when you self-host is on that list. What you take over when you self-host Concern On an AgentCore Runtime Self-hosted (local script, plain Lambda, EC2/ECS, any AWS-credentialed app) Workload (agent) identity One is created and service-managed for you at resource creation, named after the runtime id. You can create your own as well, and sometimes have to (next row but one). You create it with CreateWorkloadIdentity (API/CLI/SDK). If you use the SDK decorator and no workload access token is in its request context, it will create one for you and cache its name in a file next to your code, .agentcore.json. That behaviour has real hazards, below. Inbound identity extraction The authorizer validates the inbound JWT and takes iss + sub from it. Under IAM inbound it instead reads X-Amzn-Bedrock-AgentCore-Runtime-User-Id, an unverified header the caller sets to name the end user. No authorizer exists. You assert the user identity when you call GetWorkloadAccessTokenForJWT, passing a JWT, or GetWorkloadAccessTokenForUserId, passing an opaque string. Workload access token Minted and injected as a request header, but only when the Runtime has an identity to bind it to: JWT inbound, or IAM inbound plus the User-Id header. Under plain IAM SigV4 with no User-Id, nothing is injected. You call GetWorkloadAccessToken* yourself (or the SDK decorator does). Which identity you can mint a token against Not the service-managed one. The identity the Runtime created for itself is blocked from GetWorkloadAccessToken*, so the token can’t be extracted and replayed. A workload identity you created is not blocked, and minting against it works from inside a Runtime. Any workload identity you created. Nothing is blocked, because nothing is service-managed. Credential providers, Vault, decorators Work out of the box on top of the injected token. Fully supported, once you’ve done the manual identity and workload-token steps above. (Sources: obtain credentials, get workload access token, understanding workload identities, Google tutorial.) Most of that is what you’d expect: on a Runtime the platform does it, off a Runtime you do. The workload-access-token row is the one to stop on. It says the injection happens only under certain inbound configurations, which means a Runtime can hand your agent nothing at all. The docs don’t spell that out, so I tested it. What the Runtime actually injects The docs describe the JWT auto-injection path and stop there. So I deployed a Runtime and logged the incoming request headers under all three inbound configurations. JWT authorizer: the workload access token is present. IAM (SigV4) plus the X-Amzn-Bedrock-AgentCore-Runtime-User-Id header: present. And the raw User-Id header is not forwarded. The Runtime consumes it to mint the token, so your container gets the WorkloadAccessToken and nothing else, exactly like the JWT case. IAM (SigV4), no User-Id header: absent. The request arrives with host, content-type, content-length, baggage, x-amzn-bedrock-agentcore-runtime-session-id, x-amzn-requestid and x-amzn-trace-id, and nothing else. No workload access token under either name, so your agent has nothing to spend at the Vault. There’s a way out, further down. When a token is injected, it arrives under two header names carrying the same value, WorkloadAccessToken (the one the SDK reads) and X-Amzn-Bedrock-AgentCore-Runtime-Workload-AccessToken. Header lookups are case-insensitive but not hyphen-insensitive, so match these exact lowercased spellings: workloadaccesstoken and x-amzn-bedrock-agentcore-runtime-workload-accesstoken. That third case is not the Vault demanding a user. Agent-only workload access tokens exist and are useful, and an API key or a machine token needs no user identity whatsoever. It’s the Runtime’s auto-injection specifically that produces nothing when there’s nobody to bind to. Which leaves the practical question: what does your code do when it reaches for a token that was never injected? With no token, the decorator guesses When the decorator can’t find a workload access token, it doesn’t fail, and that’s the problem. The decorators in question are the two the AgentCore Python SDK ships for fetching outbound credentials: @requires_access_token for an OAuth token and @requires_api_key for a stored API key. You put one on an async function and name the credential provider you want. The decorator runs the whole fetch before your code starts, and your function body receives a ready-to-use credential as a keyword argument: from bedrock_agentcore.identity.auth import requires_api_key @requires_api_key(provider_name=\"my-weather-api\") async def call_weather_api(*, api_key: str): ... # api_key arrives already pulled from the Token Vault That’s the path the SDK is built around. The alternative is calling the boto3 APIs yourself, which skips everything described in this section, and that code is here. Everything the decorators do before your function body runs is in identity/auth.py. Before the decorator can fetch anything it needs a workload access token, and it looks for one in a request-scoped context object, BedrockAgentCoreContext (runtime/context.py). Exactly one thing populates that context automatically, and it isn’t the decorator. It’s BedrockAgentCoreApp (runtime/app.py), the SDK’s ready-made implementation of the Runtime’s HTTP contract: an ARM64 container on 0.0.0.0:8080 serving POST /invocations and GET /ping. Its /invocations handler reads the incoming WorkloadAccessToken header into the context before your handler runs. Use a different server and nothing does that for you, unless you write it yourself. Which gives three ways to arrive at the decorator with an empty context: A plain script or notebook. There’s no HTTP request, so there’s no header to read. Your own FastAPI or Flask server on a Runtime. The header may well arrive, and nothing puts it in the context, so the decorator can’t see it. An SDK-served Runtime invoked with no token to inject. The bare-SigV4 case from the tests above. With an empty context the decorator has to decide what to do, and the decision is where the guessing happens. It checks the DOCKER_CONTAINER environment variable: \"1\" means it refuses to guess and raises: “Workload access token has not been set. If invoking agent runtime via SIGV4 inbound auth, please specify the X-Amzn-Bedrock-AgentCore-Runtime-User-Id header and retry.” anything else means it assumes local development and fabricates an identity. Both branches are in identity/auth.py, in the helper the decorators run before your function body. What “fabricates an identity” actually does It creates a real AWS resource. The decorator calls CreateWorkloadIdentity, which creates a workload identity in your account: it shows up in aws bedrock-agentcore-control list-workload-identities, it needs the appropriate IAM permission to succeed, and it stays there until you delete it yourself. The decorator then invents a random user id and caches both values in .agentcore.json, next to your code. On later runs it reads that file first and reuses whatever it finds, creating a new identity only when the file isn’t there. All of it is _set_up_local_auth in identity/auth.py, short enough to read in a minute. The test for “am I running locally” is an empty context plus DOCKER_CONTAINER not being 1. Empty context here means no workload access token in BedrockAgentCoreContext, the request-scoped object the decorator looks in, which nothing fills automatically except BedrockAgentCoreApp. Two of the three empty-context cases above pass that test in production: a bring-your-own server on a Runtime, and an SDK-served Runtime under bare SigV4. Neither sets the variable. I confirmed it inside a bring-your-own-server container, where os.getenv(\"DOCKER_CONTAINER\") returns None, because the platform doesn’t set it. In production, whether the decorator succeeds in creating that workload identity comes down to the execution role’s permissions. If the role lacks bedrock-agentcore:CreateWorkloadIdentity, the call raises AccessDenied and you find out immediately. If the role allows it, the call succeeds, and your agent serves production traffic under an identity and a user id that nothing else in your account has ever heard of. The case that fires on a correctly configured Runtime Case two above is worth its own walkthrough, because nothing in it is misconfigured. I ran a bring-your-own FastAPI server on a JWT Runtime, with a tool decorated @requires_api_key. JWT inbound, so the platform did mint and inject a token. The header arrived. No code put it in the context. The decorator fabricated instead of using it, and tried to CreateWorkloadIdentity. It failed loudly only because that execution role lacked the permission. A broader role would have succeeded silently, against a fake identity, on a Runtime that was doing everything right. So with a bring-your-own server plus the decorator, pick one of three fixes: Populate the context yourself. Read the header, call BedrockAgentCoreContext.set_workload_access_token(...). (The SDK also ships a @requires_wat decorator that reads the token out of the context for you once something has put it there, in identity/auth.py.) Set DOCKER_CONTAINER=1 to force a loud failure instead of a silent fabrication. Skip the decorator and pass the header straight to the raw APIs. All of this guessing is decorator-only. The context lookup, the DOCKER_CONTAINER check and the fabrication all live in that one helper. Call the boto3 APIs directly and there’s nothing to detect, because you pass workloadIdentityToken and, when minting, the user’s JWT or id, explicitly. The SDK never guesses on that path. That covers what your code does when no token is injected. It does not yet answer how to get one. Getting a token when the platform won’t give you one Under bare SigV4 with no user, the Runtime injects no token. You also can’t mint one against the identity the Runtime created for itself, because that one is blocked: the call fails with WorkloadIdentity is linked to a service and cannot retrieve an access token by the caller. So nothing to spend, and nothing to mint with. A workload identity you created yourself isn’t blocked, though, and minting against one works from inside a Runtime. Create the identity, mint an agent-only workload access token against it, spend it at the Vault as normal. That’s the documented managed path for an agent that needs an API key or a machine token with no user anywhere in the picture. I tested it end to end for both an API key and an M2M token, and the code is below. For completeness, the other two ways out of that situation are to change the inbound call rather than the agent: have the caller send a User-Id header, or put a JWT authorizer on the Runtime. Both give the platform an identity to bind a token to, so injection starts working. The parts that matter The Runtime automates three steps and no more, which is the whole reason outbound is portable and inbound isn’t: you can adopt the credential machinery from a Lambda, a laptop or an ECS task today, and what you give up off-Runtime is the front door and the automatic token injection. Whether you get a token at all depends on your inbound configuration. JWT and IAM-plus-User-Id both inject one. Bare SigV4, the default, doesn’t. The part that catches people out is what happens next. With nothing in the decorator’s context it invents an identity rather than failing, and nothing about that branch checks where the code is running, so it fires in production too. A broad IAM role is what makes it silent instead of loud. When the platform gives you no token, the fix is a workload identity of your own to mint against, since the Runtime’s own identity can’t. Test your understanding What are the three things the Runtime does for you on every invocation, and which of them do you take over when you self-host? Under which inbound configurations does the Runtime inject a workload access token, and which configuration is the default? What does the SDK decorator do when no workload access token reaches it, and why can that happen in production? Answers Every one of those turned on which inbound configuration the Runtime has: what gets injected, whether the decorator fabricates, whether you need your own identity. So the front door is worth covering properly, and there are four options. Inbound Inbound: who may call your agent First, the self-hosted case, because it’s short. There is no AgentCore authorizer in that path at all. “Inbound auth” is whatever your own web server enforces, and the options below simply don’t apply. You can still use every outbound feature, as long as you assert user identity yourself through the two GetWorkloadAccessToken* calls. On a Runtime, four options. A Gateway carries the same kind of authorizer independently, but there it governs who may call the Gateway, which from your agent’s point of view is a downstream target. The options apply to both; just keep straight which resource you’re protecting. Inbound option Identifies the caller by Where Setup IAM SigV4 An AWS IAM principal Runtime (default) & Gateway None. Works like any AWS API; caller needs bedrock-agentcore:InvokeAgentRuntime / InvokeGateway IAM + User-Id header IAM principal plus X-Amzn-Bedrock-AgentCore-Runtime-User-Id Runtime Caller adds the header; needs InvokeAgentRuntimeForUser JWT bearer (OAuth) The token’s iss + sub claims Runtime & Gateway --authorizer-config with an OIDC discovery URL Offloaded (AUTHENTICATE_ONLY / NONE) Defers or skips the check Gateway only Authorizer config IAM SigV4 is the Runtime default and needs no configuration, which is worth pairing with the injection findings above: the default configuration is the one that injects nothing. NONE is for intentionally public gateways only. With JWT there are two different jobs that are easy to blur together. The token’s iss and sub claims build the caller’s identity, which is the thing outbound credentials later bind to. AWS’s token flow says the Runtime “extracts issuer and sub claims from the OAuth token representing user identity.” Separately, allowedClients, allowedAudience, and scopes are the authorization gate, validated against the token’s client_id, aud, and scope to decide whether the call is allowed in at all. “JWT bearer” does not imply a human A JWT authorizer validates a token. It doesn’t care whether a person is behind that token, and sub doesn’t have to name one. Whose identity ends up in sub depends on how the caller is acting, not on what the caller is. The caller here is whatever invokes your agent: a backend service, a cron job, a chat front end, another agent. If the caller acts on its own behalf, using a client-credentials (M2M) grant, sub identifies the calling application itself and no user appears in the token at all. Your authorizer is validating that application’s own machine token. Agent-to-agent calls are one instance of this, and a nightly batch job hitting your agent is another. If the caller acts on behalf of a user, sub carries the user’s identity instead. How the caller came to hold a token it could send you depends on what it is. A chat front end simply presents the token the user received when they signed in there. Another agent is doing outbound work of its own to produce it: forwarding a user token it already holds (passthrough), which arrives unchanged, or exchanging it for one minted for your Runtime’s audience (OBO), which arrives naming the calling agent as the acting party alongside the user. Both of those are covered later, from the caller’s side. It’s the same JWT authorizer on the receiving Runtime in every case. Only the sub differs. Two edge cases the docs leave implicit. First, a token missing iss or sub can’t be resolved to an issuer or bound to a user, so treat both claims as mandatory in practice. AWS documents that they’re used to identify the caller but not what happens when they’re absent. Second, the X-Amzn-Bedrock-AgentCore-Runtime-User-Id header belongs to the IAM inbound path. It rides on the InvokeAgentRuntimeForUser IAM action and the GetWorkloadAccessTokenForUserId flow. On a JWT-inbound Runtime the caller identity comes from the verified token, not a header, and since a Runtime runs only one inbound type at a time, sending both isn’t a supported combination. The docs don’t define a precedence for it. That last clause has a consequence people run into as soon as they have two kinds of caller. When one agent needs two authorizers An internal team wants to call the agent with IAM. An external app needs to call it with a JWT. Or you have users in two different IdPs. One authorizer config does one thing at a time. AWS: “An AgentCore Runtime can support either IAM SigV4 or JWT Bearer Token based inbound auth, but not both simultaneously” (Runtime auth). And a JWT authorizer points at exactly one IdP, one discoveryUrl. So if the same agent has to accept both, you front it with more than one authorizer. Two clean ways to do that, both documented. Multiple versions of one Runtime. authorizerConfiguration is set at create or update time and frozen into each immutable version. Every update mints a new version, and an endpoint is just a named pointer to a version. AWS says it outright: “You can always create different versions of your AgentCore Runtime and configure them for different inbound authorization types.” (Runtime auth, versioning) One version behind a JWT endpoint, another behind an IAM endpoint. Multiple Runtime instances from the same image. A Runtime is created from a container image in ECR. Nothing stops you standing up two Runtimes pointing at the same image URI, each with its own authorizerConfiguration. One IAM, one JWT, or two JWT authorizers for two different IdPs. Same code, same container, two independently addressable runtimes with different front doors. Reach for versions when the variants are two faces of one deployment you manage together. Reach for separate runtimes when you want them deployed, scaled, and secured independently, like an internal IAM-only runtime and an external JWT-only one. You don’t need to split for multiple clients or audiences. A single JWT authorizer already trusts multiple clients and audiences, since allowedClients and allowedAudience are both lists, as long as they share one IdP. “Many apps, one Auth0 tenant” is a single authorizer. What you do need more than one authorizer for is multiple IdPs. One authorizer, one discoveryUrl, one issuer. Okta plus Cognito plus Google means three authorizers, via either approach above. Test your understanding What are the four inbound options, and what does a JWT authorizer check beyond who the caller is? What are your options when one agent has to accept two different kinds of caller? Answers Outbound Outbound, starting with a fast OAuth primer The outbound patterns lean on three OAuth flows with intimidating names: authorization code grant, client credentials, token exchange. If your background is ML rather than web auth, they can feel like folklore passed between engineers. Skip to the next section if OAuth is already second nature. Everything below reappears, applied, in the patterns that follow. The cast Every OAuth flow is a story with the same four characters, plus the token that changes hands. The resource owner is the human who owns the data. You, when it’s your Google Drive. The client is the application that wants to use the data. The authorization server issues tokens after checking identity and, sometimes, consent; this is the IdP, so Google, Cognito, Auth0, Okta. The resource server is the API that holds the data and accepts the token, like Google Drive’s API or your internal service. The access token is the short-lived key the client presents to the resource server, often paired with a longer-lived refresh token used to get new access tokens without bothering the user again. And audience (aud) is who a token was minted for. A token issued for service A’s audience gets rejected by service B. The roles belong to the exchange, not to the component Before mapping any of this onto your architecture: these are roles in one particular exchange, not labels you attach to a box on a diagram, and the same component plays different roles depending on which resource is being accessed and who is asking for it. Your agent is the clearest example. When it reaches into a user’s Google Drive, the agent is the client. Google is both the authorization server and the resource server, the user is the resource owner, and your agent is the application holding a token and presenting it to someone else’s API. Now change the resource being accessed. Say it’s the conversation between the user and the agent: the message history, the agent’s tools, whatever that user’s session holds. Google is nowhere in this picture. The user is sitting in a chat front end, which gets a token from your own IdP and calls your Runtime with it. In that exchange the front end is the client, your IdP is the authorization server, the user is still the resource owner, and your agent is the resource server: the thing that holds the protected resource and has to validate a token before serving it. It’s the same agent and the same user in both cases. What changes the role is which resource is being reached for. Which is the inbound-and-outbound split restated in OAuth vocabulary: Inbound is your agent acting as a resource server. Something else holds a token and presents it to you, and the Runtime’s authorizer is doing the token validation any resource server has to do. Outbound is your agent acting as a client. You hold a token, or go and get one, and present it to somebody else. Where AgentCore Identity sits You rarely write client code. AgentCore Identity plays the client’s side of these flows for you. It holds your client secret inside the credential provider, performs the redirects and token calls, refreshes expiring tokens, and stores the resulting access token in the Token Vault keyed to your agent, and to the user when there is one. Your job is to declare which flow and which provider. The decorator or API call triggers it. So the three flows below are three things you declare, not three things you implement. Flow 1: authorization code grant, or “3LO” Three-legged means three parties: the user, the client, and the authorization server. Use it when the client acts on behalf of a user and needs that user’s consent, which is the familiar “Sign in with Google, allow this app to access your Drive?” screen. Figure 2. The authorization code grant (3LO), step by step. Why the two-step dance of getting a code and then exchanging it for a token? So the actual token never travels through the browser’s URL bar. Only a single-use code does, redeemed over a secure back channel. AgentCore is the client here. @requires_access_token(auth_flow=\"USER_FEDERATION\") runs steps 1 through 5 for you, stores the token in the Vault, and injects the step-6 token into your function. Each user consents separately and ends up with their own token. Flow 2: client credentials, or “2LO” / “M2M” Two-legged means two parties, the client and the authorization server. No user, no browser, no consent screen. The client authenticates as itself with its own client id and secret and gets a token representing the application. This is the flow for service-to-service and agent-to-agent calls. Client sends its client_id and client_secret to the token endpoint, asking for scopes. Authorization server returns an access token representing the client itself, with no user identity inside. Client calls the resource server with that token. @requires_access_token(auth_flow=\"M2M\") does both of those for you and vaults the token agent-only. There’s no consent and nothing to bind to a user. Flow 3: token exchange, or “OBO” (RFC 8693) Use it when the client already holds a token for the user but the target won’t accept it, usually because the target wants a token for its own audience. Instead of re-prompting the user, the client trades the token it has for a new one. Client presents the token it holds, the subject token, optionally alongside its own actor token, with a token-exchange grant type. Authorization server validates them and returns a new access token minted for the requested audience, still carrying the user’s identity and often the agent’s as the acting party. Client calls the downstream resource server with the new token, which now passes the audience check. In AgentCore the credential provider is configured with an onBehalfOfTokenExchangeConfig and you request it with oauth2Flow=ON_BEHALF_OF_TOKEN_EXCHANGE. Two things that aren’t OAuth at all JWT passthrough just forwards a token you already have, with no round-trip to an authorization server. IAM SigV4 is AWS request signing. Both are outbound mechanisms here, neither is an OAuth grant. One thing the “pick a mechanism” framing hides: an agent that talks to several systems ends up with several mechanisms side by side. A passthrough tool here, an M2M-authenticated Gateway client there, an IAM-signed Gateway via mcp-proxy-for-aws, an OBO call to a tiered API, a 3LO tool for the user’s data. You’re not choosing one for the agent, you’re choosing one per connection, and the wiring is mechanical once you’ve picked. Those three flows are the ones where AgentCore acts as your OAuth client. The comparison table in the reference section lines them up against each other, with the argument that triggers each one. With the cast and the flows in hand, the rest is mostly picking which one the target forces on you. The target picks the mechanism Your agent is the client. The external system it calls already has an authentication method of its own, and that system is the lock. AgentCore only cuts keys, and you don’t get to file down the lock to fit the key you’d prefer. So the first question is never “which mechanism do I like?” It’s “what does this target expect?” A Gateway configured for IAM inbound accepts only SigV4. Google’s Drive API accepts only a user-delegated OAuth token with the right scopes. A partner API that validates tokens for its audience rejects one minted for any other. An API-key service wants an API key and nothing else. Answer the target question and your options usually collapse to one. There are four answers to “what does the target expect,” and they organise everything that follows: Nothing. The target is protected by the network, not by auth. AgentCore Identity doesn’t help. A static API key. A user’s access token. The call must act as a specific user. A machine (M2M) token. The call acts as the agent itself. The first two involve no identity whatsoever: no user, no agent, no token negotiation, nothing to consent to. That’s why none of the OAuth vocabulary above applies to either of them. Answers three and four are where the flows from the primer show up, and they share a setup shape that’s identical every time: configure the external IdP or OAuth server first, registering an app and getting client credentials. Then create the AgentCore credential provider. Then register the provider’s returned callback URL back on the IdP. (Walkthroughs: Google, Cognito.) Easiest first. Case 1: the target wants nothing Some downstream systems have no authentication at all. An internal service reachable only inside a VPC. A database open to a security group. A legacy endpoint fronted by nothing but a private subnet. The network boundary is the auth. AgentCore Identity has nothing to offer here. It’s a networking problem, solved with networking primitives: VPC configuration, security groups, PrivateLink, VPC endpoints, and the egress settings of wherever your agent runs. On a Runtime that means the Runtime’s networking configuration reaching the target’s private network. Self-hosted, it’s your own host’s network placement. Case 2: the target wants an API key Plenty of services authenticate with a single long-lived API key. Many weather, search, and data APIs, plus a lot of internal tooling. AgentCore handles these with an API-key credential provider, a sibling of the OAuth credential provider. Two steps: store the key once, pull it at runtime. Step 1: create the provider Pass the key inline, from the CLI or the SDK. # Control-plane API. Pass the key inline (simplest) aws bedrock-agentcore-control create-api-key-credential-provider \\ --name \"your-service-name\" --api-key \"your-api-key\" --region us-east-1 # SDK, equivalent from bedrock_agentcore.services.identity import IdentityClient identity = IdentityClient(\"us-east-1\") identity.create_api_key_credential_provider({\"name\": \"your-service-name\", \"apiKey\": \"your-api-key\"}) Either one returns the provider ARN plus the ARN of a Secrets Manager secret that AgentCore created to hold the key. That second ARN is worth reading closely, because it tells you where the key actually lives, and it raises a question this section comes back to. { \"name\": \"your-service-name\", \"credentialProviderArn\": \"arn:aws:bedrock-agentcore:us-east-1:<acct>:token-vault/default/apikeycredentialprovider/your-service-name\", \"apiKeySecretArn\": { \"secretArn\": \"arn:aws:secretsmanager:us-east-1:<acct>:secret:bedrock-agentcore-identity!default/apikey/your-service-name-…\" }, \"apiKeySecretSource\": \"MANAGED\" } \"MANAGED\" means AgentCore created and owns that secret. If you’d rather point at a secret you already manage, swap --api-key \"…\" for --api-key-secret-source EXTERNAL --api-key-secret-config secretId=<secret-arn>,jsonKey=<field>, and apiKeySecretSource reads EXTERNAL. Source: Credential providers, creating an API key credential provider. Response shape verified against a live create-api-key-credential-provider call. Step 2: use it at runtime The easy path is the @requires_api_key decorator, which pulls the key from the Vault and injects it the same way @requires_access_token injects an OAuth token. from bedrock_agentcore.identity.auth import requires_api_key @requires_api_key(provider_name=\"your-service-name\") async def call_weather_api(*, api_key: str): # api_key is injected from the Token Vault. No user, no agent, no flow ... Source: adapted from Obtain an API key. Under the hood it’s the same two-hop machinery as every other outbound call, mint a workload access token then spend it, except the spend call is GetResourceApiKey instead of GetResourceOauth2Token and there’s no consent branch. The key is just sitting there. Without the decorator you make both hops yourself, and the first one has a branch in it: the workload access token may already be sitting in your request headers. If the Runtime injected one, read it and spend it. If it didn’t, mint one against a workload identity you created yourself. Off a Runtime there are no request headers at all, so the branch collapses and you always mint. That decision works the same way for every credential type, and the rule per credential type is spelled out later, but here is the whole handler: import os import boto3 from fastapi import FastAPI, Request # Data-plane client. This is the one that mints and spends workload access tokens. client = boto3.client(\"bedrock-agentcore\", region_name=\"us-east-1\") app = FastAPI() PROVIDER_NAME = \"your-service-name\" # the credential provider from step 1 # A workload identity YOU created, for the case where nothing is injected. Once: # aws bedrock-agentcore-control create-workload-identity --name my-workload STANDALONE_WI = os.getenv(\"STANDALONE_WORKLOAD_IDENTITY_NAME\") # The Runtime sends the same value under both names. Lookups are case-insensitive, # but they are not hyphen-insensitive, so match these exact spellings. WAT_HEADERS = (\"workloadaccesstoken\", \"x-amzn-bedrock-agentcore-runtime-workload-accesstoken\") def read_injected_wat(headers) -> str | None: return next((headers[n] for n in WAT_HEADERS if headers.get(n)), None) @app.post(\"/invocations\") async def invocations(request: Request): # HOP 1a: already injected? (JWT inbound, or IAM + User-Id.) Use it as-is. wat = read_injected_wat(request.headers) # HOP 1b: nothing injected (bare IAM SigV4, no User-Id). Mint an agent-only # token against YOUR identity. The Runtime's own identity is blocked from this. if wat is None: wat = client.get_workload_access_token( workloadName=STANDALONE_WI, )[\"workloadAccessToken\"] # HOP 2: spend whichever token you ended up with. api_key = client.get_resource_api_key( resourceCredentialProviderName=PROVIDER_NAME, workloadIdentityToken=wat, )[\"apiKey\"] ... Nothing about identity is negotiated here. There’s no consent step and no refresh flow, and the user-versus-agent question doesn’t arise at all. What the Vault gives you is encrypted storage and scoping by workload identity. “Why not just use Secrets Manager directly?” As the create response showed, AgentCore puts the key in Secrets Manager for you as a managed secret. What the provider adds is consistency. The secret sits behind the same Token Vault, is scoped by the same workload-identity and execution-role machinery, and is injected by the same decorator as your OAuth credentials. One mental model and one IAM story for every outbound secret instead of hand-rolling Secrets Manager access per service. If you have exactly one API key and no OAuth anywhere, using Secrets Manager directly is defensible. Once you have both, the uniformity is worth it. That argument rests entirely on the phrase “one IAM story”. That story has two permissions in it, and a locked-down role has neither. Who’s actually allowed to read it: two permissions, not one Reading a credential out of the Vault is gated by ordinary IAM on whoever is calling: the Runtime’s execution role, or your local profile when you’re testing. It takes two permissions rather than one, and the second belongs to a different service entirely. The first is bedrock-agentcore:GetResourceApiKey, which lets you call the retrieval API at all. Without it: AccessDeniedException: ... not authorized to perform: bedrock-agentcore:GetResourceApiKey on resource: ...:token-vault/default/apikeycredentialprovider/<name> The second is secretsmanager:GetSecretValue, because the key physically lives in a Secrets Manager secret, and GetResourceApiKey reads that secret as your role rather than as a service principal. With the first permission in place but not this one: AccessDeniedException: Access denied when retrieving secret 'arn:...:secret:bedrock-agentcore-identity!default/apikey/<name>-...': ... not authorized to perform: secretsmanager:GetSecretValue Here is the least-privilege version, from AWS’s execution-role reference: { \"Version\": \"2012-10-17\", \"Statement\": [ { \"Sid\": \"GetApiKey\", \"Effect\": \"Allow\", \"Action\": \"bedrock-agentcore:GetResourceApiKey\", \"Resource\": [ \"arn:aws:bedrock-agentcore:<region>:<acct>:token-vault/default\", \"arn:aws:bedrock-agentcore:<region>:<acct>:workload-identity-directory/default\", \"arn:aws:bedrock-agentcore:<region>:<acct>:token-vault/default/apikeycredentialprovider/<name>\" ] }, { \"Sid\": \"ReadBackingSecret\", \"Effect\": \"Allow\", \"Action\": \"secretsmanager:GetSecretValue\", \"Resource\": \"arn:aws:secretsmanager:<region>:<acct>:secret:bedrock-agentcore-identity!default/apikey/<name>-*\" } ] } The trailing -* on the secret ARN matches the random suffix Secrets Manager appends to the name. The provider segment is worth a second look too: it’s apikeycredentialprovider/<name>, not the api-key/<name> that the scope-credential doc writes. The error message above, the create response, and the execution-role reference all use the long form. Get it wrong and the policy silently fails to match. If you don’t need per-provider isolation yet, one broader pair covers everything in the default vault, and I verified it works: GetResourceApiKey and GetResourceOauth2Token on token-vault/default/*, plus secretsmanager:GetSecretValue on secret:bedrock-agentcore-identity!default/*. None of this is specific to API keys, by the way. That’s just where you meet it first. GetResourceOauth2Token needs the same pair, on …/oauth2/<name>-* instead, and so does CompleteResourceTokenAuth when your callback endpoint runs it. Assume anything that pulls a credential out of the Vault needs both permissions. Nothing binds an agent to a provider by default Those policies scope by provider ARN, which makes it look as though AgentCore tracks which provider a given agent is entitled to. It doesn’t. Any workload identity in your account can fetch any credential provider in that account, so long as the caller’s IAM allows it. AWS says so outright: the service “does not enforce additional binding between workload identities and credential providers in the same account.” So the Resource blocks above aren’t tightening some restriction that already exists. They are the restriction, and without them a broad grant reads every provider you have. If you want one agent limited to one provider, you write that yourself: separate workload identities, separate execution roles, and Resource scoped to specific provider ARNs. An explicit Deny on a provider ARN is the stronger version, since Deny always beats Allow. (Scope credential provider access) That also answers a question the API-key case raises: what is the workload identity even doing here? With a 3LO token it picks which row comes back, because the Vault keys on (identity + user). An API key is stored once per provider, so there’s one row and nothing to pick. The call still won’t run without a workloadIdentityToken, but that token isn’t what narrows access here. Your execution role is: it’s the IAM principal, and the Resource blocks it’s scoped with name providers, not identities. In the API-key case the workload identity is a required parameter, not an access boundary. Before moving on Ask what the target expects before anything else, because that one question does most of your architecture for you: nothing, an API key, a user’s token, or a machine token. Where the answer is “nothing,” Identity has no part to play at all and you’re reaching for VPCs and security groups instead. API keys are the easy case with a hard IAM story. The secretsmanager:GetSecretValue half stays invisible until a least-privilege role hits production, and the provider ARN segment is apikeycredentialprovider/<name>. Test your understanding What are the four things a downstream target can expect, and which of them need no identity at all? When is your agent the OAuth client and when is it the resource server? Which two IAM permissions does reading a credential out of the Token Vault require? What binds a given agent to a given credential provider? Answers Acting as a user Case 3: the target wants a token that acts as a specific user Reading someone’s Google Drive. Posting to their Slack. Hitting an internal API as them rather than as your service. The user’s identity has to reach the outbound call somehow. On a Runtime that means it arrived inbound, either as a verified JWT or via the User-Id header. Self-hosted, you assert it yourself. One distinction decides most of this: do you own the target? Sometimes the team that owns the agent also owns the downstream system, like an internal API behind your own IdP. Then you have latitude, because you control both ends: you can accept the user’s existing token, or configure a token exchange. Sometimes you don’t own it, as with Google Drive, Slack or a partner API. Then the target’s rules are fixed and you usually have to originate a fresh token through their OAuth flow. Given a user identity, there are three mechanisms, and that ownership question is most of what picks between them. Figure 3. Three ways to act as a user, as a decision tree. Originate is 3LO. Forward is passthrough. Exchange is OBO. Session binding takes up most of the 3LO material below. It turns a half-hour demo into a half-day of work, it’s the reason a 3LO flow hangs forever with no error, and it exists to stop a real account-takeover attack. It’s also the one thing you can’t pick up by copying AWS’s sample callback server, which takes the user’s identity from a value you POST before the flow rather than from the browser that just consented. That’s fine for the single-user dev harness it is, and it’s the whole vulnerability if you carry the pattern into a multi-user app. Why, in detail, once the mechanism is on the table. Originating a fresh token with 3LO Use this when you don’t hold a usable token for the target, which is almost always because you don’t own the target. To reach a user’s Google Drive, their Slack, their calendar, you have to send them through Google’s or Slack’s own consent screen. Different users, different tokens, different data. No way around it. This is the OAuth authorization-code flow and auth_flow=\"USER_FEDERATION\" is its name in AgentCore. What this pattern quietly assumes 3LO is interactive. A real human has to open a browser and click “Allow.” That part is non-negotiable, because only a person signed in at Google can approve access to their own Google data. What is negotiable is what kind of application drives that browser. The walkthrough below assumes one shape: a human user, at a browser, using a web app you build and control, which talks to your agent. A CLI works too. A CLI opens the user’s browser and catches the post-consent redirect on a loopback address, which is exactly what aws sso login and gh auth login do, and what the legacy agentcore starter toolkit does locally. Loopback return URLs are accepted by AgentCore, which I tested. The case that genuinely doesn’t fit is a fully headless one: a backend service or a scheduled job with no human present at the moment the credential is needed. Nobody is there to click, so you can’t run first-time consent inline. Pre-authorize instead, having the user consent once up front so a refreshable token is waiting in the Vault, after which the agent reads the cached token and never needs a browser again. The cast 3LO has more moving parts than the other patterns, so they’re worth naming once. Who What they are The user (+ their browser) The person whose Google data you want to reach. Your app The web front end the user logs into and clicks around in; it talks to your agent. Your agent Your code, running on a Runtime or self-hosted. AgentCore Identity AWS’s broker. It runs the OAuth dance and stores the result in the Token Vault. The provider Google, Slack, whoever owns the data and shows the consent screen. The happy path Once a user is already connected, the entire agent side is one decorated function. @requires_access_token is a helper from the AgentCore Python SDK: it runs the auth flow, pulls the resulting credential from the Token Vault, and passes it into your function as the access_token keyword argument. from bedrock_agentcore.identity.auth import requires_access_token @requires_access_token( provider_name=\"google-provider\", scopes=[\"https://www.googleapis.com/auth/drive.metadata.readonly\"], auth_flow=\"USER_FEDERATION\", # 3-legged OAuth (authorization code) on_auth_url=lambda url: print(\"Visit to authorize:\", url), force_authentication=False, # cache the token after first consent callback_url=\"https://your-app.example.com/callback\", # YOUR session-binding endpoint (see below) ) async def access_user_drive(*, access_token: str): # access_token is injected, scoped to THIS user ... Source: adapted from the Google Drive 3LO tutorial. That’s it. access_token arrives already scoped to the current user, so you build a Google client and go. callback_url only matters the first time a user connects, when no token exists yet. That first connect is where all the complexity lives. The first time a user connects Your agent asks AgentCore for the user’s Google token. There isn’t one yet, so AgentCore hands back a consent URL instead of a token. You send the user’s browser to it. They sign in to Google and click Allow. Google sends the browser back through a short redirect chain, and AgentCore stores the resulting token in the Token Vault. Your agent, which has been waiting this whole time, receives the token and calls Google. Two different URLs show up in steps 3 and 4, and the docs call both of them a “callback URL.” Name them apart and the rest falls into place. (a) The IdP redirect URL (b) The session-binding endpoint Who hosts it AWS/AgentCore. You don’t build or deploy anything You (or the CLI, locally) What it looks like https://bedrock-agentcore.<region>.amazonaws.com/identities/oauth2/callback/… https://your-app.example.com/callback How you get it Auto-generated. It’s the callbackUrl field in the create-oauth2-credential-provider response You choose it, and the user’s browser has to be able to reach it. AWS documents it as a public HTTPS endpoint, though loopback is accepted in practice Do you register it at Google? Yes, and it’s the only URL Google ever needs. Paste it into Google’s “authorized redirect URIs” No. Google never sees (b). You register it with AgentCore, on the agent’s workload identity, and pass it as the decorator’s callback_url Two different registrations in two different places. That’s the whole confusion. (a) is registered at Google. (b) is registered at AgentCore. They are never the same URL and you never give (b) to Google. So the auto-generated URL you get back from creating the credential provider is (a). You host nothing, you just copy it into Google’s redirect-URI list. (provider callbackUrl) But then how does (b) ever get called, if Google doesn’t know about it? Because the post-consent redirect is a two-hop chain, and Google only needs to know the first hop. Figure 4. The post-consent redirect is a two-hop chain: (a) is registered at Google, (b) is registered with AgentCore, and Google never sees (b). Google redirects the browser to (a), the AgentCore endpoint it was told about. AgentCore takes the authorization code, then redirects the browser onward to (b). It knows where (b) is because you registered (b) with AgentCore, on the workload identity. Not because Google did. So who builds (b)? In production you host (b) yourself no matter where the agent runs, and AgentCore does not provide it. Locally you don’t have to: the legacy agentcore starter toolkit hosts it for you, or you run AWS’s sample callback server. The details, and which tool actually does that, plus the order everything has to be created in, are a couple of sections down. What matters for now is that (b) is code you own, and the next section is why. Session binding Session binding is a security check you can’t skip, and it’s the reason endpoint (b) has to be yours rather than something AWS hosts for you. What goes wrong without it Think of the authorization URL as a coupon that says “file the token this produces in this agent + user slot.” Concretely it’s the authorizationUrl that GetResourceOauth2Token hands back instead of a token on a first connect. AgentCore assembles it rather than hosting it: the client id and scopes come from your credential provider, the redirect points at the AWS-hosted (a) endpoint, and the page the user actually lands on is Google’s. Alongside it comes a sessionUri, and that’s where the binding really lives. The URL is just what carries it to a browser. AgentCore knows who the coupon is for because you told it. The workloadIdentityToken you spent on that call is a workload access token, and it encodes workload identity plus user. AgentCore reads that pair off it and ties the new session to it, and from that point on the pair is “the originating user” that CompleteResourceTokenAuth will later insist you match. Nothing about the user is inferred from the browser, then or ever, which is the root of everything below. Mallory kicks off a 3LO flow as himself, gets the authorization URL, and sends it to Alice: “please authorize our assistant.” Alice opens it, signs in to her Google, and clicks Allow. The token AgentCore harvests is Alice’s Google token. But the flow was started by Mallory, so without session binding it gets filed under Mallory’s agent + user slot. Mallory’s agent can now read Alice’s Drive. Nothing on Alice’s consent screen looked wrong. She really was authorizing access to her own account. She just had no idea the grant was being bound to someone else’s session. This is the OAuth cousin of session fixation, and it’s why a coupon can’t be allowed to self-redeem. Something has to confirm that the person clicking Allow is the same person the coupon was issued to. How the check works Session binding is that confirmation. When your agent starts the flow it’s acting for a specific user, the identity (inbound JWT or user_id) that minted its workload access token. AgentCore ties that to a unique session URI. After consent, AgentCore redirects the browser to (b), carrying the session URI and information identifying the originating user. Endpoint (b) is a route in your own web app, so it already knows who is currently logged in, from the live browser session. That means the session cookie your app set when this person logged in. (A session cookie is the small token a website drops in your browser at login so it recognizes you on later requests. If you’ve never built a web app, that’s the one piece of background to take on faith.) The docs are explicit that this identity must come from the active browser session, not a shared or remote cache. Your code compares the two. Is the person finishing consent in this browser the same user the flow was started for? Only if they match do you call CompleteResourceTokenAuth(sessionUri, userIdentifier), where userIdentifier is that same original identity, bound to the session URI. Back to the attack. Alice’s browser is logged into your app as Alice, but the flow’s originating user is Mallory, so step 4’s comparison fails, you call nothing, and Alice’s token never lands in Mallory’s slot. More generally, a forwarded URL opened in someone else’s browser carries a different app session, or none at all, so step 4 fails and nothing is released. And until CompleteResourceTokenAuth lands, AgentCore holds the token back and the pending token call just hangs. That’s the silent stall, and now you know what it means. Who enforces what It’s easy to lose track of which half is yours, so here it is exactly. CompleteResourceTokenAuth rejects a userIdentifier that doesn’t match the session’s originating user. I tested it; the enforcement is real and it is server-side. What AWS cannot do is judge whether the identifier you handed it has anything to do with the person in the browser. That’s the whole game, and it turns on where your callback gets the identifier from, not on the comparison you write around it. Derive it from the live browser session and the API’s check does the work for you. Alice’s browser carries her cookie to (b), you pass Alice, the session originated with Mallory, the identifiers disagree, and AWS refuses. Alice’s token never reaches Mallory’s slot. Derive it from your own records instead and you’ve disarmed the check. Look the session URI up in a pending-flow ledger, find started_by = mallory, pass that, and you have handed the API back the very value it’s comparing against. It matches by construction. The API is satisfied, Alice’s Google token lands in Mallory’s slot, and nothing anywhere logged a problem. That is precisely what AWS’s sample callback server does, which is why it isn’t a security template. It’s worth seeing, because it doesn’t look like a bug. Here is the same callback as the recipe below, written by someone who read the constraint and took it at face value: # THE BROKEN CALLBACK. Reads sensibly, passes every check AWS makes. @app.get(\"/callback\") def oauth_callback(request): session_uri = request.query_params[\"session_id\"] # \"The API demands the identity that STARTED this flow, not whoever's in the # browser. I wrote that down when I kicked it off, so I'll read it back.\" # pending_auth: a short-TTL store of your own, written when the flow began. started_by = pending_auth.get(session_uri) client.complete_resource_token_auth( sessionUri=session_uri, userIdentifier={\"userId\": started_by}, # <-- sourced from YOUR records ) return \"Connected.\" The reasoning in that comment is correct. You really must complete with the originating identity, and reading it back out of your own ledger really does satisfy that. The requirement is met. The check is dead. Walk Alice through it. Mallory is the one who started the flow, so when his agent made the GetResourceOauth2Token call that produced this session URI, it recorded session_uri → \"mallory\". Alice’s browser arrives at /callback carrying that session URI and, on the very same request, Alice’s cookie for your app. The handler reads the session URI off the query string, then reads \"mallory\" straight back out of that store. AWS compares \"mallory\" against the originator, \"mallory\", and agrees. Alice’s Google token is vaulted under Mallory. Her cookie sat on that request the whole time and no line of code ever looked at it. Now compare it to the working version below. It differs by one if and one variable. That difference is invisible in normal use. When the person consenting is the person who started the flow, current.id and started_by are the same string, so both callbacks send AWS exactly the same request and both work. The broken one only behaves differently once two different people are involved. So it passes code review, and it passes a test run where you are the only user, and it fails the first time someone actually attacks it. So the security boundary is the sourcing. Worth being concrete about how (b) can source it at all, because it isn’t obvious: the last hop is a redirect, not a server-to-server call from Google. It’s Alice’s browser that navigates to https://your-app.example.com/callback?session_id=…. An ordinary request to your own domain, so the browser attaches your app’s cookies and the handler reads its own session. The identity never comes from Google. It comes from the fact that the browser making the request is the browser you logged in earlier. That’s why (b) has to be a route in your app rather than something AWS hosts, and why the docs specify the live browser session rather than a lookup. Write the explicit current == started_by comparison anyway. Not because AWS skips it, but because it fails fast with a clean 403 instead of an opaque AccessDenied from deep inside the call, and because it forces you to decide what happens when there is no app session in that browser. The tempting answer there is to fall back to the ledger, and the fallback is the vulnerability. What about a CLI, where there are no cookies? Some of it doesn’t change. 3LO’s consent is always a browser step, since only a human in a browser can approve at Google, and something still has to catch the post-consent redirect and call CompleteResourceTokenAuth. What changes is that the cookie-based check in the recipe is a web-app construct, and a CLI has no cookies. But a CLI is single-user, the person at the terminal, so the multi-user hijack that session binding defends against largely evaporates. “Current equals originator” is trivially true. The CLI equivalent is a loopback server plus a state nonce, exactly how aws sso login and gh auth login work. The CLI generates a random state, opens the auth URL, starts a throwaway server on http://localhost:<port>, checks state on the redirect as CSRF protection (the stand-in for the cookie check), then calls CompleteResourceTokenAuth. AgentCore accepts that loopback URL, tested, including from a deployed Runtime, so this isn’t a local-only trick. The legacy agentcore starter toolkit already does it for you. Why does that work without a cookie when the web app needs one? The cookie was never the goal. Proving the finisher is the starter is the goal, and each context proves it differently. The forwarding attack needs the victim’s completed consent to land where the attacker’s pending flow lives. With a CLI that’s http://localhost, reachable only from the attacker’s own machine, so a link opened on someone else’s machine redirects to their localhost and the attacker’s flow never completes. The loopback boundary does what the cookie does. A web app can’t lean on that, because its callback is a public URL shared by every user (it has to be, to serve them all on any machine), so a forwarded completion lands at that same shared server and the cookie becomes the only way to tell whose browser it is. The CLI gets that boundary from the network for free. A web app has to build it out of the session. For a headless Runtime-hosted agent the cleanest path is to pre-authorize once. Have the user consent a single time up front so a refreshable token is vaulted, after which the agent reads the cached token and never needs a browser. A caveat I had wrong until I tested it: AWS documents AllowedResourceOauth2ReturnUrl as a public HTTPS endpoint, but loopback is in fact accepted, including on a deployed Runtime’s service-managed identity. The tested rule is below. A recipe you can copy The whole idea in one sentence: your app already knows who’s logged in, and session binding says don’t finalize a user’s Google connection unless the person in the browser right now is signed in as that same user. Same instinct as a “link your bank account” button that refuses to run unless you are the one logged in and clicking it. One constraint makes it more than a vibe. At the callback you must call complete_resource_token_auth with the identity that started the flow. That’s the identity the session URI is tied to, the one that minted the workload access token. You can’t substitute whoever happens to be in the browser. So you need two things. Know who started this particular flow, and confirm that’s who’s logged in now. A short-lived ledger in your own store does both, and it’s framework-agnostic. # STEP 1: when you kick off 3LO for the currently-logged-in user. # # From AWS: just boto3. There is no special client for any of this. import boto3 client = boto3.client(\"bedrock-agentcore\", region_name=\"us-east-1\") # # Yours to supply, because they're specific to your app and framework: # request the inbound HTTP request object (Flask, FastAPI, Django, whatever) # current_user the user your app already authenticated for this request # pending_auth a short-TTL key-value store you own: DynamoDB, Redis, Postgres. # Needs put(key, value, ttl) / get(key) / delete(key). # send_user_to however your framework issues a browser redirect # The Runtime sends the same value under both names. Lookups are case-insensitive, # but they are not hyphen-insensitive, so match these exact spellings. WAT_HEADERS = (\"workloadaccesstoken\", \"x-amzn-bedrock-agentcore-runtime-workload-accesstoken\") def read_injected_wat(headers) -> str | None: return next((headers[n] for n in WAT_HEADERS if headers.get(n)), None) # Where `wat` comes from: READ the token the Runtime injected. Do not mint one here. # 3LO files the result under (agent + user), so the token has to name a user, and an # agent-only token you minted yourself names none. No injected token means no user # reached your agent, which is an inbound problem. See the note under this snippet. wat = read_injected_wat(request.headers) if wat is None: return \"No user identity on this request.\", 401 # The raw call hands you the sessionUri; stash which user it belongs to. resp = client.get_resource_oauth2_token( resourceCredentialProviderName=\"google-provider\", scopes=[\"https://www.googleapis.com/auth/drive.metadata.readonly\"], oauth2Flow=\"USER_FEDERATION\", workloadIdentityToken=wat, resourceOauth2ReturnUrl=\"https://your-app.example.com/callback\", # endpoint (b) ) if \"authorizationUrl\" in resp: # first-time consent needed pending_auth.put(resp[\"sessionUri\"], current_user.id, ttl_seconds=600) # your DB / Redis send_user_to(resp[\"authorizationUrl\"]) # redirect the browser to consent # STEP 2: the callback (endpoint b), a route in YOUR web app. AgentCore sends the # browser here after consent (register this URL on the workload identity as an # AllowedResourceOauth2ReturnUrl). # # `pending_auth` is the same short-TTL store as step 1. `app` is your web framework's # app object, and the route decorator here is FastAPI-flavoured; use whatever yours is. # current_user_from_browser_session() is yours to write: it reads your session # cookie and returns the logged-in user, or None. That function IS the security # check, so it has to read the live session and not a cache. import boto3 client = boto3.client(\"bedrock-agentcore\", region_name=\"us-east-1\") @app.get(\"/callback\") def oauth_callback(request): session_uri = request.query_params[\"session_id\"] # the flow's session URI current = current_user_from_browser_session(request) # who's logged in NOW started_by = pending_auth.get(session_uri) # who kicked THIS flow off (from step 1) # THE session-binding check, in one line: if current is None or started_by is None or current.id != started_by: return \"Session mismatch, not authorizing.\", 403 # do nothing; token stays locked client.complete_resource_token_auth( sessionUri=session_uri, # Must match HOW the workload access token was minted (see rule below): # JWT inbound -> {\"userToken\": \"<the inbound JWT>\"} # IAM + User-Id -> {\"userId\": \"<the user id>\"} userIdentifier={\"userId\": current.id}, ) pending_auth.delete(session_uri) # one-time use return \"Connected. You can return to your assistant.\" Two things that will cost you an afternoon in step 1. resourceOauth2ReturnUrl must match the URL registered on the workload identity exactly, trailing slash included, or AgentCore won’t redirect to it. And the token you pass as workloadIdentityToken must be the injected, user-bound one: minting an agent-only token here is the one substitution that looks like it works and then files the grant under no user at all. The read-or-mint rule covers every credential type. Source: sessionUri and userIdentifier are the wire names, and this dict form is the one I tested. AWS’s session-binding page shows the same call through the Python SDK instead, where the arguments are snake_case and the identifier is a typed object rather than a dict, complete_resource_token_auth(session_uri=…, user_identifier=UserIdIdentifier(user_id=…)), with UserTokenIdentifier in the same module. Either form works, so pick one and be consistent. The session_id query-param name follows AWS’s sample callback server, and I confirmed AgentCore appends it to the redirect. Which identifier to complete with is not a free choice CompleteResourceTokenAuth validates the identifier against how the workload access token was minted, and the two inbound styles mint it differently. I tested both combinations. Inbound to your agent AgentCore minted the WAT via Complete with JWT authorizer GetWorkloadAccessTokenForJWT(userToken=<JWT>) {\"userToken\": \"<the inbound JWT>\"} IAM SigV4 + User-Id GetWorkloadAccessTokenForUserId(userId=<id>) {\"userId\": \"<the user id>\"} Get it wrong and the call fails with a generic AccessDeniedException: Invalid or expired session. This lines up with the docs’ wording, “the original inbound identity provider OAuth token or user_id String that was used to generate the workload access token”. The sub is low-secrecy, it’s in every token and every log. Requiring the actual token means the completer must possess the inbound credential, not merely know an id. That’s the entire mechanism. A valid session, and the logged-in user equals the user who started the flow. Run the Mallory attack through it and started_by is \"mallory\" while current.id is \"alice\", so the comparison fails and you 403 without releasing anything. Forward the link to a stranger instead and the first clause catches it: no session with your app means current_user_from_browser_session(...) returns None. So the whole scheme rests on one thing: your callback must actually read your real login session. You never authenticate the stranger’s Google identity. You only ever check your own app’s session. Don’t copy AWS’s sample server for this check Its oauth2_callback_server.py is a single-user dev harness, not a security template. You POST a user identifier to a /userIdentifier/token route before the flow, it stashes that in memory, and its callback passes it straight through with complete_resource_token_auth(session_uri=session_id, user_identifier=self.user_token_identifier). No comparison against a logged-in browser session anywhere. That stashed value is the originator, so the harness hands CompleteResourceTokenAuth the very identity the API is about to compare against. The check passes by construction, whoever is actually sitting in the browser. Fine for one local user, where the two are always the same person. Copied into a multi-user app it reopens the exact Mallory/Alice hole above: Alice consents, Mallory’s identifier completes the flow, and Alice’s token lands in Mallory’s slot with nothing logged. Use it to see how the call is wired, never as the security model. One caveat about the session URI Don’t try to decode it. The sessionUri is an opaque URN (urn:ietf:params:oauth:request_uri:...), not a JWT, so there’s no user claim to read off it. That’s exactly why the recipe keeps its own short-TTL ledger of who started which flow. Your current == started_by comparison is still worth writing even though the API enforces its own half, because it fails fast with a clean 403 instead of an opaque AccessDenied. What to remember about 3LO The two callback URLs have separate owners and separate registrations. (a) is AgentCore-hosted and goes in Google’s redirect-URI list; (b) is yours and goes on the workload identity. If your 3LO flow hangs after the user clicks Allow, look here first. Session binding is a shared job, and the half that’s yours is the one that’s easy to get wrong. AWS enforces that the userIdentifier you submit matches the user who started the flow. You supply that identifier, and it has to come from the live login session in the browser that just consented. Read it from your own pending-flow records instead and the enforcement is satisfied by construction and protects nobody. Match the identifier to the mint. JWT inbound completes with userToken, IAM plus User-Id completes with userId. Budget for it. Stand up endpoint (b) first, before you write the agent. And nothing suspends while a user consents, so at any scale you want them pre-authorized out of band, with the tool hitting a cached token. Who actually hosts endpoint (b) You do. AgentCore generates and hosts (a). It never hosts (b), on Runtime or self-hosted, and there is no setting that makes it. Endpoint (b) is code you write, deploy and own. It needn’t be a dedicated service. A single route in the web app that already fronts your agent is enough, and because (b) is never in the token’s path it can equally be a Lambda, a container, or a process in an unrelated app. Register it on the workload identity: aws bedrock-agentcore-control update-workload-identity \\ --name <your-workload-identity> \\ --allowed-resource-oauth2-return-urls https://your-app.example.com/callback What URLs are allowed A public HTTPS endpoint, or loopback on any scheme. Nothing else. AWS documents the field as “a publicly available HTTPS application endpoint” and says nothing about loopback, so I assumed http://localhost was a local-dev indulgence that would stop working once deployed. It isn’t. Loopback is accepted everywhere, including on a deployed Runtime’s service-managed identity, confirmed end to end from the receiving server’s own log. What the validator actually implements is RFC 8252’s loopback exception. Accepted — https://example.com:8443/callback, and on the three loopback hosts localhost, 127.0.0.1, [::1] any scheme at all: http://localhost/callback (port optional), http://127.0.0.1:8080/callback, https://localhost:8443/callback, even ftp://localhost:8080/callback. Rejected, ValidationException / HTTP 400 — http://example.com/callback (plain HTTP off-loopback), myapp://callback, http://app.localhost:8080/callback, http://127.0.0.2:8080/callback, https://192.168.1.50:8443/callback, https://10.0.0.5/callback, https://169.254.169.254/callback. Undocumented, not guaranteed. Tested 2026-09-22 in us-east-1. AWS’s devguide says this endpoint must be publicly available over HTTPS, and separately that Runtime requires a publicly accessible HTTPS callback. The service enforces neither. This is what it does, not what it promises, and behaviour that contradicts the docs is the kind that changes without notice. Why loopback isn’t the security hole it looks like Allowing plain http anywhere in an OAuth flow reads like a mistake, because the thing being redirected is worth stealing: the session URI that completes the flow. Over plain HTTP to a public host that value crosses the internet in cleartext, which is exactly why the validator rejects it. A loopback address never crosses anything. The browser hands the request to a process on the same machine over the loopback interface, and no packet reaches a network. TLS there would be encrypting a conversation that has no eavesdropper available to it. The exception isn’t a relaxation of the rule, it’s the recognition that the threat the rule exists to stop doesn’t apply on that path. What does remain is a hostile process on the same machine claiming the port first. RFC 8252’s answer is the state nonce, which the CLI pattern above already carries, and AgentCore adds its own: a completion whose userIdentifier doesn’t match the flow’s originator is refused outright. The reason it still can’t serve a web app has nothing to do with safety. Your users’ localhost is their machine, not your server, so a loopback callback is unreachable from any browser but the one on the host running the receiver. That’s fine for a CLI, where the browser and the receiver are the same machine by construction. It’s useless for a server that has to serve everybody. Public HTTPS in production is an architectural requirement, not a validation one. The local-dev shortcuts Two AWS-supplied receivers save you writing one while developing. Neither is a production component, and neither performs the session-binding check. The legacy Python bedrock-agentcore-starter-toolkit hosts (b) for you and registers http://localhost:8081/oauth2/callback itself via UpdateWorkloadIdentity — incidentally proving AWS’s own tooling relies on the loopback allowance. The npm @aws/agentcore that replaced it has no OAuth receiver at all (checked at 0.24.1), so if agentcore dev isn’t catching your redirect, that’s why. oauth2_callback_server.py, a short FastAPI script you run on localhost:9090 yourself, registering the URL yourself. AWS’s docs link a path that now 404s; that’s the current one. The awkward part On AgentCore Runtime, the registration step is genuinely backwards. The Runtime creates its own workload identity for you, service-managed, named after the runtime id, and that identity doesn’t exist until after the runtime is deployed. So you can’t declare the return URL up front alongside the runtime. It isn’t a property of the runtime resource, and it isn’t part of the execution IAM role either. It’s data on the identity. The order of operations ends up being: deploy the runtime, look up the identity it created, then call update-workload-identity on that identity to add your callback URL. Create a resource, go find what it auto-created, patch that, all to wire up something you knew from the start. But that is what AWS documents. The session-binding guide says register the return URL with CreateWorkloadIdentity or UpdateWorkloadIdentity, and notes that “for workload identities created on your behalf by AgentCore Runtime or Gateway, the workload identity name will correspond to the runtime ID”, meaning update the service-managed one. You could instead create your own workload identity with the return URL baked in and mint tokens against it explicitly, but that trades the managed decorator path for the raw one and isn’t the documented Runtime flow. The full order of operations That backwards step isn’t the only one. Standing a 3LO setup up from nothing has two circular dependencies, and the first one sends you back to your IdP a second time. Here is the whole sequence. At the IdP, create the OAuth client. You want the client id and client secret. You can’t fill in the redirect URI yet, because the value doesn’t exist — leave it empty or park a placeholder there. Create the AgentCore credential provider with that client id and secret. The response hands back callbackUrl, which is (a). AgentCore also writes the client secret into Secrets Manager at this point; keep the secret’s ARN, because two IAM roles will need it. Back to the IdP, and add (a) to the authorized redirect URIs. This is the hop people skip, because nothing prompts you to return: the value you need only came into existence in step 2. Deploy endpoint (b). Its role needs bedrock-agentcore:CompleteResourceTokenAuth and secretsmanager:GetSecretValue on the step 2 secret. Deploy the Runtime. This is the act that creates the service-managed workload identity, named after the runtime id. Its execution role needs GetResourceOauth2Token and the same Secrets Manager grant. Update that workload identity with (b)’s URL. Steps 4 and 5 don’t depend on each other and can run in parallel. Everything else is strictly ordered. The two loops are 1 → 2 → 3, where the IdP needs a value only AgentCore can mint, and 5 → 6, where the identity you must configure is created by the thing you just deployed. If you’re doing this in IaC Both loops are exactly what declarative infrastructure handles badly, and they break differently. Step 3 lands outside AWS, after an AWS resource exists. If your IdP has a decent Terraform provider — Auth0 and Okta do — you can express it as a resource with a dependency edge and it’s merely ugly. If it doesn’t, you have a manual console step wedged into the middle of an otherwise automated pipeline, and the honest move is to make it an explicit gate rather than pretend it isn’t there. Step 6 is the more interesting one, because you can design it away. The reason it can’t sit beside the Runtime is that the identity is created by the Runtime. Create your own workload identity instead and that inversion disappears: CreateWorkloadIdentity accepts allowedResourceOauth2ReturnUrls at creation, so the identity and its return URL become one ordinary declarative resource that the Runtime then references, rather than something you patch afterwards. This is the case where I’d reach for a bring-your-own workload identity by default. Everywhere else in this guide, BYO identity is an escape hatch for when the Runtime injects nothing. Here it’s a design choice that turns a post-deploy patch into a declaration. The price is the one named above: you mint against it explicitly, which means the raw API path rather than the decorator path. I’ve verified the API takes return URLs at creation. Whether AWS::BedrockAgentCore::WorkloadIdentity exposes them as a CloudFormation property I haven’t tested, so confirm that before building a stack around it. What that leaves is a four-way split, cut along change frequency and along what crosses a trust boundary. Provider. The IdP OAuth client and the AgentCore credential provider. Depends on nothing else, and changes only when you rotate credentials. Callback. Endpoint (b) and its IAM role. Needs the secret ARN from the provider stack. Agent. The Runtime, its execution role, and the workload identity if you own it. Needs the secret ARN from the provider stack, and (b)’s URL. This is the one that changes on every deploy. Wiring. The update-workload-identity call. Needs the callback and agent stacks to exist first, and changes only when (b) moves. The split is doing three specific jobs. Stack 3 changes on every agent deploy, and you don’t want a routine deploy to be able to touch the credential provider, so the provider goes in a stack that changes on rotation and nothing else. The client secret enters the system only at stack 1, which keeps it out of the state file the agent team runs plans against daily. And stack 4 exists only because of the step 6 inversion — take the BYO identity route and it folds into stack 3, leaving three stacks and no post-deploy patching. How the token actually reaches your agent, given that (b) never touches it, is below. Endpoint (b) needs its own IAM, including a Secrets Manager grant Because (b) is a separate process, its execution role is what calls CompleteResourceTokenAuth, not the agent’s. That role needs bedrock-agentcore:CompleteResourceTokenAuth and secretsmanager:GetSecretValue on the provider’s backing secret (secret:bedrock-agentcore-identity!default/oauth2/…). The second is easy to miss. CompleteResourceTokenAuth is what actually exchanges the auth code with the IdP, so it reads the provider’s client secret from Secrets Manager as (b)’s role. Omit it and you get AccessDeniedException: Access denied when retrieving secret …, and it lands after the session validates, so it looks like a 3LO bug rather than a missing grant. Same “the API reads the secret as your role” pattern as every other Vault read. What your tool is doing while the user consents When the agent calls a tool decorated with @requires_access_token, execution enters the decorator’s wrapper before your function body runs. The wrapper asks AgentCore for the token. On first consent there’s none, so it gets back an authorizationUrl, hands it to on_auth_url, and then appears to pause. It starts a polling loop. There’s no magic suspend, no checkpoint and no continuation. The loop itself is the TokenPoller in services/identity.py; the decorator just accepts one through its token_poller argument (identity/auth.py). # what the poller does, conceptually while True: resp = get_resource_oauth2_token(... same request ...) # ask AgentCore again if resp.get(\"accessToken\"): return resp[\"accessToken\"] # got it, let the function body run time.sleep(poll_interval) # wait a couple seconds... if elapsed > timeout: raise TimeoutError # ...or give up So the call stack is parked in a live loop the whole time. agent's turn └─ calls tool: access_user_drive(...) └─ @requires_access_token wrapper ← execution is sitting in this loop └─ polls GetResourceOauth2Token every few seconds (your function body has NOT started yet) The process is alive and busy, re-polling. From the model’s point of view the tool call simply hasn’t returned yet. And CompleteResourceTokenAuth, called by endpoint (b), doesn’t resume anything directly. It writes the token to the Vault, and the loop’s next iteration finds it there and returns it. Two separate processes, synchronized only through the Vault. That has consequences worth designing around. A human is in your invocation’s critical path. The tool call stays open while someone clicks through consent, which on a Runtime counts against the max invocation duration, and the poll has its own timeout on top. The clean fix is to pre-authorize users out of band, so the tool finds a cached token and never pauses. It only pauses on first consent. With force_authentication=False, once a user has consented the token is cached and auto-refreshed, so later calls never pause. The stall is a first-consent or post-revocation event, not an every-call tax. The raw API lets you avoid blocking entirely. Since you own the poll, you can return the authorizationUrl to your caller, end the invocation, and re-drive the tool once consent is done. Interrupt and resume instead of a long synchronous wait. The same flow without the decorator The agent side by hand. You mint the workload access token and call get_resource_oauth2_token yourself, handling the authorizationUrl re-poll branch. import boto3 client = boto3.client(\"bedrock-agentcore\", region_name=\"us-east-1\") # `request` is your inbound HTTP request object. Nothing else here is AgentCore-specific. WAT_HEADERS = (\"workloadaccesstoken\", \"x-amzn-bedrock-agentcore-runtime-workload-accesstoken\") def read_injected_wat(headers) -> str | None: return next((headers[n] for n in WAT_HEADERS if headers.get(n)), None) # 3LO needs a USER-bound token, so read the one the Runtime injected. Don't mint: # an agent-only token names no user, and there'd be no (agent + user) Vault entry. wat = read_injected_wat(request.headers) if wat is None: raise RuntimeError(\"no workload access token on the request\") req = { \"resourceCredentialProviderName\": \"google-provider\", \"scopes\": [\"https://www.googleapis.com/auth/drive.metadata.readonly\"], \"oauth2Flow\": \"USER_FEDERATION\", \"workloadIdentityToken\": wat, \"resourceOauth2ReturnUrl\": \"https://your-app.example.com/callback\", # endpoint (b) # \"customState\": \"...\", # echoed to (b) as ?state= # \"forceAuthentication\": True, # ignore any cached token, re-consent } resp = client.get_resource_oauth2_token(**req) if \"accessToken\" not in resp: # first consent: URL instead of a token print(\"Authorize here:\", resp[\"authorizationUrl\"]) # the decorator's on_auth_url # ...user consents, endpoint (b) calls CompleteResourceTokenAuth... poll_req = {**req, \"sessionUri\": resp[\"sessionUri\"], \"forceAuthentication\": False} resp = client.get_resource_oauth2_token(**poll_req) # repeat until accessToken appears provider_token = resp[\"accessToken\"] A few details in there that the diagrams gloss over. The poll must echo sessionUri and set forceAuthentication back to False, or you restart the consent you’re waiting on. customState is an opaque string AgentCore hands to endpoint (b) as ?state=, which is how (b) learns which identifier to complete with. And resourceOauth2ReturnUrl has to match the registered return URL character for character, trailing slash included. Where wat comes from, and what to do when it’s absent, is the read-or-mint rule. The decorator and the Runtime each automate a different slice, and neither hosts (b). The Runtime’s contribution is exactly one thing: it mints the workload access token and injects it into your request. The decorator’s is two: it hands you the consent URL through on_auth_url, and it polls until the token lands. Drop to the raw API and you do both of those yourself — read the URL off the GetResourceOauth2Token response, then re-call it echoing sessionUri until an accessToken comes back. Endpoint (b) and the session-binding check appear in neither list. In production they are yours, decorator or not, Runtime or self-hosted. The only time anything else hosts (b) is local dev, where the legacy starter toolkit or the sample server stands in for you. The same 3LO flow both ways. Left is the decorator, right is the exact API sequence it hides, with every @requires_access_token argument mapped (←) onto the internal parameter it becomes. I checked this against IdentityClient.get_token in services/identity.py and reproduced it end to end in both forms. Figure 5. The same 3LO flow with and without the decorator. A note on two of the labels there. custom_state becomes customState and is echoed to endpoint (b) as state, which is the channel that carries identity to the callback. And the userIdentifier in CompleteResourceTokenAuth is dictated by inbound type, userToken for JWT and userId for IAM plus User-Id, and it’s a call endpoint (b) makes, not the agent. Downstream sees the end user, so user-delegated access, and the provider access token is vaulted per agent + user. Forwarding a token you already hold: JWT passthrough This one is much simpler. Use passthrough when you already have a user token and the target accepts that exact token, same IdP and same audience. Common when you own the target: your agent and the downstream service both sit behind your own Auth0 or Cognito tenant, so the token the user presented to your agent is equally valid downstream. The agent forwards the user’s inbound JWT unchanged, so there’s no new token, no credential provider, no Vault entry and no consent step. AWS documents this as “Propagate a JWT token”, and at the Gateway it’s the JWT_PASSTHROUGH outbound type. Two moving parts: allow the header in at deploy time, then read it and attach it to the outbound call. Allow the Authorization header through It is not forwarded to your container by default. You opt in via the runtime’s request-header allowlist, and it’s permitted only on a custom-JWT-authorizer runtime. Per AWS: “You can also pass the Authorization header for JWT-based authentication when your agent is configured with a custom JWT authorizer,” and “The Authorization header requires the agent runtime to be configured with a customJWTAuthorizer.” (Authorization isn’t on the restricted-headers list. Up to 20 headers, each 4KB or less.) # AWS's `agentcore` CLI agentcore configure --entrypoint agent.py --name my-agent --execution-role <role-arn> \\ --authorizer-config '{\"customJWTAuthorizer\":{\"discoveryUrl\":\"...\",\"allowedClients\":[\"...\"]}}' \\ --request-header-allowlist \"Authorization\" # CloudFormation, AWS::BedrockAgentCore::Runtime RequestHeaderConfiguration: RequestHeaderAllowlist: - Authorization Read it and call the downstream Once allowlisted, the header arrives in the request context. Strip the Bearer prefix and attach the token, unchanged, to your outbound request. import requests # ordinary HTTP client; the forwarding here is just a header # `app` is your BedrockAgentCoreApp instance, so `context` is what the SDK passes in. @app.entrypoint def invoke(payload, context): # context.request_headers with BedrockAgentCoreApp; request.headers on a BYO server user_jwt = context.request_headers.get(\"Authorization\", \"\").removeprefix(\"Bearer \") # forward it unchanged to a downstream that trusts the SAME IdP + audience resp = requests.get( \"https://internal-service.example.com/data\", headers={\"Authorization\": f\"Bearer {user_jwt}\"}, ) return resp.json() Source: allowlisting rules and context.request_headers from Pass custom headers to AgentCore Runtime. JWT propagation framing from Runtime inbound/outbound auth. I confirmed separately that without the allowlist entry, the inbound Authorization header never reaches the container. The catch The token carries the user’s expiry. On a long-running task it can expire mid-flight, and you can’t refresh it, because it isn’t yours. There’s no fix at this layer. If that’s a real risk for your workload, exchange the token instead, which is OBO. Passthrough also requires the user’s token to have arrived inbound as a JWT, which makes it a non-starter under IAM inbound. Downstream sees exactly the user’s original identity, their unchanged inbound JWT. Passthrough is the cheapest user-delegated mechanism and the least flexible. Eight lines of code, one allowlist entry, zero Vault involvement, and a hard ceiling at the user’s token expiry and the target’s audience. Test your understanding What are the two callback URLs in a 3LO flow, who hosts each one, and where do you register each one? What is the sequence of AWS API calls in a 3LO flow, including the ones your callback endpoint makes rather than your agent? What is session binding and which attack does it prevent? What is your agent doing while it waits for a user to consent? When is JWT passthrough the right mechanism, and what is its hard limit? Answers Exchanging for a new audience: OBO The third way to act as a user. This section stays high level, because a working exchange depends mostly on configuration inside your identity provider, and that isn’t something I can test on your behalf. AWS’s on-behalf-of token exchange page has the configuration, the parameters, and the code. Reach for it when you hold a token for the user, the target rejects it because it wants a token minted for its own audience, and the authorization server on the other end will actually perform the exchange for you. That last condition is the one that decides whether this is available at all. Where it holds, re-prompting the user would be absurd, since they already consented: your agent hands AgentCore the token it has, AgentCore trades it with the IdP for a new one scoped to the downstream, and the new token carries both the user’s identity and the agent’s as the acting party. No browser, no second consent screen. Typical shape: an internal service you at least partly own, behind the same IdP as your agent but validating tokens minted for itself. The user’s token arrived at your agent inbound, addressed to your agent’s audience. The service you need to call won’t accept it, so you exchange it for one addressed to theirs. That’s the whole of what your agent does: one hop, one exchange. What makes it interesting is that it composes. If the service you called then needs to call something further along, it exchanges the token it received the same way. Repeat as needed and the user’s identity survives a chain of any length without anyone being re-prompted, which is the property AWS means by zero-trust authorization at every hop. Against its two neighbours. 3LO also acts for the user, but it runs an interactive consent flow to create a token, while OBO reuses one that already exists. Passthrough also reuses an existing token, but it sends it unchanged, so it only works when the audience already matches. The moment a downstream rejects your token’s audience, passthrough is out. What replaces it depends on who runs the downstream’s authorization server. If it’s one you can configure a trust in, OBO. If it isn’t, OBO is simply not on the menu and you’re back to 3LO, holding a perfectly valid user token you have no way to trade. Your internal JWT says nothing Google is willing to act on, so writing to that user’s Drive means originating a Google token through Google’s own consent flow. Mechanically it’s an option on the OAuth credential provider, an onBehalfOfTokenExchangeConfig, brokered over RFC 8693 token exchange or RFC 7523 JWT-bearer, and requested with oauth2Flow=\"ON_BEHALF_OF_TOKEN_EXCHANGE\". It needs a user-bound workload access token, since the user’s original JWT is the subject of the exchange, so it’s JWT-inbound territory and an agent-only token is no substitute. OBO depends on your IdP more than any other mechanism here AgentCore only brokers. Per AWS, it “automatically takes the inbound access token… along with the client credentials already stored in the credential provider, and brokers the token exchange request with the customer’s IdP… It submits the request, parses the response, and returns it to the agent.” And critically: “the authorization server makes the final authorization decision, including whether to grant the requested scopes and whether to permit the delegation.” So your authorization server has to implement RFC 8693 or RFC 7523 itself, and which one it speaks is its contract, not AgentCore’s. AWS ships turnkey support for one vendor today, MicrosoftOauth2; everything else goes through CustomOauth2 with configuration you own, which means reading your provider’s own token-exchange documentation rather than AWS’s. That reverses the usual order of work. Everywhere else in this guide you can start with AgentCore and work outward. Here, check that your provider supports the exchange grant first, because if it doesn’t, no amount of AgentCore configuration produces a token. My opinion: if you’re building tiered services where agents call other protected services as the user, OBO is the design AWS clearly wants you to reach for. Downstream sees the user and the agent, in a provider access token minted for the downstream’s own audience. When user identity can’t arrive inbound: the User-Id header All three user-delegated mechanisms need a user identity to work from. On a JWT-inbound Runtime that’s automatic, since the verified iss and sub become the user. Under IAM inbound the caller is an IAM principal, typically your backend’s role fronting all your end users, so AgentCore can’t tell Alice’s request from Bob’s and has no idea whose Vault entry a 3LO flow should use. The X-Amzn-Bedrock-AgentCore-Runtime-User-Id header restores the missing identity. Internally it rides the GetWorkloadAccessTokenForUserId on-ramp, so the user-delegated flows operate on the right agent + user pair while the wire stays IAM SigV4. There is no separate “invoke-for-user” API. You make the same InvokeAgentRuntime call and set that header (in boto3, the runtimeUserId parameter). InvokeAgentRuntimeForUser is an IAM action, not an operation. Supplying the header adds its authorization check, so the caller needs both bedrock-agentcore:InvokeAgentRuntime and bedrock-agentcore:InvokeAgentRuntimeForUser. Omit the header and it’s a plain InvokeAgentRuntime with no user, and as the injection tests showed, no workload token injected at all. (InvokeAgentRuntime API) Your agent never sees the raw user id (tested) I confirmed this two independent ways. The Runtime consumes the User-Id header server-side. It calls GetWorkloadAccessTokenForUserId, mints a user-scoped workload access token, then injects that token as the WorkloadAccessToken header. The raw X-Amzn-Bedrock-AgentCore-Runtime-User-Id header never reaches your container. First, it’s simply absent from the invocation request. Second, you can’t force it through the header allowlist; trying fails at deploy time with 400 … Header 'X-Amzn-Bedrock-AgentCore-Runtime-User-Id' is restricted and cannot be configured. (All reserved x-amzn-* headers are non-forwardable except X-Amzn-Bedrock-AgentCore-Runtime-Custom-*.) So a container under IAM+User-Id receives exactly what a JWT-inbound one does, a WorkloadAccessToken and nothing else, with the user id baked opaquely into that token. So why send the header at all, if you can’t read it? Because it does one job, and it isn’t for your code. It’s the input AgentCore needs to mint the user-scoped workload access token, the token that binds this Runtime’s workload identity to this user. That binding is what makes the managed user-delegated flows work: the Vault hands back that user’s 3LO or OBO credentials automatically, with no user id anywhere in your code. That’s the whole purpose. Link workload identity plus user for credential retrieval. If you need the user id for anything else, fetching that user’s AgentCore Memory records, a per-user row in your own database, audit logs, you must pass it a second time separately. Either in the invocation payload or as your own X-Amzn-Bedrock-AgentCore-Runtime-Custom-… allowlisted header. The official header and your copy feed different consumers, the platform’s Vault machinery versus your application logic, so under IAM+User-Id you end up sending the id twice by design. Under JWT inbound you’d instead read the verified sub from the forwarded token, once. This header is unverified, so treat it as a footgun AWS is blunt: it “treats the header value as an opaque identifier without verifying it against an authenticated identity.” Anyone who can call InvokeAgentRuntimeForUser can claim to be any user. So lock the IAM action down, derive the user-id from your authenticated context and never from user input, audit-log the principal-to-user-id pairing, and explicitly Deny it where you don’t need it. AWS positions this path for enterprise and quickstart use. For production, prefer JWT inbound, where identity rides verified inside the token. (Runtime auth) Test your understanding What’s the difference between JWT passthrough and on-behalf-of exchange? In an OBO exchange, which part is AgentCore’s responsibility and which part is your IdP’s? What is the User-Id header for, and why can’t your agent read it? Answers No user at all Case 4: the target wants a machine (M2M) token This is the case with no human in it at all. The call acts as the agent itself, with no user and no consent. Access is defined at the agent level: “Permissions are defined at the agent level rather than per-user” (supported patterns). Two flavors, and the target decides which. If the target is AWS-hosted and IAM-authed, just sign it If the downstream Gateway or Runtime uses IAM inbound and you don’t need user identity, this is the simplest path by a mile. When everything lives inside AWS, default to it. The agent uses its execution role’s AWS credentials to make SigV4-signed requests. No OAuth, no providers, no Vault. The role needs bedrock-agentcore:InvokeGateway (or InvokeAgentRuntime), and AWS’s mcp-proxy-for-aws package signs the MCP calls. Nothing about this is AgentCore-specific. It’s the ordinary AWS execution-role model, the same as a Lambda execution role, an ECS task role, or an EC2 instance role. The Runtime assumes its role, the SDK picks up those role credentials from the environment, and outbound access is whatever IAM policy you attach. SigV4 to any AWS service or IAM-authed endpoint, gated by that role, not by any of the Vault or provider machinery described here. If you’ve ever given a Lambda permission to call another AWS service, you already know how this works. from mcp_proxy_for_aws.client import aws_iam_streamablehttp_client from strands.tools.mcp import MCPClient mcp_client = MCPClient(lambda: aws_iam_streamablehttp_client( endpoint=gateway_url, aws_region=\"us-east-1\", aws_service=\"bedrock-agentcore\")) Source: import and client signature from the mcp-proxy-for-aws repo, which wraps an MCP client so its HTTP calls get SigV4-signed. MCPClient here comes from Strands, AWS’s open-source agent SDK; swap in whatever MCP client your framework provides. Gateway IAM inbound from Gateway inbound auth. Downstream sees the execution role’s IAM principal. No user identity, no provider token at all. In practice: if your answer to “do I care which user?” is no and the target is an AWS-hosted endpoint, stop here. Don’t reach for OAuth machinery you don’t need. If the target speaks OAuth, use client credentials If the target validates OAuth tokens rather than SigV4, which covers another Runtime behind a JWT authorizer, a Gateway trusting an IdP, or an internal API expecting a bearer token, the agent gets a new token as itself via the client-credentials grant. The token issuer is not the Runtime you’re calling. Three separate roles, and conflating them is what breaks this setup: Figure 6. Three roles in an M2M call between agents. Your IdP issues the token. Runtime 1 has a credential provider that fetches it, which is outbound. Runtime 2 has its own inbound JWT authorizer that trusts the same IdP and validates it. Runtime 2 issues nothing. from bedrock_agentcore.identity.auth import requires_access_token @requires_access_token( provider_name=\"auth0-gateway-provider\", scopes=[\"invoke:gateway\"], audiences=[\"https://my-api.example.com\"], # see note below auth_flow=\"M2M\", # client credentials, no user ) async def call_gateway(*, access_token: str): ... Source: adapted from AgentCore identity authentication. That audiences argument is easy to leave out and hard to debug when you do. Some authorization servers key the client-credentials grant on the audience rather than on scopes: with Auth0, the API identifier goes there, and without it you get a token the downstream rejects. Whether you need it is your IdP’s contract, not AgentCore’s. M2M is agent-only, so unlike 3LO it does have a valid mint fallback. The raw version reads the injected token when there is one and mints an agent-only token when there isn’t: import os import boto3 client = boto3.client(\"bedrock-agentcore\", region_name=\"us-east-1\") STANDALONE_WI = os.getenv(\"STANDALONE_WORKLOAD_IDENTITY_NAME\") # one you created WAT_HEADERS = (\"workloadaccesstoken\", \"x-amzn-bedrock-agentcore-runtime-workload-accesstoken\") def read_injected_wat(headers) -> str | None: return next((headers[n] for n in WAT_HEADERS if headers.get(n)), None) wat = read_injected_wat(request.headers) if wat is None: # bare SigV4, no User-Id wat = client.get_workload_access_token( workloadName=STANDALONE_WI, # an identity YOU created )[\"workloadAccessToken\"] token = client.get_resource_oauth2_token( resourceCredentialProviderName=\"auth0-gateway-provider\", oauth2Flow=\"M2M\", workloadIdentityToken=wat, scopes=[\"invoke:gateway\"], # required even when empty: pass [] audiences=[\"https://my-api.example.com\"], # omit if your IdP doesn't want it )[\"accessToken\"] M2M returns the accessToken on the first call, with no authorizationUrl, no sessionUri, no polling and no callback endpoint. That’s the whole difference from 3LO on the wire. (The read-or-mint rule covers read_injected_wat and the scopes trap.) Downstream sees the agent itself, a client-credentials identity, with no user, and the provider access token is vaulted agent-only. Prereqs: configure the auth server and client credentials first, then the credential provider, then register its callback URL. (auth_flow=\"M2M\" reference) No user anywhere? That’s a perfectly normal setup, not a degenerate one. A backend invoking your agent with an M2M JWT or IAM SigV4, your agent reaching downstream with SigV4 or client credentials, uses AgentCore Identity end to end with no human identity in the chain. The directory, credential providers, and Vault all operate in agent-only mode. User identity is something you opt into. The plumbing What the workload access token actually is Every mechanism above, API keys, 3LO, passthrough, OBO and M2M, quietly depended on the same thing. Each one needed a workload access token, which I kept calling the key to the Vault and promised to explain properly. An AWS-signed, opaque token representing your agent’s workload identity, bound to a user when there is one. It is not the inbound JWT the caller presented. It is not the provider access token you eventually send to Google or Slack. It sits between them with one job: authorize your agent against AgentCore’s own first-party services, the Token Vault and the credential providers. AWS is blunt that it’s “exclusively for accessing AWS first-party AgentCore services and cannot be used for external services.” You cannot call Google with it, and there’s no clever way to make it work. What’s inside it (I tried to decode one) The header value is an AWS Encryption SDK message. It base64-decodes to a blob starting AgV4…: format version 0x02, a committing and ECDSA-P384-signed AES-256-GCM suite. Its encryption context is cleartext routing metadata. I could read DataType=WorkloadAccessToken, Service=ACPS (AgentCore’s identity service), my CustomerAwsAccountId, and an aws-crypto-public-key. But the body is wrapped by a KMS key in an AWS-service-owned account, arn:aws:kms:…:677273280899:key/…, not your account. So there’s no decrypting it client-side. That’s the design. The envelope is readable enough to route, the payload is sealed to AgentCore. It’s also why you can’t recover the user id, or anything else, from it inside your container. Three tokens, three roles. The vocabulary from earlier, pinned down: Inbound JWT Workload access token Provider access token (outbound) Issued by The caller’s IdP (Cognito, Auth0, Okta) AWS / AgentCore Identity The external provider (Google, Slack) Represents The end user Agent identity + user identity, bound together Delegated access to the external resource Format JWT (iss / sub) AWS-signed opaque token Provider’s access token Presented to Your agent, as inbound auth AgentCore’s Token Vault / credential providers The external API You use it to Prove who the caller is (inbound) Unlock the Vault (mint, then spend) Actually call the downstream API The three on-ramps for minting one The mechanics are two hops. First you mint a workload access token from whatever user identity you have. There are exactly three on-ramps and they map onto the Runtime-versus-self-hosted distinction. Your situation How user identity arrives Bridge API User-token mechanisms this opens JWT inbound (on a Runtime) Verified iss + sub claims GetWorkloadAccessTokenForJWT Originate (3LO), Exchange (OBO), Forward (passthrough) IAM inbound + User-Id header An unverified header your caller supplies GetWorkloadAccessTokenForUserId Originate (3LO) via the header path Self-hosted (no authorizer) You assert it, a JWT or an opaque user id GetWorkloadAccessTokenForJWT / ForUserId, called by you Originate (3LO), Exchange (OBO), with the identity you assert No user at all It doesn’t GetWorkloadAccessToken (agent-only) Agent-only (M2M / SigV4) Then you spend it. Hand it to GetResourceOauth2Token or GetResourceApiKey as the workloadIdentityToken parameter and AgentCore returns the real provider access token from the Vault, scoped to exactly the agent + user the workload access token encodes. Step zero: do you already have one? Before minting anything, check whether the platform handed you a token. On a Runtime it usually has, and minting a second one is both wasteful and, for user-scoped work, wrong. What to do when the header is empty depends on what kind of credential you’re after, and the split is sharp: You’re fetching Token was injected Nothing was injected API key or M2M (agent-only) Use it. It may be user-bound; harmless here. Mint an agent-only token against a workload identity you created. 3LO, OBO, passthrough (user-scoped) Use it. The user binding is the entire point. You can’t substitute. An agent-only token names no user, so there’s no (agent + user) Vault entry for it to reach. Fix the inbound path instead: have the caller send User-Id, or move the Runtime to JWT inbound. That bottom-right cell is why my 3LO and M2M handlers return 401 rather than falling back to a mint: on a JWT Runtime a missing token means something upstream is broken, and papering over it with an agent-only token would either fail at the Vault or quietly bind the wrong subject. The read half is then the same in every raw handler: # The Runtime sends the same value under both names. Lookups are case-insensitive, # but they are not hyphen-insensitive, so match these exact spellings. WAT_HEADERS = (\"workloadaccesstoken\", \"x-amzn-bedrock-agentcore-runtime-workload-accesstoken\") def read_injected_wat(headers) -> str | None: return next((headers[n] for n in WAT_HEADERS if headers.get(n)), None) Mint and spend, in code The mint half is what you write when read_injected_wat comes back None and you’re off a Runtime entirely. It’s also what @requires_access_token does for you, so you’d normally only write it by hand off the Runtime, or from a language without the SDK. The two are alternatives: use the decorator or call these APIs directly, never both. import boto3 # Data-plane client. On a Runtime you rarely need this, the decorator does all of it. client = boto3.client(\"bedrock-agentcore\", region_name=\"us-east-1\") # 1) MINT a workload access token. Off-Runtime you assert the user by passing their # inbound JWT; on a Runtime this token is minted and injected for you instead. wat = client.get_workload_access_token_for_jwt( workloadName=\"my-demo-agent\", # your self-created workload identity userToken=\"<end-user-jwt>\", )[\"workloadAccessToken\"] # response field is 'workloadAccessToken' # 2) SPEND it. Every spend call takes the token as `workloadIdentityToken`; which call # and which flow depends on the credential. This is the API-key one, the shortest. api_key = client.get_resource_api_key( resourceCredentialProviderName=\"my-api-key-provider\", workloadIdentityToken=wat, )[\"apiKey\"] Source: request and response shapes from the GetResourceOauth2Token and GetWorkloadAccessTokenForJWT API references. IdentityClient(\"us-east-1\").get_workload_access_token(workload_name=…, user_token=…) is a thin SDK convenience over step 1. The OAuth spend calls are the same shape with get_resource_oauth2_token and an oauth2Flow. 3LO is the only one with a second half, because it’s the only one that has to wait for a human; M2M and OBO return the credential on the first call. A couple of things to notice while the two tokens are side by side. The decorator’s auth_flow and callback_url are friendly names for the API’s oauth2Flow and resourceOauth2ReturnUrl, same concepts one layer down. And the credential you get back is the provider access token, while the workloadIdentityToken you passed in is the workload access token. Two different tokens in one call, which is why keeping the names straight matters. One scoping note before the calls. Everything in this guide describes what AgentCore Identity will do for you. Your agent is ordinary code, and nothing stops you from running IAM inbound with no header and implementing the authorization-code grant yourself, with your own OAuth client, callback endpoint, and encrypted store. That’s a legitimate architecture. The price is that you’ve rebuilt the Token Vault by hand: secure storage, encryption, refresh, agent + user scoping, session binding. So treat the managed mechanisms as the list of things AgentCore does for you, not the list of things you’re allowed to do. When the Runtime hands you nothing Two situations the docs leave you to work out. I couldn’t find the first one documented anywhere. You can’t mint against the Runtime’s identity, but you can bring your own The Runtime’s service-managed identity is blocked from GetWorkloadAccessToken* (WorkloadIdentity is linked to a service and cannot retrieve an access token by the caller), so the usual raw-on-Runtime path reads the injected token. The neighbouring mistake fails differently: a workloadName that isn’t in your account gives you AccessDeniedException: Workload Identity does not belong to caller account. But nothing stops you, from inside the Runtime, minting against a self-created workload identity. That turns out to be the answer to an otherwise dead-end scenario. Picture an AWS-credentialed backend invoking your IAM-inbound Runtime with no User-Id header and no M2M token, where the agent needs an agent-level secret like an API key. There’s no injected token, since I verified bare SigV4 injects nothing, and you can’t mint against the Runtime’s blocked identity. The way out is to create your own workload identity, then from the agent mint an agent-only token against it and spend it. Verified end to end on a Runtime: import os import boto3 client = boto3.client(\"bedrock-agentcore\", region_name=\"us-east-1\") # A workload identity YOU created, via CloudFormation # AWS::BedrockAgentCore::WorkloadIdentity or `create-workload-identity`. STANDALONE_WI = os.getenv(\"STANDALONE_WORKLOAD_IDENTITY_NAME\") wat = client.get_workload_access_token(workloadName=STANDALONE_WI)[\"workloadAccessToken\"] # agent-only, no user api_key = client.get_resource_api_key( resourceCredentialProviderName=\"my-provider\", workloadIdentityToken=wat, )[\"apiKey\"] Grant the execution role GetWorkloadAccessToken on that identity’s ARN, plus the usual GetResourceApiKey and secretsmanager:GetSecretValue. In my test this returned the key while the injected-token and decorator paths came up empty, because it doesn’t depend on anything the Runtime injects. The same pattern works for outbound M2M, not just API keys. Swap the spend call for get_resource_oauth2_token(oauth2Flow=\"M2M\", scopes=[...], workloadIdentityToken=wat) and it returns the machine token. Also verified under bare SigV4, where the decorator path instead fabricate-failed with CreateWorkloadIdentity AccessDenied. So bringing your own workload identity is the general agent-only escape hatch, API key or M2M, whenever the Runtime injects no token. The decorator’s fabricate path always binds to a user Whenever no token is in context and DOCKER_CONTAINER is not 1, which the SDK calls its “local dev” path but which also fires on a Runtime under bare SigV4, @requires_access_token and @requires_api_key call CreateWorkloadIdentity, fabricate a user id (an 8-char UUID slice), cache both in .agentcore.json, and mint via GetWorkloadAccessTokenForUserId. Confirmed in a local run. The file holds {\"workload_identity_name\": …, \"user_id\": …} and the SDK logs “Found existing workload identity from …/.agentcore.json”. Some AWS docs still call this file .bedrock_agentcore.yaml. So even API-key and M2M go through a user-bound token on this path, which is why such a run can behave differently from a production one using the real injected token. Reading the injected token How you get at the Runtime-injected token depends on whether you run inside the SDK’s server. With BedrockAgentCoreApp (runtime/app.py), its server already read the header into a request-scoped context, so use the accessor from runtime/context.py. This is what the decorator does under the hood: from bedrock_agentcore.runtime.context import BedrockAgentCoreContext wat = BedrockAgentCoreContext.get_workload_access_token() # -> str | None There’s also a decorator for this, if you’d rather not touch the context object. @requires_wat reads the same token out of the context and passes it into your function, defaulting to the identity_wat keyword argument (identity/auth.py): from bedrock_agentcore.identity.auth import requires_wat @requires_wat() async def fetch_something(*, identity_wat: str): # spend identity_wat directly as workloadIdentityToken ... With your own FastAPI or Flask server, nothing populates that context, so read the header off the request yourself with read_injected_wat and either pass the result to get_resource_* as workloadIdentityToken or call BedrockAgentCoreContext.set_workload_access_token(wat) so the decorator finds it. That second option is exactly what BedrockAgentCoreApp does for you before your handler runs. Either route only yields a token when the Runtime actually injected one, so JWT or IAM plus User-Id inbound. Under bare SigV4 you get None, and the read-or-mint rule takes over. The short version of the plumbing The workload access token is a Vault key and nothing else: opaque, AWS-signed, sealed to an AWS-owned KMS key. Don’t try to read a user id out of it. Underneath, there’s one pipeline. The Runtime spares you the identity and the mint, since it owns one and injects the other, and the decorator spares you the spend and the 3LO poll. Strip both away and what’s left is: CreateWorkloadIdentity → GetWorkloadAccessToken* → GetResource{Oauth2Token,ApiKey} with CompleteResourceTokenAuth bolted on for the one workflow that needs human consent. Self-hosting means writing those calls yourself, on the same pipeline with the lid off. Bring your own workload identity when the Runtime gives you nothing. Bare SigV4 with no user injects no token and the managed paths dead-end, but a self-created identity plus an agent-only mint works. I tested it for both API keys and M2M. Two IAM permissions, always. bedrock-agentcore:GetResource* and secretsmanager:GetSecretValue. If you remember one operational fact from all of this, make it that one. Test your understanding What are the two M2M flavors and how do you choose between them? What is the workload access token and what can you not do with it? What are the three APIs for minting one, and what decides which of them you call? The platform injected no token. What do you do if you’re fetching an API key, and what do you do if you’re running 3LO? What is the full API pipeline once you remove both the Runtime and the decorator? Answers Reference Everything from here down is meant to be skimmed and bookmarked rather than read straight through. The whole model in five lines. Inbound (who may call your agent) and outbound (how your agent reaches everything else) are independent systems. Inbound lives on the Runtime or Gateway. Outbound works anywhere you have AWS credentials. For outbound, the target picks the mechanism: nothing, an API key, a user’s token, or a machine token. “Act as a user” has three answers: originate (3LO), forward (passthrough), exchange (OBO). Underneath all of it: CreateWorkloadIdentity → GetWorkloadAccessToken* → GetResource{Oauth2Token,ApiKey}. Every API call, in every mode The decorator is wonderful right up until you self-host, at which point it stops hiding the machinery and you need to know exactly which APIs fire, in what order. This is the lookup version; the narrative is back in the plumbing. The universal skeleton Strip away the workflow-specific details and every outbound credential fetch is the same three steps. Have a workload identity. The agent needs an entry in the Agent Identity Directory. Mint a workload access token from an identity. Three variants: GetWorkloadAccessToken (agent-only, no user), GetWorkloadAccessTokenForJWT (user, from a JWT), GetWorkloadAccessTokenForUserId (user, from an opaque string). Spend it to pull the real credential out of the Token Vault. GetResourceOauth2Token for OAuth workflows, GetResourceApiKey for API keys, passing the workload access token as workloadIdentityToken. The authorization-code (3LO) workflow inserts one detour into step 3. If the provider token isn’t in the Vault yet, GetResourceOauth2Token returns an authorizationUrl instead of an accessToken. The user consents, your session-binding endpoint (b) calls CompleteResourceTokenAuth, and then step 3 is re-called, echoing sessionUri, until the accessToken appears. No other workflow has that detour. M2M, OBO, and API-key all return their credential on the first call. Who makes each call The two axes are independent. Runtime versus self-hosted decides who does steps 1 and 2. Decorator versus raw decides who does step 3, and the 3LO polling. Step 1 · workload identity Step 2 · workload access token Step 3 · fetch the credential Decorator · on Runtime Service-managed, auto Runtime mints and injects it; decorator reads it from context Decorator calls GetResource* and returns the credential to your function Decorator · no token in its context Decorator auto-creates one (CreateWorkloadIdentity) and caches its name in a local .agentcore.json Decorator mints it, with a fabricated user id Decorator calls GetResource* Raw API · on Runtime Service-managed, auto, or one you create yourself Read the injected token, or mint against your own workload identity (not the Runtime’s, that one’s blocked) You call GetResource* Raw API · self-hosted You call CreateWorkloadIdentity You call GetWorkloadAccessToken* You call GetResource* Two of those rows have more to them than fits in a cell: what to do when the Runtime injects nothing, and what the decorator does instead of failing. The exact calls, per workflow Every entry below is step 2 (mint) plus step 3 (spend) from the skeleton. The mint call is what you write self-hosted; on a Runtime it’s replaced by the injected token. Workflow Mint (self-hosted) Spend 3LO detour? Result field Authorization code (3LO) get_workload_access_token_for_jwt / _for_user_id (user-bound) get_resource_oauth2_token(oauth2Flow=\"USER_FEDERATION\", …) Yes. authorizationUrl → complete_resource_token_auth → re-poll accessToken Client credentials (M2M) get_workload_access_token (agent-only)¹ get_resource_oauth2_token(oauth2Flow=\"M2M\", …) No accessToken On-behalf-of (OBO) get_workload_access_token_for_jwt (user-bound) get_resource_oauth2_token(oauth2Flow=\"ON_BEHALF_OF_TOKEN_EXCHANGE\", …) No accessToken API key get_workload_access_token (agent-only)¹ get_resource_api_key(…) No apiKey ¹ At the API level, M2M and API-key need no user, since GetWorkloadAccessToken takes no user parameter. But the decorators don’t guarantee an agent-only token. They reuse whatever workload token is present, which is user-bound if the Runtime was invoked with a JWT or User-Id header, and always user-bound in local dev. If you specifically want an agent-only token, mint it yourself with GetWorkloadAccessToken. All the spend calls take the same two required arguments, resourceCredentialProviderName and workloadIdentityToken, plus oauth2Flow and scopes for the OAuth ones. And scopes is required even when you have none. Pass []. Omit it and the raw call fails with ParamValidationError: Missing required parameter in input: \"scopes\". The decorator hides this because the SDK always sends scopes, so it’s a trap only hand-rolled raw calls hit. I found it on an M2M call with no scopes. Each workflow’s raw code sits with the workflow: 3LO, M2M, API key, and the completion call your callback endpoint makes in the recipe. For OBO, see AWS’s on-behalf-of page, for the reasons given earlier. Naming note for all of them: parameters and response fields come from IdentityClient.get_token and get_api_key in services/identity.py, which forwards them verbatim to the bedrock-agentcore boto3 client. Every one of them is in the API reference if you want the full request and response shapes. The outbound mechanisms, compared Organized by what the target expects. The first three columns tell you when. The rest carry the operational attributes. Target expects Mechanism What triggers it User consent Credential provider Token Vault Refresh Nothing (network-only) Networking, not Identity n/a n/a n/a n/a n/a API key API-key provider @requires_api_key No Yes (API-key) Yes n/a (static) User token, start fresh Originate · 3LO auth_flow=\"USER_FEDERATION\" Yes (once) Yes Yes Auto (refresh token) User token, same audience Forward · passthrough header allowlist, no flow No No No None, user’s expiry User token, new audience Exchange · OBO oauth2Flow=\"ON_BEHALF_OF_TOKEN_EXCHANGE\" No (reuses prior) Yes Yes Re-exchange User token, under IAM inbound + User-Id header X-Amzn-…-Runtime-User-Id (as 3LO) (as chosen) Yes (as chosen) M2M token, AWS/IAM target Just sign it · SigV4 your execution role No No No n/a (IAM rotates) M2M token, OAuth target Client credentials · 2LO auth_flow=\"M2M\" No Yes Yes Auto (re-fetch) Refresh in plain terms: 3LO and M2M renew themselves silently, since AWS stores refresh tokens with roughly 30-day default lifetimes against 1 to 2-hour access tokens. Passthrough can’t renew, so when the user’s token dies the call dies. Plan long tasks accordingly. (Refresh behavior) When do you need your own workload identity? A Runtime or Gateway gets a service-managed one automatically, and most agents never create another. Four cases where you do: Self-hosted. Nothing created an identity for you, so you call CreateWorkloadIdentity. The SDK decorator will also do it unprompted whenever no workload access token reaches its context, which has its own hazards. On a Runtime that injects no workload access token. Bare IAM SigV4 with no User-Id header injects nothing, and the Runtime’s service-managed identity is blocked from minting a token for itself (WorkloadIdentity is linked to a service and cannot retrieve an access token by the caller). If the agent needs an outbound API key or an M2M token there, create an identity you can mint against. Verified code. To register a 3LO return URL up front. The service-managed identity doesn’t exist until the runtime is deployed, so declaring AllowedResourceOauth2ReturnUrl ahead of time means creating your own identity and minting against it explicitly. That trades the managed decorator path for the raw one. More here. To scope credential-provider access. Nothing binds an agent to a provider by default, so isolation is something you build: separate workload identities and separate execution roles, with each role’s Resource scoped to specific provider ARNs. The role is the IAM principal doing the scoping; the separate identities are what let the roles differ per agent. More here. Which mechanism do I use? Every branch below is a question about the target, not your taste. Figure 7. Which mechanism to use, as a decision flowchart. Orange means mint or broker a token, so credential provider plus Vault. Teal means reuse an identity you already hold. Grey means it isn’t an Identity problem at all. If the target is IAM-inbound but you still need user-scoped operations, layer the User-Id header on top. When it breaks: inbound or outbound? Start by asking which direction is failing, because the fixes have nothing in common. Symptom Likely direction First thing to check 403 / AccessDenied invoking your agent Inbound Caller’s IAM action (InvokeAgentRuntime), or JWT audience/client mismatch in the authorizer Caller’s JWT rejected at the door Inbound Discovery URL, allowedClients/allowedAudience, token expiry 3LO auth URL appears, then nothing returns Outbound Session binding. Is your endpoint (b) reachable and calling CompleteResourceTokenAuth? Not the auto-generated (a) URL you gave Google AccessDeniedException: Invalid or expired session on completion Outbound Wrong userIdentifier type. userToken for JWT inbound, userId for IAM plus User-Id (the rule) Downstream returns 401 / invalid_audience Outbound Wrong mechanism. Passthrough where the audience differs; use OBO GetResourceOauth2Token access denied Outbound IAM scoping of GetResourceOauth2Token to the workload-identity ARN Access denied when retrieving secret … Outbound Missing secretsmanager:GetSecretValue on the provider’s backing secret. The API reads it as your role Token works locally, fails deployed Outbound Local-versus-Runtime identity difference, random local user id Long task fails partway through Outbound Passthrough token expired mid-task. Switch to a refreshable flow WorkloadIdentity is linked to a service… Outbound You’re minting a workload token with a Runtime-managed identity. Use a self-created one AccessDeniedException: Workload Identity does not belong to caller account Outbound The workloadName you passed doesn’t exist in your account. Create it with create-workload-identity ParamValidationError: Missing required parameter … \"scopes\" Outbound Raw OAuth spend calls require scopes even when empty. Pass [] Decorator fabricates an identity on a Runtime that did inject a token Outbound Nothing put the header into the SDK context. With a BYO server, read it yourself, or check the header spelling: workloadaccesstoken and x-amzn-bedrock-agentcore-runtime-workload-accesstoken, hyphen included (read-or-mint) Downstream rejects an M2M token that looks valid Outbound Some IdPs key client-credentials on audiences rather than scopes. Auth0 wants the API identifier there (M2M) 3LO completes but the grant lands under no user Outbound You minted an agent-only workload access token instead of reading the injected user-bound one. 3LO and OBO can’t use a substitute (read-or-mint) When in doubt, AWS’s runtime auth page has the authoritative OAuth error reference. Edges and limits The unglamorous details that save you a support ticket later. Header allowlist: up to 20 headers per Runtime, each 4KB or less. Reserved x-amzn-* headers can’t be forwarded, except X-Amzn-Bedrock-AgentCore-Runtime-Custom-*. (Headers) Token lifetimes: access tokens commonly 1 to 2 hours, stored refresh tokens default to around 30 days. Tokens can be revoked provider-side without AgentCore knowing, so set force_authentication=True to force a clean re-auth. (Lifecycle) Per-agent provider access is opt-in. By default AgentCore enforces no binding between a workload identity and a provider, so any authorized caller can read any provider in the account. To restrict it, scope GetResourceOauth2Token and GetResourceApiKey in the role’s IAM policy to specific workload-identity and provider ARNs, and use Deny for hard guardrails. (Scope provider access) Quotas: credential-provider counts and other limits live in AgentCore Identity service quotas. Check them before designing for thousands of providers. Gateway visibility: with a Cedar policy (Cedar is AWS’s open-source authorization-policy language, the same one used by Verified Permissions), denied tools don’t even appear in tools/list, since “Tools that are denied by policies will not appear in the list.” With interceptors (Lambda), nothing is filtered unless you write a RESPONSE interceptor to do it. (Policy, Interceptors) FAQ What do you mean by an “AWS-credentialed process”? Any code running with AWS credentials available to it, the same thing the AWS CLI or an SDK needs to make a call. Your laptop after aws configure. A Lambda function or EC2/ECS task running under an IAM role. A CI job that has assumed a role. If it can call AWS APIs it can use AgentCore Identity’s outbound features. Nothing AgentCore-specific about it, and no Runtime required. Do I have to use the @requires_access_token decorator, or can I call the token APIs directly? Either, they’re two ways to do the same thing, and you pick one per code path rather than mixing them. Reach for the raw APIs when the decorator doesn’t fit: self-hosted code, another language, or when you want explicit control over the poll. The calls, in order. Is the inbound authorizer part of AgentCore Identity, or is Identity only outbound? Part of Identity. AWS calls inbound auth “powered by AgentCore Identity,” and the Identity terminology page defines the “OAuth 2.0 authorizer” as a term of art. The nuance is that you don’t create an authorizer as a standalone Identity object, you attach one (authorizerConfiguration) to a Runtime or Gateway. The outbound pieces, workload identities, credential providers, and the Vault, are standalone Identity resources, which is why Identity gets mistaken for outbound-only. (Runtime concepts, terminology) Does AgentCore Identity require an end-user identity? No. A chain with no human in it anywhere uses Identity end to end, with tokens vaulted agent-only. User identity is something you opt into. Do I have to build and deploy a separate server just to handle the 3LO redirect? Only for endpoint (b), never for (a), and the split is dev versus production rather than Runtime versus self-hosted. It doesn’t have to be a dedicated server either; a single route in the web app that already fronts your agent is enough. (More here) My Runtime uses IAM inbound. Can I still run a 3LO flow for my users? Yes. The managed way is the User-Id header. The DIY way is to pass a user id in the request payload and implement the OAuth flow yourself, at which point token storage, encryption, refresh and per-user scoping all become yours to build and secure. How do I get the end-user’s id inside my agent? First check whether you actually need it, because for identity and credential work you usually don’t. The runtimeUserId you pass on invoke is for the platform: it scopes the Vault, so @requires_access_token and GetResourceOauth2Token already return that user’s token automatically. You only need the raw id for your own logic, like per-user lookups or logging. When you do, you have to supply it yourself. The reserved X-Amzn-Bedrock-AgentCore-Runtime-User-Id header is consumed server-side and never reaches your container. I verified it’s absent from the request, and you can’t allowlist it, because the API rejects reserved x-amzn-* headers with a 400. Two ways to pass it: put it in the request payload, which is simplest since the caller already knows it, or send it as a custom allowlisted header X-Amzn-Bedrock-AgentCore-Runtime-Custom-UserId, since the …-Custom-… prefix is allowlist-able. You cannot recover it from the injected workload access token, which is an opaque KMS-encrypted blob. And both hand-passed values are unverified, exactly like runtimeUserId itself. If you need a cryptographically verified user id in the container, use JWT inbound and read the token’s sub, forwarding Authorization via the allowlist. If you’re starting today Five opinions, earned the hard way. Get inbound versus outbound straight before you write a line of agent code. Almost every confusion downstream traces back to blurring them. Inbound is a Runtime concern, a Gateway has its own for whoever calls it, and outbound works anywhere. Let the target choose the mechanism. The external system’s auth method is a hard constraint, not a preference. Identify it first (nothing, key, user token, machine token) and your options usually collapse to one. Then optimize for simplicity within what’s left. Inside AWS with no user identity? Just sign it. For user data, budget for session binding. It’s the step that turns a 30-minute 3LO demo into a half-day. Stand up the callback endpoint first, before the agent. Treat the User-Id header as a last resort in production. If you can use JWT inbound, do. Verified identity beats a trusted-by-IAM string. And one more, free: test the deployed path. Local runs use a fabricated identity and a fabricated user, so a green laptop test tells you your syntax is right and almost nothing else. Most of what’s here took a test run or a wrong turn to find out, which is the only reason it’s written down. If you’re building agents that have to act securely on behalf of real users and this saved you an afternoon, that was the point. We do this for a living at Loka. If you’re wrestling with an agent architecture, talk to us. Further reading Supported authentication patterns (3LO / M2M / OBO) AgentCore Identity overview · terminology · key features (self-hosted/hybrid) Understanding workload identities · create & manage them · obtain credentials On-behalf-of token exchange Inbound & outbound auth (runtime) · inbound JWT authorizer OAuth2 authorization URL & session binding Google Drive 3LO tutorial · sample callback server (AWS docs link a stale path) Credential providers (OAuth / API key / payment) · OAuth2 vendor list Custom header allowlist · Scope credential provider access Get workload access token · InvokeAgentRuntime API Gateway core concepts · inbound auth · target outbound auth Use a gateway with policy (Cedar) · interceptors AgentCore Identity service quotas mcp-proxy-for-aws · Strands MCP tools AgentCore Python SDK source, worth reading directly when the docs are silent: identity/auth.py (the decorators, the DOCKER_CONTAINER branch, _set_up_local_auth) · services/identity.py (IdentityClient, get_token, get_api_key, TokenPoller) · runtime/context.py · runtime/app.py Test your understanding: the answers Each block links back to the section it came from, in case an answer doesn’t match what you had. Answers: the model Back to the questions 1. What’s the difference between inbound and outbound authorization? Inbound is who may invoke your agent, enforced by the authorizer on a Runtime or Gateway. Outbound is how your agent proves itself to everything it calls, and it works from any process with AWS credentials. They never consult each other, so any combination is legal, and they touch at exactly one point: user identity. (Section) 2. What are the core primitives and what’s the purpose of each one? Three on the outbound side, and the useful axis is who provisions them. The Agent Identity Directory is the per-account registry of workload identities, created automatically. Credential providers describe how to authenticate to an external service, and they’re always yours to create. The Token Vault is encrypted storage for the credentials themselves, keyed by agent plus user, provisioned for you. The inbound authorizer sits alongside them, part of Identity but not a standalone resource. (Section) 3. What are the three kinds of token and what is each one used for? The inbound JWT is what the caller presents in order to invoke your agent, issued by the caller’s IdP, identifying the caller; your agent is the resource server and validates it. There is none when inbound is IAM. The provider access token is what your agent presents to the outbound system, issued by that external service, and it’s what the Vault stores; your agent is the client in that exchange. The workload access token is the key your agent uses to get the provider access token out of the Vault, issued by AWS, representing your agent bound to a user when there is one, and usable against AgentCore’s own services only. (Section) Answers: where your agent runs Back to the questions 1. What are the Runtime’s three jobs, and which do you take over? It validates the caller and extracts an identity, resolves your agent’s workload identity, and mints a workload access token binding those two together and injects it as a request header. Self-hosted you take over all three: no authorizer exists, you create the workload identity with CreateWorkloadIdentity, and you assert user identity through GetWorkloadAccessTokenForJWT or GetWorkloadAccessTokenForUserId. Everything past those three steps behaves identically either way. (Section) 2. Which inbound configurations inject a token, and which is the default? JWT authorizer: injected. IAM SigV4 plus the X-Amzn-Bedrock-AgentCore-Runtime-User-Id header: injected, and the raw User-Id header is consumed server-side rather than forwarded. Bare IAM SigV4 with no User-Id: nothing is injected. That last one is the Runtime default, so the out-of-the-box configuration is the one that gives your agent nothing to spend at the Vault. (Section) 3. What does the decorator do with no token, and why can that happen in production? It fabricates an identity rather than failing. It checks DOCKER_CONTAINER, and unless that’s \"1\" it calls CreateWorkloadIdentity, invents a random user id, and caches both in .agentcore.json. Nothing in that decision looks at where the code is running, so it fires in production in two cases: a bring-your-own FastAPI or Flask server, where the header arrives but nothing puts it in the SDK’s context, and an SDK-served Runtime under bare SigV4. A broad IAM role makes it silent. (Section) Answers: inbound Back to the questions 1. What are the four inbound options, and what does a JWT authorizer check? IAM SigV4 (the default), IAM plus the User-Id header, JWT bearer, and offloaded (AUTHENTICATE_ONLY / NONE, Gateway only). A JWT authorizer does two separable jobs: it takes iss and sub to build the caller identity that outbound credentials later bind to, and separately it validates allowedClients, allowedAudience and scopes against the token’s client_id, aud and scope to decide whether the call is allowed in at all. (Section) 2. What are your options when one agent needs two kinds of caller? A Runtime supports either IAM SigV4 or JWT, never both at once, and a JWT authorizer points at exactly one IdP. So you front the agent with more than one authorizer: multiple versions of one Runtime, since authorizerConfiguration is frozen into each immutable version, or multiple Runtime instances from the same container image. You don’t need to split for multiple clients or audiences sharing one IdP, since allowedClients and allowedAudience are lists. You do need to split for multiple IdPs. (Section) Answers: outbound and API keys Back to the questions 1. What are the four things a target can expect? Nothing, where the network is the auth. A static API key. A user’s access token. Or a machine (M2M) token. The first two involve no identity at all. The target picks, not you. (Section) 2. When is your agent the client and when the resource server? It depends on which resource is being accessed, not on the component. Reaching into a user’s Google Drive, your agent is the client: it holds a token and presents it to someone else’s API. Serving a chat front end that calls it with a token from your own IdP, your agent is the resource server: it holds the protected thing and validates a token before serving it. Same agent, same deployment, same user. That’s the inbound and outbound split in OAuth vocabulary. (Section) 3. Which two IAM permissions does a Vault read require? bedrock-agentcore:GetResourceApiKey or GetResourceOauth2Token, plus secretsmanager:GetSecretValue on the backing secret, because the credential physically lives in a Secrets Manager secret that the AgentCore API reads as your role. The AgentCore-generated role includes neither. (Section) 4. What binds an agent to a credential provider? Your IAM policy, and nothing else. AWS states the service “does not enforce additional binding between workload identities and credential providers in the same account,” so scoping the Resource blocks isn’t hardening layered on a default restriction, it is the restriction. (Section) Answers: 3LO and passthrough Back to the questions 1. What are the two callback URLs? (a) The IdP redirect URL is hosted by AWS, arrives as the callbackUrl field in the create-oauth2-credential-provider response, and is the only URL you register at Google. You build and deploy nothing for it. (b) The session-binding endpoint is hosted by you, a route in your own web app, registered with AgentCore on the agent’s workload identity and passed as the decorator’s callback_url. Google never sees (b). The post-consent redirect is a two-hop chain: Google to (a), then AgentCore to (b). (Section) 2. What is the sequence of API calls in a 3LO flow? Your agent makes two, and your callback endpoint makes a third. Read the injected user-bound workload access token (or mint one self-hosted), then call GetResourceOauth2Token with oauth2Flow=\"USER_FEDERATION\" and resourceOauth2ReturnUrl pointing at endpoint (b). On a first connect that returns an authorizationUrl and a sessionUri instead of a token. After consent, endpoint (b) calls CompleteResourceTokenAuth(sessionUri, userIdentifier), which writes the token into the Vault, and your agent’s re-call with the echoed sessionUri finally returns an accessToken. (Section) 3. What is session binding and which attack does it prevent? It’s the check that the person finishing consent is the person the flow was started for. Without it, Mallory starts a flow as himself, sends the authorization URL to Alice, and her token gets filed under Mallory’s agent-plus-user slot. It’s the OAuth cousin of session fixation. AWS enforces that your userIdentifier matches the flow’s originator, but that only means something if you source the identifier from the live browser session rather than from your own records, and AWS’s own sample callback server sources it from records. (Section) 4. What is your agent doing while it waits? Polling, in a live loop. There’s no suspend, checkpoint or continuation: the wrapper sits in a while loop calling GetResourceOauth2Token until a token appears, and your function body hasn’t started. So a human is inside your invocation’s timeout, and only on first consent. (Section) 5. When is passthrough right, and what’s its limit? When you already hold the user’s token and the target accepts that exact token, same IdP and same audience, which usually means you own both ends. The hard limit is that the token carries the user’s expiry and you can’t refresh it, because it isn’t yours. It also requires the token to have arrived inbound as a JWT, which rules it out under IAM inbound. (Section) Answers: OBO and the User-Id header Back to the questions 1. What’s the difference between passthrough and OBO? Audience. Passthrough forwards the user’s token unchanged, so it only works where the downstream trusts the same IdP and the same audience. OBO exchanges it for a brand-new token minted for the downstream’s own audience, with no second consent and no browser, and the exchanged token carries both the user’s and the agent’s identity. The moment a downstream rejects your token’s audience, passthrough is dead. OBO replaces it only where the downstream’s authorization server will perform the exchange, which in practice means an IdP you can configure a trust in. Where it won’t, as with Google or Slack, OBO isn’t available and 3LO is the fallback. (Section) 2. Which part of OBO is AgentCore’s and which is your IdP’s? AgentCore only brokers: it takes the inbound token plus the client credentials stored in the credential provider, submits the exchange request, parses the response, and returns it. Your authorization server makes the final call, including whether to permit the delegation at all, and it has to implement RFC 8693 token exchange or RFC 7523 jwt-bearer itself. AWS ships turnkey OBO for MicrosoftOauth2 only; everything else is CustomOauth2 with configuration you own. (Section) 3. What is the User-Id header for, and why can’t you read it? It’s a mint input, not data for your code. Under IAM inbound the caller is an IAM principal, so AgentCore can’t tell Alice’s request from Bob’s; the header supplies the missing identity and rides the GetWorkloadAccessTokenForUserId on-ramp. The Runtime consumes it server-side and injects the resulting token instead, so the raw header never reaches your container, and you can’t force it through the allowlist because reserved x-amzn-* headers are rejected at deploy time. It’s unverified, so prefer JWT inbound in production. (Section) Answers: machine tokens and the plumbing Back to the questions 1. What are the two M2M flavors? The target decides. If the downstream is AWS-hosted and IAM-authed, sign the request with your execution role’s credentials: no OAuth, no provider, no Vault. If the target validates OAuth tokens instead, use the client-credentials grant through a credential provider, auth_flow=\"M2M\", and watch the audiences argument, since some servers key client-credentials on audience rather than scopes. (Section) 2. What is the workload access token and what can’t you do with it? An AWS-signed, opaque token representing your agent’s workload identity, bound to a user when there is one, whose only job is to authorize your agent against AgentCore’s own first-party services. You can’t call an external service with it, and you can’t read anything out of it: it’s an AWS Encryption SDK message whose body is wrapped by a KMS key in an AWS-service-owned account, so the user id isn’t recoverable client-side. (Section) 3. What are the three mint APIs and what picks between them? The identity you’re holding. GetWorkloadAccessTokenForJWT when you have the user’s JWT, GetWorkloadAccessTokenForUserId when you have an opaque user id, and GetWorkloadAccessToken when there’s no user at all, which returns an agent-only token. On a Runtime the platform makes one of the first two calls for you and injects the result, so you read it instead of minting. (Section) 4. Nothing was injected. What now? It depends on the credential. For an API key or M2M, both agent-only, mint an agent-only token against a workload identity you created yourself. For 3LO, OBO or passthrough, all user-scoped, there is no substitute: an agent-only token names no user, so there’s no agent-plus-user row in the Vault for it to reach. Fix the inbound path instead. (Section) 5. What’s the pipeline with both conveniences removed? CreateWorkloadIdentity → GetWorkloadAccessToken* → GetResource{Oauth2Token,ApiKey}, with CompleteResourceTokenAuth bolted on for the one workflow that needs human consent. The Runtime spares you the first two steps, the decorator spares you the third plus the 3LO poll. One extra rule: the Runtime’s own service-managed identity is blocked from minting, so minting from inside a Runtime has to be against an identity you created. (Section)"},{"href":"/esmc-trainium2/","title":"Scoring 42 Million Protein Variants a Day on AWS Trainium2","subtitle":"A native PyTorch benchmark for an open-weight protein language model","description":"A native PyTorch benchmark showing EvolutionaryScale ESMC-300M running on AWS Trainium2: 490.8 variants per second on a single trn2.3xlarge — approximately 42.4 million protein variants scored per day at approximately $1.26 per million, 60% below H100 in this fixed-shape D2Deep benchmark.","abstract":"ESMC-300M scored 490.8 protein variants per second on one trn2.3xlarge at batch size 16, with ROC-AUC 0.8525 and estimated cost of $1.26 per million variants on this fixed-shape D2Deep evaluation.","tags":["ESM-C","AWS Trainium","Protein Language Models","Benchmarking"],"topics":["trainium","biomedical-ai","benchmarks"],"authors":["João Correia","Telmo Felgueira","Tiago Gonçalves","Bojan Jakimovski","Jim Burtoft","Louise Ping"],"text":"Introduction Protein variant effect prediction is a core problem in computational biology. Every human protein can be altered by thousands of single-amino-acid substitutions. Some cause disease. Most do not. Distinguishing the two, at scale, underpins therapeutic target selection, clinical variant interpretation, and personalized medicine pipelines. The traditional approach is expensive and slow: wet-lab deep mutational scanning, computational homology modeling, or population-scale gnomAD[1] lookups. Protein language models[2] changed the economics. A model trained on hundreds of millions of natural protein sequences learns, implicitly, which amino acids are tolerated at each position and which are not. A substitution that is unlikely under the model’s learned distribution can be associated with reduced functional tolerance, while a score close to wild type can be consistent with benign variation. These scores are useful evidence, not clinical diagnoses. ESMC-300M[3], from EvolutionaryScale[4], is a strong open option for this task. It is an encoder-only model of the ESM-C family[5], trained on sequences from UniRef[6], MGnify[7], and JGI[8]. The weights are public, the architecture is a standard bidirectional Transformer, and zero-shot variant scoring needs no fine-tuning. Trainium2 gave us exactly what we wanted to see. ESMC-300M ran cleanly on a single trn2.3xlarge and reached 490.8 variants per second. That works out to approximately 42.4 million protein variants scored per day on one small Trainium2 instance. The cost story is just as important. At that throughput, Trainium2 comes in at approximately $1.26 per million variants scored, compared with $3.17 on H100. That is 60% lower cost per million variants, or about 2.5× more variants for the same accelerator budget. The key model-side compatibility change was to turn off Flash Attention so the model could use the standard attention path supported by Trainium2. After that, ESMC-300M ran without a model rewrite. We evaluated on D2Deep[10]: 125,190 human protein variants (109,700 benign, 15,490 pathogenic), scored zero-shot using the log-probability delta between the mutant and wild-type amino acid in context. The four-logical-NeuronCore configuration with batch=16 reaches 490.8 samples/s at approximately $1.26 per million samples scored, 60% lower cost than H100 at higher measured throughput in this fixed-shape benchmark. What makes ESMC different ESMC is encoder-only: bidirectional attention over all residues simultaneously, no decode loop, no KV (Key-Value) cache[12]. For variant scoring, that is exactly what you want. One forward pass per variant: feed in the wild-type sequence, read log-softmax at the mutation position, compute the delta[2]. No generation, no sampling. The architecture is a standard bidirectional Transformer with rotary positional embeddings (RoPE), SwiGLU feed-forward layers[13], and a 33-token protein vocabulary. ESMC-300M loads in ~0.6 GB at bfloat16 and runs efficiently at batch=1—the natural shape for single-variant scoring. Model Layers Hidden Heads Parameters Weight size ESMC-300M 30 960 15 ~300M ~0.6 GB (bfloat16) ESMC-600M 36 1152 18 ~600M ~1.2 GB (bfloat16) Table 1. ESM-C model dimensions. The key Neuron compatibility requirement is disabling Flash Attention. ESMC uses Flash Attention[14] by default; passing use_flash_attn=False at load time switches to standard scaled-dot-product attention, which compiles cleanly. It is easy to miss and blocks compilation if overlooked. The esm_neuron package in this repository handles it automatically. Scale performance, not cost with AWS Trainium2 In this benchmark we focus on the low-batch regime: scoring inside a latency-bound or sequential loop, such as interactive scoring behind an API, agentic tool calls that request one score and wait, or RL-guided design like LatProtRL, where each step depends on the previous reward. Here batch size stays low by design, and per-request turnaround matters more than saturating the hardware. This is where Trainium2[15] fits naturally. A trn2.3xlarge gives one Trainium2 chip with four logical NeuronCores (eight physical NeuronCore-v3 paired into four under the default LNC=2 configuration) and 96 GB of accelerator memory. The one-day São Paulo Capacity Block reservation rate used here is $2.235/hour[16]. The reported full D2Deep evaluation—125,190 variants—completes in around 255 seconds. At that rate, one trn2.3xlarge can score approximately 42.4 million variants per day. ESMC’s encoder architecture maps well onto Trainium2. Unlike autoregressive generation—where each token depends on the last and the model runs N times per sequence—ESMC does one forward pass per sample with fully static shapes once sequence length is fixed. Static shapes are exactly what the Neuron compiler[17] is designed for. Setup We ran the Trainium2 experiments on a single trn2.3xlarge (4 logical NeuronCores, 96 GB accelerator memory). Four Docker workers ran in parallel, each pinned to one NeuronCore via NEURON_RT_VISIBLE_CORES, processing a quarter of the D2Deep dataset independently. The model ran through native PyTorch[9] on the Neuron backend (TorchNeuron[11], in beta at the time of writing). For the H100 comparison, we used the same ESMC checkpoint, scoring procedure, D2Deep inputs, sequence length (512), and batch size (16). This is an application-level comparison for the stated workload and shape, not a claim that one accelerator is universally faster across models or batch sizes. Component Setting Instance trn2.3xlarge Chip 1 Trainium2 chip Runtime PyTorch 2.11.0, Native PyTorch Neuron DLC (TorchNeuron, beta) Compiler NEURON_CC_FLAGS=--target trn2 --model-type transformer Compile strategy Regional (transformer blocks compiled individually) Batch size 16 (headline configuration; the batch=1 results use the same setup at batch size 1) Sequence length 512 tokens (fixed shape) Model ESMC-300M, bfloat16, use_flash_attn=False D2Deep variants 125,190 (109,700 benign / 15,490 pathogenic) Table 2. Experimental setup configuration. Results and analysis The headline result is compatibility and quality. ESMC-300M compiled cleanly on Trainium2 with no model rewrite. Quality was effectively identical to the CUDA baseline in this evaluation: ROC-AUC 0.8525 on Trainium2 versus 0.8524 on H100. The 0.0001 difference is small, but we do not attribute it to a single numerical cause without a dedicated reproducibility study. Full-instance throughput With four logical NeuronCores in parallel, the full-instance throughput is 490.8 samples/s, versus 414.0 samples/s on H100: 18.6% higher throughput for this model, sequence length, batch size, and scoring procedure. Hardware Config Throughput ROC-AUC Trainium2 trn2.3xlarge 4×logical NeuronCore, batch=16 490.8 samples/s 0.8525 H100 p5.4xlarge 1 GPU, batch=16 414.0 samples/s 0.8524 Trainium2 trn2.3xlarge 4×logical NeuronCore, batch=1 279.4 samples/s 0.8525 H100 p5.4xlarge 1 GPU, batch=4 136.5 samples/s 0.8524 RTX 5060 Ti 1 GPU, batch=16 77.7 samples/s 0.8524 H100 p5.4xlarge 1 GPU, batch=1 35.9 samples/s 0.8524 Table 3. D2Deep throughput and ROC-AUC by hardware configuration. Figure 1. D2Deep throughput across hardware configurations. Trainium2 4×logical NeuronCore at batch=16 and H100 at batch=16 are the key comparison: 18.6% higher throughput on Trainium2 at approximately 60% lower cost per million samples. Per-unit comparison at batch=1 Metric Value Trainium2 logical NeuronCore (batch=1) 69.9 samples/s H100 GPU (batch=1) 35.9 samples/s Trainium2 p50 latency (batch=1) 15.2 ms H100 GPU p50 latency (batch=1) 27.1 ms Per-unit advantage 1.95× Trainium2 Table 4. Per-unit comparison at batch=1. At batch=1, a single Trainium2 logical NeuronCore scores 69.9 samples/s (279.4 ÷ 4) versus 35.9 samples/s on H100. The Trainium2 logical NeuronCore is 1.95× faster per unit at batch=1 in this run. The result suggests better utilization for this small, fixed-shape encoder workload; profiling would be needed to attribute it to a specific hardware subsystem. Figure 2. Per-unit throughput at batch=1: one Trainium2 logical NeuronCore vs one H100 GPU. Batch scaling Although this benchmark focuses on the low-batch regime, it is useful to understand how both Trainium2 and H100 scale when looking for maximum throughput in bulk operations. In general, for these cases, the practical choice is the largest batch size that fits the memory budget. On H100, throughput scales 3.8× from batch=1 to batch=4 and 3.0× from batch=4 to batch=16, for an overall 11.5× increase from batch=1 to batch=16. The highest batch size we can still fit in H100 is batch=256, and with this size we see a throughput of 998 samples/s, an increase of 2.4× from batch=16. At this batch size we can already start seeing significant diminishing returns on increasing the batch size, but it still results in a higher value for the throughput. Conversely, on Trainium2, our tests show that batch=16 is the practical sweet spot for this workflow, with only small throughput increases at higher batch sizes. In terms of raw throughput for bulk operations, H100 still has the higher potential, at a higher cost; Trainium2 can still be heavily optimized through kernel development. In the low-batch regime, Trainium2 is already the clear winner. Figure 3. Batch scaling for ESMC-300M D2Deep. H100 throughput grows 11.5× from batch=1 to batch=16 and reaches 998 samples/s at batch=256. Trainium2 (4 logical NeuronCores) is shown at the batch sizes measured here; batch=16 is its practical sweet spot for this workload. Cost-normalized throughput Metric Value Trainium2 cost / M samples (batch=16) ~$1.26 H100 cost / M samples (batch=16) ~$3.17 Cost advantage (batch=16) ~60% lower cost/M; 2.5× more samples/$ H100 cost / M samples (batch=256) ~$1.31 Cost advantage (batch=256) ~4% lower cost/M; 1.04× more samples/$ Hourly reservation rate, Trainium2 vs H100 $2.235 vs $4.720 Table 5. Cost-normalized throughput. Both rates are one-day EC2 Capacity Blocks for ML in São Paulo (sa-east-1), captured on August 6, 2026[16][18]: trn2.3xlarge at $2.235/hour and p5.4xlarge at $4.720/hour. Capacity Block prices are reservation prices and can change at purchase time; the calculations below use the accelerator reservation rate and exclude any non-Linux OS or ancillary charges. At batch=16, Trainium2 delivered 490.8 samples/s versus 414.0 on H100, while costing approximately 60% less per million samples ($1.26 versus $3.17). At maximum batch, cost per sample converges (~$1.26 vs ~$1.31): H100 wins on absolute throughput, but Trainium2 is still slightly more cost-effective. Hardware Config Throughput Hourly cost Cost / M samples Trainium2 trn2.3xlarge 4×logical NeuronCore, batch=16 490.8 samples/s $2.235 ~$1.26 Trainium2 trn2.3xlarge 4×logical NeuronCore, batch=1 279.4 samples/s $2.235 ~$2.22 H100 p5.4xlarge 1 GPU, batch=16 414.0 samples/s $4.720 ~$3.17 H100 p5.4xlarge 1 GPU, batch=256 998.0 samples/s $4.720 ~$1.31 Table 6. Hourly cost and cost per million samples by configuration. Figure 4. Cost per million samples scored. At batch=16, Trainium2 scores more samples per second than H100 at approximately 60% lower cost per million; at maximum batch the two converge. The bottom line: for this low-batch regime, Trainium2 is the more cost-effective option by far. At these measured rates, $2.235/hour on Trainium2 produces 490.8 samples/s, while $4.720/hour on H100 produces 414.0 samples/s—approximately 2.5× more samples per dollar on Trainium2. Even at maximum batch, Trainium2 is still the slightly more cost-effective option. Why this matters for healthcare and life sciences Protein variant effect prediction feeds clinical variant interpretation, therapeutic target prioritization, and personalized medicine pipelines. ClinVar[19] holds millions of variant submissions. AlphaMissense[20] scored every human missense variant. The computational infrastructure to do this at population scale, inside a secure AWS environment, is increasingly important for healthcare and life sciences teams. ESMC and Trainium2 together close a common gap: open model, Trainium2 infrastructure, predictable cost. The model is open. The weights are public. The scoring approach needs no fine-tuning and no labeled training data. And now it runs on the same accelerator infrastructure teams already operate in their AWS environment, at a predictable per-sample cost. For teams at pharma companies, diagnostics labs, and clinical AI startups, the relevance is direct. Scoring every variant in a target protein before a clinical trial takes minutes on a trn2.3xlarge. A whole-proteome run depends on the variant set and sequence lengths; at approximately 42.4 million samples per day, tens or hundreds of millions of variants are measured in days on one instance and can be split across multiple instances when turnaround matters. Where Loka fits: taking strong open protein models, making them run on AWS infrastructure, measuring them carefully, and turning the results into evidence that holds up to procurement and security review. This benchmark is exactly that. Conclusion At batch=1, a Trainium2 logical NeuronCore is 1.95× faster per unit than H100 in this benchmark. At batch=16, four logical NeuronCores delivered 490.8 samples/s versus 414.0 samples/s on H100 (+18.6%) at sequence length 512. Using the measured Capacity Block rates, that is approximately $1.26 versus $3.17 per million samples—60% lower cost per million, or 2.5× more samples per dollar. At the maximum batch size, H100 can deliver 998 samples/s. Even then, this is approximately $1.26 versus $1.31 per million samples. In conclusion, when it comes to the low-batch, low-latency regime, Trainium2 is the clear winner. In the high-batch regime, the two converge. To further drive performance gains, our next steps will focus on NKI kernel development and targeted profiling. This work will help us identify and capture additional computational margins, further optimizing the scoring pipeline beyond the efficiencies already achieved with torch.compile. If you are building protein variant scoring pipelines on AWS and need them production-shaped, reach out to Loka. This is exactly the problem we work on. Citation @misc{loka_esmc_trainium2_2026, title = {Scoring 42 Million Protein Variants a Day on AWS Trainium2}, author = {Jo\\~{a}o Correia and Telmo Felgueira and Tiago Gon\\c{c}alves and Bojan Jakimovski and Jim Burtoft and Louise Ping}, year = {2026}, month = {August}, url = {https://github.com/LokaHQ/esmc-neuronx} } References Karczewski, K. J., et al. (2020). The mutational constraint spectrum quantified from variation in 141,456 humans. Nature 581(7809), 434–443. doi.org/10.1038/s41586-020-2308-7. gnomAD browser: gnomad.broadinstitute.org Meier, J., et al. (2021). Language models enable zero-shot prediction of the effects of mutations on protein function. NeurIPS 2021. doi.org/10.1101/2021.07.09.450648 EvolutionaryScale (2024). ESMC-300M-2024-12 model card. huggingface.co/EvolutionaryScale/esmc-300m-2024-12 EvolutionaryScale (n.d.). Official website. evolutionaryscale.ai EvolutionaryScale (2024). ESM Cambrian. evolutionaryscale.ai/blog/esm-cambrian The UniProt Consortium (n.d.). UniRef: UniProt Reference Clusters. uniprot.org EMBL-EBI (n.d.). MGnify: microbiome data resource. ebi.ac.uk/metagenomics Joint Genome Institute (n.d.). JGI Genome Portal. jgi.doe.gov Ansel, J., et al. (2024). PyTorch 2: Faster Machine Learning Through Dynamic Python Bytecode Transformation and Graph Compilation. ASPLOS 2024. arxiv.org/abs/2306.09075 Tzavella, K., et al. (2024). Combining evolution and protein language models for an interpretable cancer driver mutation prediction with D2Deep. Briefings in Bioinformatics 26(1), bbae664. doi.org/10.1093/bib/bbae664 AWS (2026). Native PyTorch for AWS Trainium (TorchNeuron). Accessed August 2026. awsdocs-neuron.readthedocs-hosted.com/en/latest/frameworks/torch/pytorch-native-overview Shazeer, N. (2019). Fast Transformer Decoding: One Write-Head is All You Need. arxiv.org/abs/1911.02150 Shazeer, N. (2020). GLU Variants Improve Transformer. arxiv.org/abs/2002.05202 Dao, T., et al. (2022). FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. NeurIPS 2022. arxiv.org/abs/2205.14135 AWS (2024). AWS Trainium and Trainium2. aws.amazon.com/ai/machine-learning/trainium AWS (2026). Amazon EC2 Capacity Blocks for ML pricing. Accessed August 2026. aws.amazon.com/ec2/capacityblocks/pricing AWS (2024). AWS Neuron SDK documentation. awsdocs-neuron.readthedocs-hosted.com AWS (2026). Amazon EC2 instance types by Region. Accessed August 2026. docs.aws.amazon.com/ec2/latest/instancetypes/ec2-instance-regions NCBI (n.d.). ClinVar. ncbi.nlm.nih.gov/clinvar Cheng, J., et al. (2023). Accurate proteome-wide missense variant effect prediction with AlphaMissense. Science 381(6664). doi.org/10.1126/science.adg7492 Jakimovski, B. and Loka Applied Research (2026). Running Hugging Face Carbon on AWS Trainium2 with NxD Inference. github.com/LokaHQ/carbon-neuronx-distributed-inference"},{"href":"/a-prompt-pointed-the-other-way/","title":"A Prompt, Pointed the Other Way","description":"Everything is buildable now. Every team I meet lives in the same climate: more ideas than quarters to test them in, more tools than problems, roadmaps that read like wish lists because nothing on them is technically…","abstract":"Everything is buildable now. Every team I meet lives in the same climate: more ideas than quarters to test them in, more tools than problems, roadmaps that read like wish lists because nothing on them is technically…","tags":["Product Design","Design Thinking","AI","Workshop Facilitation","Product Development"],"topics":[],"authors":["Ana Marković"],"text":"Everything is buildable now. Every team I meet lives in the same climate: more ideas than quarters to test them in, more tools than problems, roadmaps that read like wish lists because nothing on them is technically impossible anymore. Ideas were never scarce, and lately neither is making. What got scarce is convergence — a room full of capable people actually landing, together, on what to build, for whom, and why this and not the ten-thousand other things. Three acts follow, as attempts to buy that back — and they rise the way acts should, toward the one part no method can reach. Act I: Zenith Design Sprint A client of ours — let’s call them Zenith for the purpose of this blog — started as a sketch. A founder arrived with just an idea, and it was up to us to lay down the steps we’d have to march to bring it to life. A design sprint is exactly what the name promises: a deliberately short distance, run flat out, shoulder to shoulder. The distance is the trick — a team can only run all-out when it can see the finish line from the start. And the shoulders matter just as much, because despite the first word of its name, this was never a designer-only sport. The room holds the whole company in miniature: engineers, founders, designers — whoever owns the problem — and nobody gets to spectate. Early on, anything goes — rough sketches from engineers, doubts from the founder, the idea no one would risk in a normal meeting. Teams rarely run out of ideas, they run out of decisions. So the course is staked with them. At marked points the group chooses, at speed: sticker votes, dots piling up, one direction taken, the rest left behind on the record and without a fight. And what waits at the finish line is not a report or a slide deck. It is a prototype — a film set of a product — put in front of real users, so that reality gets a vote while being wrong is still cheap. That is the sprint’s real trade: the momentum of a hackathon aimed at the one thing hackathons never produce — a decision the whole team believes in, because the whole team ran it down. Zenith is live today. It has paying users. And underneath all of it — the product, the revenue, the users — the first artifact in the chain is still a pencil sketch. Act II — The orchestrated brain dump The sprint’s success creates its own temptation, which is to declare it. The Answer — run the same framework for everyone, laminate the agenda, retire the thinking. But a sprint assumes a particular shape of problem, and clients don’t arrive in one shape. Some arrive the way Zenith did — a founder, a drawing, a decision one good sprint away. Some arrive as a scale-up with three roadmaps and, on a good day, one company. Some arrive as an enterprise that doesn’t need another prototype at all; it needs forty people to mean the same thing when they say the word “priority”. These clients are not the same distance from a decision — they aren’t even running toward the same finish line. Run them all through the identical agenda anyway and you haven’t been rigorous. You’ve been convenient. Rigor is redesigning the race for the runner. So we did the most self-aware thing a design team can do: we got in a room in Lisbon and ran a workshop about workshops. The goal was practical: get everything we had learned from every client out of our heads, find the patterns in it, and turn those patterns into new workshop frameworks — so the next client who walked in wouldn’t get the default agenda. They’d get one built for them. A workshop, done right, is an orchestrated brain dump. The dump is not optional — people walk in already full: opinions, grievances, half-formed ideas, the roadmap they’d write if anyone asked. The only question is whether all of it lands into a structure or onto the floor. Orchestration is the difference: sequence, roles, time boxes, and a person whose job is friction. In Lisbon, the dump was every client type we’d actually met, every issue they’d brought versus the one they’d booked us for — and the structure it landed into was a map: client types against their real problems, problems against exercises, exercises against the scenarios where they earn their keep. Facilitator’s role What has vanished from a culture of endless, frictionless production is the “no”. Everything about how we work is optimized toward “yes”: tools that autocomplete, roadmaps that only grow, meetings engineered for agreement, machines that will generate a hundred versions of anything before anyone asks whether there should be one. We built ourselves a yes-machine, and the “no” lost its habitat. Designers have an old name for what went missing: negative space — the part you deliberately leave empty, which is the part that gives the whole thing its shape. A workshop is one of the few rooms left where the “no” is on the agenda. Some of it happens at the composing desk, map open — which exercises to run, which to leave in the drawer. The harder one lives in the room, and the facilitator’s real job is not to say it, but to help the room find it. The “no” is almost always already there. It sits buried under politeness and momentum. So the job looks like interruptions — the timer, the agenda, “let’s park that” — but it works like excavation: build the exact moment where the buried thing becomes sayable, and let someone in the room say it. A “no” found by the team lands differently than a “no” delivered from the front of the room. It stops being an objection and becomes a decision — a cut, the small kind, made at minute three so it doesn’t have to happen at month three. We built ourselves a yes-machine, and the “no” lost its habitat. Designers have an old name for what went missing: negative space — the part you deliberately leave empty, which is the part that gives the whole thing its shape. Act III — The Cards Which brings us to the newest thing on the table, the one arriving with the most hype — which is exactly why it needs the coldest introduction. The yes-machine has produced one brand-new, very specific epidemic. Everyone has AI now — it’s in the roadmap, the board deck, the job titles — and almost nobody can say which of their problems it actually maps to. The capability arrived before the use case. Teams don’t lack access to intelligence; they lack a structured way to figure out where it belongs — which corner of the workflow, which user pain, which product surface. There is, genuinely, no established method for that conversation yet. Left unstructured, it produces either paralysis or a chatbot. Usually a chatbot. So we went analog on purpose: a deck of cards. The AI Cards exist for exactly that missing conversation. The deck walks a room through the mapping the hype keeps skipping — on one side, the areas where AI can actually act; on the other, your problems, your users, your product surfaces. The joke writes itself: the antidote to infinite compute turned out to be printed card stock. But the analog is doing real work here. Cards make the option space finite and physical — you can hold a possibility, weigh it against another, and, critically, put it down. They also change the room’s posture: the session plays like a game and works like a method, a conversation starter with an agenda hidden in the shuffle. The truest description I have is that the deck is a prompt, pointed the other way. We’ve spent the last few years learning how to prompt the machines. This one prompts the humans — it takes “we should do something with AI,” the emptiest sentence in modern product work, and forces it through problems, users, and surfaces until what comes out the other side is a use case you could actually build, or the honest discovery that you don’t have one yet. Both outputs are wins. Only one of them used to cost a quarter to find out the hard way. The cut is still yours I’d love to end with the reassuring version. The one where the methodologies solve it, facilitation is the answer, we’ve all found the new job and it’s safe and pays well and comes with dental. The methods help you decide. They don’t hand you conviction. You can run the cleanest process of your career and still end up standing in front of four good directions with the actual choice sitting there unmade. Because the choice was never going to come from the process. The process clears the ground. Somebody still plants the flag, and the flag is heavy, and it’s yours. That’s the part that didn’t get cheaper. Building got cheap. Generating got free. The cut — this one, and I’ll own it when I’m wrong — costs exactly what it always did. The methods are an antidote to the noise. There is no antidote to the cut. We just built machines good enough at everything else that we can finally see it."},{"href":"/benchmarking-grok-4-3/","title":"Benchmarking Grok 4.3 on Amazon Bedrock Mantle vs. the xAI API: The Engineering Walkthrough with Loka","description":"The main post covers what we found: Grok 4.3 lands in the same 96–97% accuracy band on GSM8K whether you reach it through Amazon Bedrock Mantle or the first-party xAI API, and low reasoning effort captures most of the…","abstract":"A sequential benchmark of Grok 4.3 on Bedrock Mantle and the xAI API, covering all four reasoning-effort settings on the full GSM8K test split.","tags":["Grok","xAI","AWS","Amazon Bedrock","SpaceX"],"topics":["inference","benchmarks"],"authors":["Nina Cvetkovska","Bojan Jakimovski"],"text":"The Engineering Walkthrough The main post covers what we found: Grok 4.3 lands in the same 96–97% accuracy band on GSM8K whether you reach it through Amazon Bedrock Mantle or the first-party xAI API, and low reasoning effort captures most of the accuracy gain at a fraction of the latency and token cost of medium or high. This post covers how we ran it. If you want to reproduce the numbers or adapt the harness for your own workload, this is the companion piece. The concrete question behind the benchmark was simple: Does routing Grok 4.3 through Amazon Bedrock Mantle cost you anything in answer quality, latency, or reliability compared to the native xAI API? We ran the full GSM8K test split (1,319 grade-school math problems) through both provider paths at four reasoning-effort levels (none, low, medium, high), recording per-request streaming latency, output throughput, token usage, and failures. That is eight runs and 10,552 scored requests in total. The benchmark harness is open and the results are saved in the repo. This post walks through the setup, the exact commands, the output format, and the design choices that made the comparison clean. For the main findings (accuracy tables, latency charts, and the enterprise deployment read), see the main Loka write-up: The Many Paths to Grok 4.3. Why GSM8K We needed a dataset that was long enough to produce stable latency distributions (1,319 requests per run means the p95 figures mean something), short enough to complete in a single session without batching or parallelism, and one where answer correctness is unambiguous and automatable. GSM8K satisfies all three. The final #### answer format makes accuracy scoring a string comparison after normalization, with no LLM judge in the loop. The harness pulls the split directly from the raw JSONL files in the openai/grade-school-math GitHub repository, so there is no dataset-library dependency to pin. The math content also makes token budgets predictable. Each question fits in well under a hundred tokens, and answers are a few lines of working plus a numeric result. That keeps the benchmark from inflating latency through unusual output lengths and keeps costs bounded before you start. It also gave us a clean lens on Grok 4.3’s configurable reasoning effort: when the task is this uniform, any accuracy or latency difference between effort levels is easy to attribute. Tested Setup The measured runs used: Setting Value Bedrock model ID xai.grok-4.3 Bedrock endpoint Bedrock Mantle, us-west-2 (https://bedrock-mantle.us-west-2.api.aws/openai/v1) xAI model ID grok-4.3 xAI endpoint https://api.x.ai/v1 Reasoning efforts none, low, medium, high Dataset GSM8K test split, 1,319 questions Concurrency 1 (sequential) Max output tokens 4096 Streaming enabled Auth (Bedrock) AWS SigV4 via an SSO profile, signed for the bedrock-mantle service (bearer tokens also supported) Auth (xAI) Bearer token via XAI_API_KEY Sequential requests were a deliberate choice. Client-side concurrency is a real variable in production, but it conflates queue effects with the underlying provider infrastructure. Running one request at a time isolates the thing we were measuring: what does each provider’s serving path cost a single in-flight request? One more Grok-specific note on the setup: reasoning in Grok 4.3 is always active by design, and the reasoning.effort parameter controls the budget, with none disabling it. The harness sends ”reasoning”: {“effort”: “<level>”} in the request body on every run, including the `none` runs, where the value is passed through explicitly. It does not request reasoning summaries or encrypted reasoning content, so reasoning shows up only as a token count in the usage data, never as visible stream text. Bootstrap the Environment The repo uses uv for dependency management and requires Python 3.12 or newer. git clone https://github.com/NineCvet/grok-bedrock-xapi-benchmark.git cd grok-bedrock-xapi-benchmark uv sync This installs the four runtime dependencies: httpx (streaming HTTP client), boto3 (SigV4 signing via botocore), python-dotenv (loads the .env file), and tiktoken (token counting in the cost estimator). The dev group brings in pytest and ruff; uv run pytest and uv run ruff check scripts tests are the repo’s checks. Configure Authentication The benchmark script supports two auth modes for Bedrock Mantle and picks between them automatically: if a bearer key is present in the environment it uses that, otherwise it falls back to SigV4 request signing with whatever AWS credentials botocore can resolve. Bedrock: AWS SigV4 (what we used) Our runs used an AWS SSO profile. Log in, then pass the profile to the script through the standard `AWS_PROFILE` variable: aws sso login --profile loka-ml The harness signs each request with SigV4 for the bedrock-mantle service in the target region. The default endpoint is https://bedrock-mantle.<region>.api.aws/openai/v1; override it with BEDROCK_GROK_BASE_URL if you need to. Before spending anything, verify the auth path with --auth-debug. It builds and signs a request but never sends it: AWS_PROFILE=loka-ml uv run python scripts/benchmark_grok_latency.py \\ --provider bedrock \\ --auth-debug auth_mode=sigv4 base_url=https://bedrock-mantle.us-west-2.api.aws/openai/v1 region=us-west-2 sigv4_service=bedrock-mantle signed_header_names=Authorization, Content-Type, X-Amz-Date, X-Client-Request-Id Bedrock: bearer token If you have a Bedrock API key instead, set BEDROCK_GROK_API_KEY (or AWS_BEARER_TOKEN_BEDROCK); when either is present it takes precedence over SigV4 and the script sends a plain Authorization: Bearer header. The same --auth-debug command confirms which mode is active. xAI API There is no committed env template; create a .env in the repo root with your key: cat > .env <<'EOF' XAI_API_KEY=xai-your-key-here EOF The script loads it automatically at startup. The default endpoint is https://api.x.ai/v1, overridable with XAI_BASE_URL. The .env file is excluded from version control. Never commit it. Estimate Cost Before Running The repo has a standalone estimator that downloads the GSM8K split, counts input tokens with tiktoken, and projects cost from a configurable output-token budget: uv run python scripts/estimate_grok_eval_cost.py \\ --dataset gsm8k \\ --split test \\ --model xai.grok-4.3 \\ --visible-output-tokens 512 \\ --reasoning-output-tokens 1024 \\ --output-dir result/cost-estimates Its output (this is the real pre-run estimate saved in the repo): | Model | Samples | Avg input tok | P95 input tok | Output tok/sample | Standard cost | Batch cost | | -------------- | ------: | ------------: | ------------: | ----------------: | ------------: | ---------: | | `xai.grok-4.3` | 1319 | 93.5 | 136 | 1,536 | $5.2191 | $2.6095 | The --reasoning-output-tokens figure is deliberately an estimate: Grok bills reasoning tokens as output tokens even though they are not visible in responses, so the ceiling depends on the effort level you choose. The $5.22 projection assumed every request burns the full budget; the actual runs came in well under it because most GSM8K answers finish in a few hundred tokens. The realized totals from the result files: Bedrock runs cost $0.4418 (none) to $2.4400 (high), and xAI runs cost $0.5883 (none) to $2.2431 (high). Run the Latency Benchmark Bedrock Mantle (one reasoning effort) AWS_PROFILE=loka-ml uv run python scripts/benchmark_grok_latency.py \\ --provider bedrock \\ --region us-west-2 \\ --model xai.grok-4.3 \\ --dataset gsm8k \\ --split test \\ --warmups 1 \\ --reasoning-effort low \\ --max-output-tokens 4096 \\ --concurrency 1 \\ --timeout-seconds 360 \\ --max-attempts 0 \\ --retry-backoff-seconds 2 \\ --retry-policy all-retryable \\ --max-billable-tokens 750000 \\ --max-estimated-grok-cost-usd 5.00 \\ --output-dir result/bedrock-grok43-low The retry flags matter on the Bedrock path, for reasons covered in the reliability section below: --retry-policy all-retryable treats a provider response that explicitly asks for a retry as retryable, and --max-attempts 0 retries until the request goes through, so the run finishes with a complete 1,319-row dataset. xAI API (one reasoning effort) uv run python scripts/benchmark_grok_latency.py \\ --provider xai \\ --model grok-4.3 \\ --dataset gsm8k \\ --split test \\ --warmups 1 \\ --reasoning-effort low \\ --max-output-tokens 4096 \\ --concurrency 1 \\ --timeout-seconds 360 \\ --max-attempts 3 \\ --retry-backoff-seconds 2 \\ --max-billable-tokens 750000 \\ --max-estimated-grok-cost-usd 5.00 \\ --output-dir result/xai-grok43-low Change the reasoning-effort flag to none, medium, or high and update the output directory accordingly for the other runs. What the eight main commands were The eight benchmark runs that produced the numbers in the main post used these output folders: Effort Provider Output folder none Bedrock result/bedrock-grok43-none low Bedrock result/bedrock-grok43-low medium Bedrock result/bedrock-grok43-medium high Bedrock result/bedrock-grok43-high none xAI result/xai-grok43-none low xAI result/xai-grok43-low medium xAI result/xai-grok43-medium high xAI result/xai-grok43-high There is one extra folder next to these: result/bedrock-grok43-low-error-examples holds the partial JSONL from an early Bedrock low pass that we stopped after ten measured prompts. It exists on purpose, as raw evidence for the reliability section below. What the Harness Does During a Run Each request goes through run_once, which opens a streaming connection and measures three timestamps: TTFB (time to first byte): the moment the first non-empty line arrives from the server, before any token is parsed. This is infrastructure only: connection setup, auth, admission, routing. TTFT (time to first token): the moment the first visible output token event arrives. With reasoning enabled this includes the model’s thinking time before the first output character, which is why the main post’s TTFT numbers diverge so sharply between the two paths at low effort (3.14s on Bedrock vs 0.71s on xAI). Concretely, the harness marks TTFT on the first streamed response.output_text.delta event that carries text. Total latency: the moment the stream closes. Token usage (input, output, and reasoning tokens separately) comes from the usage object on the stream’s completion event, where reasoning tokens sit under output_tokens_details.reasoning_tokens. Output throughput is derived per request as output tokens divided by total stream duration. Each completed or failed record is written to a partial JSONL file immediately, so a crash partway through does not lose the records collected so far. The live progress line looks like this (a real line from the Bedrock low run, reconstructed from the saved record): bedrock xai.grok-4.3 run 44/1320: ok; in=151 out=307 reasoning=258; cost=$0.000956; cumulative_tokens=21,509; cumulative_est_grok_cost=$0.046901 Three run guards keep a misbehaving run from burning budget: --max-billable-tokens and --max-estimated-grok-cost-usd stop the run when cumulative usage crosses a cap (we set 750,000 tokens and $5.00), and --timeout-seconds bounds any single request (we set 360). Output Files Each run writes three files into the output directory, plus the partial JSONL that accumulates during the run. The accuracy scorer adds two more later. This is the real Bedrock low folder: result/bedrock-grok43-low/ ├── grok_responses_latency_20260621T185415Z_partial.jsonl ├── grok_responses_latency_20260621T225049Z.jsonl ├── grok_responses_latency_20260621T225049Z_summary.json ├── grok_responses_latency_20260621T225049Z.md ├── gsm8k_accuracy_summary.json (written later by the scorer) └── gsm8k_accuracy_summary.md (written later by the scorer) The JSONL file has one record per request. This is a real record from the Bedrock low run, with the request ID shortened: { \"attempts\": 1, \"error\": null, \"estimated_grok_cost_usd\": 0.000697, \"expected_answer\": \"It takes 2/2=<<2/2=1>>1 bolt of white fiber\\nSo the total amount of fabric is 2+1=<<2+1=3>>3 bolts of fabric\\n#### 3\", \"input_tokens\": 98, \"model\": \"xai.grok-4.3\", \"ok\": true, \"output_chars\": 125, \"output_chars_per_second\": 77.96, \"output_text\": \"Blue fiber requires 2 bolts. White fiber is half of that amount, or 1 bolt. \\nAdding both gives a total of 3 bolts. \\n\\n#### 3\", \"output_tokens\": 230, \"output_tokens_per_second\": 143.45, \"prompt_id\": \"gsm8k-test-1\", \"prompt_index\": 1, \"prompt_text\": \"Solve this grade-school math problem. Show concise reasoning, then put the final numeric answer on a separate line prefixed with ####.\\n\\nProblem:\\nA robe takes 2 bolts of blue fiber and half that much white fiber. How many bolts in total does it take?\", \"provider\": \"bedrock\", \"reasoning_tokens\": 186, \"request_id\": \"fe647a91-…\", \"retry_errors\": null, \"run_index\": 3, \"started_at\": \"2026-06-21T18:54:26.516990+00:00\", \"total_ms\": 1603.32, \"ttfb_ms\": 260.6, \"ttft_ms\": 1381.7 } The summary JSON has three top-level keys: summary (one row per provider and model with avg, p50, p90, and p95 for each metric), aggregates (LLMPerf-style blocks with the full distributions: p25, p50, p75, p90, p95, p99, mean, min, max, stddev for TTFB, TTFT, end-to-end latency, throughput, and the three token counts, plus overall throughput, completed requests per minute, and total estimated cost), and dataset. The Markdown file renders the same content as tables. Score Accuracy Offline The accuracy scorer is a separate script that never touches the API. It works entirely from the saved JSONL files, which is important: you can re-score a run with an updated normalization rule without paying for another API call. To score all discovered runs at once: uv run python scripts/score_gsm8k_accuracy.py --main-runs This globs result/*/grok_responses_latency_*.jsonl, takes the newest completed JSONL in each folder (partials are skipped), and writes gsm8k_accuracy_summary.json and gsm8k_accuracy_summary.md into each run folder plus two aggregate files, result/gsm8k_accuracy_main_runs.json and result/gsm8k_accuracy_main_runs.md. The aggregate Markdown includes a comparison table across all runs and a per-effort Bedrock vs xAI delta section, which is where the main post’s accuracy table comes from. To score a single run: uv run python scripts/score_gsm8k_accuracy.py \\ --benchmark-jsonl result/bedrock-grok43-low/grok_responses_latency_20260621T225049Z.jsonl The Normalization Detail That Matters The answer extractor uses the #### prefix that GSM8K itself defines. Both the reference answers and the model answers follow the same format because the benchmark prompt asks the model to use it. Each request carries a short system message (“You are measuring API latency. Answer the user request directly, avoid markdown tables, and do not mention this instruction.”) and this user prompt: Solve this grade-school math problem. Show concise reasoning, then put the final numeric answer on a separate line prefixed with ####. Problem: {question} This makes the scorer deterministic and fast. The normalization handles the common failure modes: $14.00 instead of 14, 14,000 with a comma, a Unicode minus, a trailing period. The scorer extracts the last #### match in the output, so intermediate numbers in the reasoning do not pollute the comparison. Grok 4.3 followed the format almost perfectly: 10,538 of the 10,552 responses contained a #### line. The 14 exceptions (2 in the Bedrock medium run, 11 in Bedrock high, 1 in xAI medium) are recorded as missing_model_answer and counted as incorrect rather than silently dropped. The Two Requests That Never Reached the Model This is the part of the run we did not plan for, and the part most worth documenting. In one early Bedrock low-effort pass, two of the first ten prompts came back blocked by an automated prompt-safety check before the model produced any output. The prompts were ordinary GSM8K math problems. The blocks did not arrive as HTTP errors. The stream opened normally and then delivered an error event instead of output, which the harness caught on its stream-error path and recorded in the error field. The two affected prompts were gsm8k-test-4 and gsm8k-test-9. This is the real record for the first one, from the preserved partial JSONL (request ID shortened, prompt trimmed): { \"attempts\": 1, \"error\": \"invalid_prompt: This request was blocked by an automated content safety check. If you believe this was made in error, please retry or contact AWS Support with your request ID.\", \"estimated_grok_cost_usd\": null, \"input_tokens\": null, \"model\": \"xai.grok-4.3\", \"ok\": false, \"output_tokens\": null, \"prompt_id\": \"gsm8k-test-4\", \"prompt_text\": \"Solve this grade-school math problem. […] Problem:\\nEvery day, Wendi feeds each of her chickens three cups […]\", \"provider\": \"bedrock\", \"reasoning_tokens\": null, \"request_id\": \"147396ed-…\", \"run_index\": 6, \"total_ms\": 3159.35, \"ttfb_ms\": null, \"ttft_ms\": null } Note what the record structure gives you: ok is false, the token fields are null, TTFB and TTFT are null because no byte of model output ever arrived, and the exact provider message is preserved. We stopped that pass after ten prompts and kept its partial JSONL in result/bedrock-grok43-low-error-examples as evidence. The error message itself says to retry, so for the measured runs we set --retry-policy all-retryable with no attempt cap, and every blocked request eventually went through with exponential backoff. The retries are not hidden: each record carries an attempts count and a retry_errors list, so the full history is auditable in the saved artifacts. Across the completed Bedrock runs, the number of requests that hit at least one content-safety block before succeeding was 58 (none), 581 (low), 550 (medium), and 567 (high), with the worst case needing 10 attempts. The four xAI runs saw zero content-safety blocks; the only retry on that path in all 5,276 requests was a single connection reset. All eight runs finished 1,319 completed, 0 failed. The recorded latency for a retried request is the latency of the final successful attempt, so the retry mechanics inflate wall-clock time, not the per-request distributions. The engineering takeaway is that the harness treats a blocked request, a timeout, and a wrong answer as three different record types, and the scorer keeps them separate. Accuracy is computed over scoreable answers; reliability is reported alongside it, not blended into it. Running at Reduced Scale Before committing to the full 1,319-question run, use --limit to test against a small slice: AWS_PROFILE=loka-ml uv run python scripts/benchmark_grok_latency.py \\ --provider bedrock \\ --region us-west-2 \\ --model xai.grok-4.3 \\ --dataset gsm8k \\ --split test \\ --limit 10 \\ --warmups 1 \\ --reasoning-effort none \\ --max-output-tokens 4096 \\ --concurrency 1 \\ --output-dir result/bedrock-grok43-none-pilot This runs the first 10 questions, produces all the same output files, and lets you verify auth, output format, and metric collection before spending the full budget. Our own pilot is saved in result/bedrock-grok43-none-pilot. Caveats This benchmark is intentionally narrow: It measures sequential single-stream requests from one client location. Concurrent-request behavior and multi-region comparisons are out of scope. The dataset is grade-school math. Short prompts with compact answers are not representative of all enterprise workloads; longer prompts or outputs would shift the TTFT and throughput numbers. In particular, the flat accuracy curve above low effort is a property of this workload, not a universal claim about reasoning budgets. Latency, tail behavior, and safety-filter behavior are point-in-time properties of a serving fleet. Our numbers reflect the Mantle path as it stood in June 2026, weeks after the Bedrock launch. All of it can change as the fleet matures. Cost figures are estimates from list prices as of June 2026. The harness prices both paths at xAI’s published grok-4.3 rates ($1.25 per million input tokens, $2.50 per million output tokens, with reasoning billed as output); if your Bedrock pricing differs, override with --input-price-per-mtok and --output-price-per-mtok and the per-record costs recompute. Those caveats do not change the main result: same model quality through both doors, with the differences showing up in latency shape and reliability behavior rather than accuracy. But they matter when you translate these numbers into a production SLO. Takeaway The useful part is not only the numbers. It is the measurement discipline. The harness records every request, writes partial results during the run, separates blocked requests from wrong answers, and scores accuracy offline from saved artifacts. That structure is what made an honest comparison possible, including the part we did not expect to find. You can rerun it against your own region, your own workload shape, and your own concurrency level and get numbers that mean something for your system, not just ours. For teams evaluating Grok 4.3 on Bedrock Mantle against the first-party xAI API, that is the starting point: run the benchmark against your own traffic shape before committing an SLO to results from someone else’s setup."},{"href":"/grok-bedrock-xai/","title":"The Many Paths to Grok 4.3","subtitle":"What changes when xAI's reasoning-first model runs through AWS-native infrastructure","description":"A public-facing benchmark story on Grok 4.3 through Amazon Bedrock Mantle and the xAI API, focused on accuracy, latency, cost, reliability, and enterprise deployment tradeoffs.","abstract":"On 1,319 GSM8K test questions, Grok 4.3 reached 96.51% accuracy through Bedrock Mantle and 96.89% through the xAI API at low reasoning effort; provider differences were clearer in tail latency than answer accuracy.","tags":["Grok","Amazon Bedrock","xAI","Benchmarking"],"topics":["benchmarks","inference"],"authors":["Nina Cvetkovska","Bojan Jakimovski"],"text":"Why this matters In June 2026, xAI joined Amazon Bedrock as a model provider, and Grok 4.3 became the first model to run on Mantle, Bedrock’s new OpenAI-compatible inference engine. For teams that already live inside AWS, that’s a bigger deal than it sounds: it means access to xAI’s reasoning-first model without a new vendor relationship, a new billing pipeline, or a security review that starts from zero. But availability is only half the story. The question we kept hearing from clients wasn’t whether Grok 4.3 is good; xAI’s own benchmarks make that case. The question was more practical: does anything change when the same model runs through a different door? Does the AWS-native path affect accuracy? Latency? Does it fail differently under load? Nobody had published a straight answer, so we ran the experiment ourselves. This isn’t a leaderboard post, and it isn’t an implementation walkthrough. We took the same workload, the same evaluation, and pointed it at both routes to Grok 4.3, Amazon Bedrock Mantle and the first-party xAI API, and measured what actually differed. The short version: once reasoning was enabled, final accuracy was nearly identical on both paths. Where the paths genuinely diverged was latency, reliability behavior, and the operational machinery around the model. In our experience, that is exactly where enterprise deployments succeed or stall. What we wanted to learn If your organization has standardized on AWS (procurement, security review, IAM, regional architecture, cost allocation), then Bedrock Mantle is the path of least resistance to Grok 4.3. The question is whether “least resistance” comes with tradeoffs you’d want to know about before committing. So we framed the benchmark around the questions a technical decision-maker would ask before recommending one path over the other: Does Grok 4.3 deliver the same final-answer quality through Bedrock Mantle as through the xAI API? How much latency does each step of reasoning effort really add? Where does cost start to climb, and does accuracy keep pace with it? Do the two paths fail in different ways? Which reasoning-effort setting is the sensible default? A quick note on scope: Mantle itself deserves more than a passing mention, and we give it one later in the post. For now, the relevant point is that it puts Grok 4.3 behind AWS billing, governance, and regional deployment patterns your organization has likely already approved. What we tested We ran Grok 4.3 against the full GSM8K test split: 1,319 grade-school math word problems. GSM8K is a narrow benchmark, and we chose it deliberately for that reason. Because the task is so well-defined (read a short problem, produce one correct number), it gives us a clean, controlled way to compare final-answer accuracy, reasoning behavior, latency, and cost across the two paths without application-specific prompt design muddying the signal. (The dataset is openly available if you want to reproduce the setup.) Both paths got identical treatment: the same prompt shape, streaming enabled, one request at a time, and all four reasoning-effort settings that Grok 4.3 exposes (none, low, medium, and high). For each run we measured final-answer accuracy, p50 and p95 end-to-end latency, time to first visible token, median reasoning-token usage, and estimated run cost. Scoring was deliberately unforgiving: the final numeric answer had to match the reference exactly. A beautifully reasoned explanation ending in the wrong number scored zero. Strict scoring keeps the comparison honest and easy to interpret. What we got The most useful finding is also the simplest: reasoning effort mattered far more than provider path for final accuracy. With reasoning turned on at any level, both paths landed in the same 96–97% band. Whichever door you walk through, you get essentially the same model. Turning reasoning off entirely was the fastest and cheapest configuration, and also the least accurate. The single biggest jump in the whole benchmark came from switching to low effort. On Bedrock, accuracy climbed from 93.10% to 96.51%. On the xAI API, from 94.16% to 96.89%. Reasoning effort Bedrock (%) xAI API (%) none 93.1 94.16 low 96.51 96.89 medium 96.59 96.97 high 96.13 96.89 View numeric chart data Series Reasoning effort Accuracy (%) Bedrock none 93.1% Bedrock low 96.51% Bedrock medium 96.59% Bedrock high 96.13% xAI API none 94.16% xAI API low 96.89% xAI API medium 96.97% xAI API high 96.89% Figure 1. GSM8K accuracy by provider and reasoning effort. Low effort captured most of the accuracy gain. After that, the curve went flat. medium and high bought essentially nothing on GSM8K: Bedrock reached 96.59% at medium and actually dipped to 96.13% at high, while xAI reached 96.97% at medium and 96.89% at high. Those differences are noise, not signal. The clearest way to see it is to plot each step up in reasoning effort against the extra median latency it costs. The move from none to low sits in the part of the chart you want to be in: a large accuracy gain for a few additional seconds. Every step after that clusters near zero accuracy gain while latency keeps climbing. Series Added median latency (seconds) Accuracy gain (percentage points) provider step Bedrock 2.77 3.41 Bedrock none → low Bedrock 0.25 0.08 Bedrock low → medium Bedrock -0.2 -0.46 Bedrock medium → high xAI API 1.76 2.73 xAI API none → low xAI API 1.06 0.08 xAI API low → medium xAI API -0.09 -0.08 xAI API medium → high View numeric chart data Series Added median latency (seconds) Accuracy gain (percentage points) Bedrock 2.77 3.41 Bedrock 0.25 0.08 Bedrock -0.2 -0.46 xAI API 1.76 2.73 xAI API 1.06 0.08 xAI API -0.09 -0.08 Figure 2. Accuracy gain versus added median latency for each reasoning-effort step. The first step to low effort delivered the meaningful payoff. To be clear, this doesn’t mean higher effort is never worth it; harder workloads may well need the extra thinking budget. It means that for structured arithmetic like GSM8K, the model had all the room it needed at low. Beyond that point, you’re mostly buying tokens, not accuracy. Reading the tradeoff Latency is where the two paths stopped looking identical. Enabling low effort raised median latency on both: Bedrock moved from 0.79s to 3.56s, and xAI from 1.05s to 2.81s. That is the expected price of reasoning. The interesting part is the tail. Anyone who has shipped a user-facing product knows the tail is what users remember. A workflow can feel perfectly fine at the median and still feel broken when p95 spikes. In this run, the xAI API held a meaningfully tighter tail at low effort: 5.45s at p95 versus 9.70s on Bedrock. Reasoning effort Bedrock p50 (s) Bedrock p95 (s) xAI p50 (s) xAI p95 (s) none 0.79 1.72 1.05 1.56 low 3.56 9.7 2.81 5.45 medium 3.81 11.24 3.87 9.66 high 3.61 10.41 3.78 9.96 View numeric chart data Series Reasoning effort Seconds Bedrock p50 none 0.79s Bedrock p50 low 3.56s Bedrock p50 medium 3.81s Bedrock p50 high 3.61s Bedrock p95 none 1.72s Bedrock p95 low 9.7s Bedrock p95 medium 11.24s Bedrock p95 high 10.41s xAI p50 none 1.05s xAI p50 low 2.81s xAI p50 medium 3.87s xAI p50 high 3.78s xAI p95 none 1.56s xAI p95 low 5.45s xAI p95 medium 9.66s xAI p95 high 9.96s Figure 3. End-to-end p50 and p95 latency. The provider path showed up more clearly in latency than in final accuracy. The token story told the same tale from another angle. low effort used roughly 260–290 median reasoning tokens per question. medium and high pushed that past 400 on both paths while, as we saw above, accuracy barely moved. Reasoning effort Bedrock xAI API none 0 0 low 289 264 medium 467 399 high 459 412 View numeric chart data Series Reasoning effort Median reasoning tokens Bedrock none 0 Bedrock low 289 Bedrock medium 467 Bedrock high 459 xAI API none 0 xAI API low 264 xAI API medium 399 xAI API high 412 Figure 4. Median reasoning tokens by effort. Higher effort increased reasoning-token usage more clearly than it improved GSM8K accuracy. Cost tracked the reasoning tokens almost exactly, which makes the recommendation straightforward: low effort was the sweet spot in this benchmark. It captured most of the quality improvement without paying the full latency and token bill of medium or high. Full benchmark view Here’s everything in one place: accuracy, latency, throughput, reasoning tokens, and cost for all eight runs. Run Provider Effort Accuracy p50 p95 TTFT p50 Tok/s p50 Reason p50 Cost bedrock-grok43-none Bedrock none 93.10% 0.79 1.72 0.62 88.3 0 $0.4418 bedrock-grok43-low Bedrock low 96.51% 3.56 9.70 3.14 107.6 289 $1.5347 bedrock-grok43-medium Bedrock medium 96.59% 3.81 11.24 3.46 159.0 467 $2.4169 bedrock-grok43-high Bedrock high 96.13% 3.61 10.41 3.32 165.8 459 $2.4400 xai-grok43-none xAI none 94.16% 1.05 1.56 0.67 54.8 0 $0.5883 xai-grok43-low xAI low 96.89% 2.81 5.45 0.71 111.1 264 $1.5323 xai-grok43-medium xAI medium 96.97% 3.87 9.66 0.71 116.3 399 $2.1449 xai-grok43-high xAI high 96.89% 3.78 9.96 0.67 118.2 412 $2.2431 p50 and p95 are measured in seconds. Reasoning tokens are medians. Cost is the estimated cost for the full 1,319-question run. Reliability behavior Here’s the part that never shows up on a leaderboard. In one early Bedrock low-effort pass, two of the first ten prompts were stopped by an automated prompt-safety check before the model produced any answer at all. The prompts were ordinary GSM8K math problems, questions about apples and train schedules. That’s not a model-quality issue. It’s a property of the path the request travels through. And that distinction matters enormously for production planning. A blocked request, a timeout, and a wrong answer are three different failure modes with three different fixes, and collapsing them into one accuracy score hides the information you need most. Accuracy tells you whether the model solved the task. Reliability tells you whether the path consistently delivered a scoreable answer in the first place. This is why we always recommend benchmarking through your actual deployment path, not a proxy for it. Governance layers, safety filters, streaming behavior, and regional infrastructure all shape the user experience, even when the model underneath is identical. The bigger picture: why this pairing matters Before the takeaways, it’s worth zooming out. We’ve spent this post measuring one workload through two doors, and being picky about tail latencies and safety filters along the way. None of that picking should obscure the larger point: both sides of this partnership shipped something genuinely useful. What AWS built with Mantle Mantle is not a wrapper around a third-party API. It is a new inference engine inside Amazon Bedrock, designed for price performance and shipped with the full production feature set from day one: response streaming, structured outputs, tool calling, and Standard and Priority service tiers. The design choice that matters most for adoption speed is API compatibility. Mantle speaks the OpenAI API specification, so a team already built on OpenAI SDKs can point base_url at the Mantle endpoint, set the model to xai.grok-4.3, and be running inside Bedrock with minimal code changes. Meanwhile everything an enterprise actually worries about (billing, IAM, governance, procurement, regional controls) stays on rails the organization has already approved. As an AWS partner, we read Mantle as infrastructure, not a one-off integration. AWS built an OpenAI-compatible runtime into Bedrock, which positions the platform to onboard future third-party models the same way. Model choice without vendor sprawl is the whole promise of Bedrock, and Mantle extends it. What xAI brings with Grok 4.3 On the model side, Grok 4.3 earned its place in the catalog. It is a reasoning-first design: reasoning is always active rather than optional, with effort configurable from none to high, which is exactly the lever our benchmark shows paying off. It ships a 1-million-token context window, and xAI reports top marks on independent evaluations, including the lowest hallucination rate among frontier models on Artificial Analysis’s Omniscience benchmark and leading results on real-world tool-calling tests. That profile maps cleanly onto the workloads enterprises are trying to ship right now: contract review, case law research, financial document Q&A, and customer-support agents that need reliable tool calling over long context. Combined with Bedrock’s on-demand pricing for the model, it makes Grok 4.3 one of the most cost-effective frontier reasoning options on AWS today. Our results add the practical footnote: the combination holds up under measurement. Same model quality through the AWS route, with the operational conveniences that come with it. Takeaways for decision-makers If you’re a CTO, Head of AI, or solutions architect weighing this decision, the framing that helps most is this: you’re not choosing between two models. You’re choosing between two operational environments around the same model. Here’s what our data says about that choice: The strategic value of Bedrock Mantle is AWS-native access. Grok 4.3 arrives inside your existing billing, governance, IAM, and deployment patterns, with no new vendor onboarding and no parallel operational stack. Model quality is effectively path-independent. With reasoning enabled, both paths landed in the same 96–97% accuracy band on GSM8K. You’re not sacrificing capability for convenience. low reasoning effort was the best default in this benchmark. It delivered nearly all of the accuracy lift at a fraction of the token and latency cost of medium or high. Medium and high effort need to earn their keep. On this workload they increased reasoning tokens and cost far more than they improved accuracy. Justify them with your own workload data, not intuition. The paths diverge in latency shape and reliability behavior, not accuracy. Tail latency (p95) and pre-model safety filtering are where the differences live, and where your production architecture review should focus. Conclusion Grok 4.3 landing on Bedrock Mantle changes the adoption conversation for AWS-centered organizations. Governance, procurement, regional planning, streaming, structured outputs, and tool calling stop being separate integration projects and become part of the same motion as adopting the model itself. That’s the real headline; the benchmark just tells you what it costs. And what it costs turns out to be encouragingly little. Our practical recommendation from 10,552 scored requests: start with low reasoning effort for structured, GSM8K-like workloads. It captured most of the accuracy gain while keeping latency and cost under control. Reach for medium or high only when your own evaluation proves the extra reasoning budget pays for itself, because on this workload it didn’t. Finally, evaluate the path for what it actually changes: latency shape, tail behavior, reliability under safety filtering, governance fit, and day-two operations. When final accuracy is this close, the right decision stops being about the model alone and starts being about the system you wrap around it. If you’re evaluating Grok 4.3, or any foundation model, for a production workload on AWS, this is the kind of benchmarking Loka’s AI engineering team runs for clients every week. We’re happy to compare notes. Citation If you find this work useful, please cite: @misc{loka2026grok43bedrock, title = {The Many Paths to Grok 4.3}, author = {Cvetkovska, Nina and Jakimovski, Bojan}, year = {2026}, month = {jul}, howpublished = {Blog post}, url = {https://techblog.loka.com/grok-bedrock-xai/} } Further reading AWS (2026). Grok 4.3 from xAI now available in Amazon Bedrock. Official AWS announcement covering regional availability and Bedrock Mantle integration. aws.amazon.com xAI (2026). Grok on Amazon Bedrock. xAI's launch post, including model positioning and benchmark claims. x.ai AWS (2026). Grok 4.3 model card. Amazon Bedrock User Guide covering endpoints, reasoning-effort configuration, service tiers, and quotas for the Mantle path. docs.aws.amazon.com xAI (2026). API documentation. Reference for the first-party path used in this comparison. docs.x.ai Cobbe et al. (2021). Training Verifiers to Solve Math Word Problems. The paper that introduced GSM8K. arxiv.org OpenAI (2021). GSM8K dataset. The openly available test split used in this benchmark. github.com"},{"href":"/contributing-to-open-source-bioinformatics-our-experience-at-the-nf-core-hackathon-from-medellin/","title":"Contributing to Open-Source Bioinformatics: Our Experience at the nf-core Hackathon from Medellín","description":"If you work anywhere near data-heavy science — genomics, metagenomics, proteomics — you’ve probably hit the same wall: building reliable, reproducible data pipelines is hard. Nextflow is an open-source workflow engine…","abstract":"If you work anywhere near data-heavy science — genomics, metagenomics, proteomics — you’ve probably hit the same wall: building reliable, reproducible data pipelines is hard. Nextflow is an open-source workflow engine…","tags":["Bioinformatics","Nextflow","Metagenomics","Hackathons"],"topics":[],"authors":["Andres Florian","Daniel Sabogal"],"text":"What is nf-core, and why does it matter? If you work anywhere near data-heavy science — genomics, metagenomics, proteomics — you’ve probably hit the same wall: building reliable, reproducible data pipelines is hard. Nextflow is an open-source workflow engine designed to solve exactly that problem, letting scientists write scalable pipelines that run consistently across laptops, clusters, and cloud environments. nf-core is the community layer on top of Nextflow. It’s a collaborative project that curates high-quality, peer-reviewed pipelines and reusable modules — think of them as vetted building blocks that any researcher can plug into their own workflows. The result: less time reinventing the wheel, more time doing actual science. Twice a year, nf-core organizes a global hackathon where contributors from around the world gather — online and at local hubs — to build, improve, and ship these community resources. In March 2026, the hackathon brought together 29 hubs across 20 countries. Loka hosted two of those hubs: one in Medellín, Colombia, and another in Skopje, North Macedonia. Why Loka at an nf-core hackathon? Nextflow comes up regularly in our client work — in cloud migrations, proof-of-concept builds, and production-grade pipeline development — so contributing back to the open-source ecosystem felt like a natural step. This post covers the Medellín experience. The Medellín node: small team, focused mission Our hub operated out of a WeWork space in Medellín on March 11–12. Three of us worked a standard 9-to-5 with a clear goal: create and publish new nf-core modules. We scoped five modules and made strong progress on two, taking both to a publishable state within the two days, both of which were later merged into the official nf-core repository. Module 1: stacks/refmap — variant calling for ddRAD-seq data Stacks is a widely used software suite for analyzing restriction site–associated DNA sequencing (RAD-seq) data, a technique commonly used in conservation biology, population genetics, and ecological research. The refmap component performs reference-based variant calling from this type of sequencing data. During the hackathon we: Refined the module’s process definition to meet nf-core standards. Tested and validated Docker and Singularity containers, as well as the Conda environment definition. Prepared the pull request against the official nf-core/modules repository. The module was essentially finished by end-of-day two. After the hackathon, a maintainer left some review comments; we addressed them, and the module was successfully merged into the official nf-core repository. You can find it live at nf-co.re/modules/stacks_refmap. Module 2: singlem/dbdownload— taxonomy database for metagenomics SingleM is a tool for metagenomics taxonomy classification — it helps researchers figure out which organisms are present in a complex environmental sample. The module we worked on wraps its database-download functionality, allowing users to fetch the required taxonomic database directly within an nf-core pipeline. During the hackathon we: Refined the process definition and environment configurations. Fixed linting issues and completed all required nf-test tests. We finished the pull request shortly after the event, and this module was also merged into the official nf-core repository. You can find it live at nf-co.re/modules/singlem_dbdownload. What we learned Beyond the code itself, the hackathon was a crash course in the nf-core ecosystem. Some highlights: nf-core module standards and best practices. The project has thorough guidelines for everything from naming conventions to container specifications. Working within these constraints taught us a lot about building robust, community-ready bioinformatics resources. Testing with nf-test. Writing meaningful tests for bioinformatics modules — where inputs and outputs are often large, domain-specific files — requires thoughtful test-data selection and snapshot strategies. The power of daily stand-ups. Each day ended with an Americas-region wrap-up session (Day 1 · Day 2) where every hub shared progress. Seeing teams from Buenos Aires, Cambridge, and North Carolina working in parallel was genuinely motivating. What’s next We ran in parallel with Loka’s other hub in Skopje, a team of 20+ tackling larger-scale pipeline work: extending the existing nf-core/proteinfold pipeline with new tools for evaluating the accuracy of AI-based protein structure predictions, and building a brand-new antibody optimization pipeline. Two hubs, two very different scopes, same goal of giving back to the ecosystem. On our side, two merged modules is a strong start for a first outing, and we’re not done. We still have the rest of our scoped backlog and are continuing to work through it, with more PRs to nf-core/modules planned in the coming weeks. If you work with data-heavy science and have never contributed to open source, a hackathon is a low-risk way in: the standards are well documented, maintainers are responsive, and you walk away with merged work that the whole community uses. The Medellín node of the nf-core March 2026 hackathon — a small but determined team If you’re interested in contributing, keep an eye on nf-co.re/events for the next hackathon — they run twice a year."},{"href":"/from-proteins-to-pipelines-how-open-source-nextflow-tools-are-accelerating-drug-discovery/","title":"From Proteins to Pipelines: How Open-Source Nextflow Tools Are Accelerating Drug Discovery","description":"Modern computational drug discovery depends on complex workflows that connect AI models, structural biology tools, databases, and quality-control steps into reproducible pipelines. While many organizations have access…","abstract":"Modern computational drug discovery depends on complex workflows that connect AI models, structural biology tools, databases, and quality-control steps into reproducible pipelines. While many organizations have access…","tags":["Nextflow","Machine Learning","Drug Discovery","Bioinformatics","Open Source"],"topics":[],"authors":["Jelena Pejovic","Jorge Moura Sampaio"],"text":"Modern computational drug discovery depends on complex workflows that connect AI models, structural biology tools, databases, and quality-control steps into reproducible pipelines. While many organizations have access to state-of-the-art models, deploying and scaling them in production remains a significant engineering challenge. At the nf-core Hackathon March 2026 in Skopje, North Macedonia, Loka’s Bioinformatics and Bio ML teams contributed two open-source Nextflow projects that demonstrate how we help organizations operationalize computational drug discovery workflows. One extends protein structure prediction pipelines with standardized evaluation capabilities, while the other provides an end-to-end workflow for computational antibody engineering. Built alongside students from the Faculty of Computer Science and Engineering in Skopje, these projects showcase the type of production-grade workflow infrastructure that enables teams to move from individual tools and models to scalable, reproducible drug discovery platforms. Why Nextflow Is the Infrastructure Layer for Modern Drug Discovery If your organization runs computational biology workloads, chances are you’re already using Nextflow. The numbers tell the story: over 20,000 bioinformaticians use it worldwide, it powers 40% of modern biology workflows, and it runs 2.5 million pipeline executions every month. Sixty-five percent of the world’s top pharmaceutical companies have adopted it. On top of Nextflow sits nf-core — a community-maintained collection of over 1,400 peer-reviewed modules and 100+ full pipelines. When a module lands in nf-core, it’s available to every researcher and every team globally. That’s the model: build once, share with everyone, improve collectively. What makes this ecosystem particularly powerful right now is how naturally it bridges machine learning and biology. The tools predicting protein structures — AlphaFold, Boltz, ColabFold — are deep learning models. The tools evaluating and validating their outputs are software engineering problems. Nextflow is the orchestration layer that connects all of it: running each tool in its own container, parallelizing across thousands of samples, and producing reproducible results on any infrastructure from a laptop to AWS. For organizations building drug discovery capabilities, the gap between a breakthrough ML model and a production-ready workflow is an engineering problem. Drug discovery workflows often involve dozens of tools, data sources, and validation steps that must run reliably across local infrastructure, HPC environments, or the cloud. That’s the problem Loka solves. This is where workflow orchestration becomes critical. Nextflow provides the foundation for building reproducible and scalable computational drug discovery platforms, allowing teams to automate complex processes while maintaining consistency across projects and environments. Projects Overview Project 1 — Protein Complex Co-folding Protein structure prediction is increasingly becoming a workflow problem rather than a modeling problem. Modern teams routinely generate thousands of structures using tools such as AlphaFold, Boltz, and ColabFold, but extracting actionable insights requires automated evaluation and quality-control steps that can scale alongside prediction. Our contribution extends the nf-core/proteinfold workflow with structural evaluation modules, enabling researchers to automatically assess prediction quality as part of the same reproducible pipeline. Project 2 — Computational Antibody Engineering The challenge in computational antibody engineering is not a lack of tools. Researchers already have access to powerful models for sequence design, structure prediction, humanization, and developability assessment. The challenge is connecting these tools into a single reproducible workflow that can be executed consistently across projects and scaled from individual candidates to large design campaigns. Most organizations still rely on fragmented processes involving multiple scripts, environments, and manual handoffs. Our second project addresses this workflow orchestration challenge directly. Project 1 — Structural Evaluation for nf-core/proteinfold The Pipeline nf-core/proteinfold unifies multiple protein structure prediction tools — AlphaFold2, AlphaFold3, ColabFold, ESMFold, Boltz, and others — under a single reproducible workflow. It solves a fragmentation problem: each tool has different dependencies, input formats, infrastructure requirements, and output conventions. Proteinfold standardizes all of that. The pipeline already reports per-model confidence metrics like pLDDT through MultiQC. What it lacked was the ability to compare predicted structures against external reference models, and to score the quality of binding interfaces in protein complexes specifically. That’s what our two modules add. What We Built We added two evaluation modules that answer the question every downstream decision depends on: how reliable is this prediction? US-align — structural comparison. US-align measures how similar a predicted structure is to a known reference, atom by atom. It produces RMSD (a 3D difference score where lower is better) and TM-score (a global similarity metric from 0 to 1, where closer to 1 is better). For any team using AI-predicted structures to guide experimental work, these metrics are essential for deciding whether a prediction is actionable. DockQ v2 — interface quality scoring. When two proteins fold into a complex, the binding interface is what matters most. DockQ scores that interface specifically, producing metrics including interface RMSD, ligand RMSD, fraction of native contacts, and an overall DockQ score. If you’re designing molecules that need to bind a specific surface, this is the metric that tells you whether your prediction got the critical part right. Together, US-align and DockQ complete proteinfold’s evaluation story: predict the structure, compare it to a reference, and score the binding interface. By integrating these capabilities directly into nf-core/proteinfold, structural evaluation becomes a reproducible step within a larger drug discovery workflow. Project 2 — An End-to-End Antibody Optimization Pipeline The Problem Researchers working on computational antibody engineering typically chain steps manually across disconnected tools and environments. The process is hard to reproduce, difficult to scale, and creates friction between computational design and wet lab validation. Our second project addresses that directly with a single Nextflow pipeline that takes a known antibody structure and produces a ranked list of optimized candidates ready for laboratory testing. What We Built Nextflow workflow for antibody CDR redesign, structure verification, humanization, and humanness scoring. Step 1 — AntiFold: CDR Redesign via Inverse Folding. Standard folding goes from sequence to structure. AntiFold does the reverse — it takes the 3D backbone of an antibody’s CDR and generates hundreds of new sequences compatible with that shape. Instead of testing trillions of possible CDR combinations, you constrain the search to sequences that are physically compatible with the binding geometry you need. Step 2 — ABodyBuilder2: Structural Verification. Not every sequence AntiFold generates will fold correctly in practice. ABodyBuilder2 takes each candidate and predicts its 3D structure independently — essentially refolding from scratch to verify it still produces a valid antibody. Think of it as a compiler check: you generated the code, now you run it to confirm it compiles. Step 3 — BioPhi Sapiens: Humanization. Most research antibodies originate from mice. A mouse antibody in a human patient triggers an immune response. Humanization rewrites the non-CDR portions to resemble human antibodies as closely as possible, while preserving the designed binding site. Step 4 — OASis: Humanness Scoring. OASis scores each humanized candidate against a database of over one billion real human antibody sequences. It breaks the sequence into overlapping 9-residue windows and checks how many appear in actual human antibodies. Higher scores mean the sequence looks more human and is likely safer in a patient. By orchestrating the entire process — from design to validation and humanization — the pipeline transforms a fragmented computational process into a reproducible and scalable antibody engineering platform. From Models to Production Workflows The projects developed during the hackathon highlight a broader trend across computational drug discovery: the bottleneck is increasingly workflow infrastructure rather than individual algorithms. Modern pipelines combine structure prediction, molecular design, sequence generation, quality control, and downstream analytics. While many organizations have access to powerful AI models, integrating them into reliable, scalable workflows remains a significant challenge. Nextflow addresses this challenge by providing a framework for orchestrating complex scientific workflows across any infrastructure. The projects described here are examples of how Loka helps organizations transform computational methods into reproducible workflows that scientists can run, validate, and scale. Both projects will continue to evolve through the nf-core review process and future benchmarking efforts. More importantly, they demonstrate the type of workflow infrastructure required to operationalize modern computational drug discovery. At Loka, we help organizations build and deploy these workflows using Nextflow and modern cloud infrastructure, enabling teams to move faster from computational insight to experimental validation."},{"href":"/computer-vision-at-scale-on-sagemaker-jobs-four-decisions/","title":"Computer Vision at Scale on SageMaker Jobs: Four Decisions","description":"Training a vision model on millions of images is, more than anything, a data problem wearing an ML costume. The architecture can many times be the least interesting part. Everything around it is usually more fun: how we…","abstract":"Training a vision model on millions of images is, more than anything, a data problem wearing an ML costume. The architecture can many times be the least interesting part. Everything around it is usually more fun: how we…","tags":["Computer Vision","Data Science","AI","Amazon SageMaker","Big Data"],"topics":[],"authors":["Didier"],"text":"Training a vision model on millions of images is, more than anything, a data problem wearing an ML costume. The architecture can many times be the least interesting part. Everything around it is usually more fun: how we are getting images onto the GPU, running distributed training without hand-rolling process management, and wiring a chain of jobs together so that a failure nine hours into a run tells you exactly what broke instead of just turning red. Better yet, so you catch it before you burn the nine hours, with good logging and small test runs. Amazon SageMaker jobs are a super solid way to build this kind of pipeline. Across a few recent projects, most recently a large-scale computer-vision pipeline, I have landed on four decisions that, in my opinion, mostly determine whether the build is linear and “boring” (the good kind) or a three-week debugging tour of CloudWatch (the ‘not-so-good’ kind): Which SageMaker job primitive runs each step. How image data reaches the GPU at scale. How distributed training is launched and synchronized. How each job’s boundaries are made explicit and operable. One honest note before we dive in: only one of these four is really about computer vision. Decisions 1 and 4 are general SageMaker jobs hygiene that any big-data workload needs, and Decision 3 is general distributed training that images only make bite harder. Decision 2, the data layer, is where computer vision actually lives. I will flag each section as we go, because knowing which lessons are vision-specific and which are “any big job on SageMaker” is half of what makes them useful. Who this is for This is written for ML and MLOps engineers who have trained models before and now have to do it at scale on AWS. You will get the most from it with at least some computer-vision experience: enough that a DataLoader, an augmentation pipeline, and an epoch are old friends, because I lean on those without re-explaining them. You do not need to be a SageMaker expert, since I introduce the pieces as they come up. And if you have so far only trained on datasets that fit on your laptop, you are exactly the person the scale gotchas here will save a week. This is not an AWS tutorial, and we are not getting into SDK code! Check the ‘further reading’ section for that, or point your favorite LLM at the docs to wire up the exact calls. This is the set of things that actually bite, or that at least have bitten me before. So, let’s go! Why big-data Computer Vision is mostly an I/O problem Before anything, a quick note: if you have only trained on datasets that fit on a local disk, the instinct is to worry about GPU memory and FLOPs. At a million images, with distributed training and a good enough budget, those are rarely the constraint. I/O is. Every epoch, each image has to travel from storage, through preprocessing and augmentation, into a batch, and onto the GPU, fast enough that the GPU never waits. Pull each one from object storage on demand and you are making millions of tiny requests per epoch while your expensive GPU sits idle on the network. So the first metric to watch is not always loss, it is GPU utilization. Under 80 percent means the data pipeline is your bottleneck, and more GPU will not help. What makes this specifically a vision problem is the unit of data. A tabular row is a few hundred bytes and needs no decoding; an image is hundreds of kilobytes to several megabytes of compressed JPEG or PNG that has to be decoded, resized, and augmented before it is ever a tensor. That decode step alone is a real CPU cost, and it is the quiet reason the GPU starves. And one dial governs most of it: resolution. The pixels you train on set your batch size, your memory ceiling, your decode and augmentation cost, your storage footprint, and your accuracy, all at once. Pick it deliberately and early, because almost every number in the rest of this post moves with it. Decision 1: pick the job primitive that matches the work Mostly general SageMaker. This is true for any big-data job, not just vision. SageMaker is a family of job primitives, and two of them are the workhorses of a training pipeline. A Processing Job is the general-purpose worker: it runs a script, reads inputs from S3, writes outputs to S3, and disappears. It usually runs on CPU (though it can use GPU instances) and lacks the training toolkit and FSx mounting. Use it for data prep, preprocessing, evaluation, and metric aggregation. A Training Job is the GPU specialist: it carries SageMaker’s training toolkit, which launches distributed training cleanly, and it can mount an FSx for Lustre filesystem. Use it for training. Three more are worth knowing even if you do not use them on a given project. A Batch Transform Job is the purpose-built primitive for bulk offline inference: it shards a dataset across instances and runs the forward pass with no inference loop to write, which is the managed alternative to scoring inside a Processing Job. A Hyperparameter Tuning Job wraps the training primitive to search a hyperparameter space across many runs. And an AutoML Job automates model building end to end, which is the wrong tool for a custom architecture but the right one for a quick standard baseline. Serving a model online is a separate world of endpoints (real-time, asynchronous, serverless), not jobs. A pipeline is just a chain of those with S3 as the “bus” between steps: a CPU step turns your data source into a snapshot on S3, a GPU step trains and writes a checkpoint, a CPU step scores the held-out set. A generic SageMaker pipeline for training a computer-vision foundation model and running offline inference, built entirely from jobs and steps. Each step is a self-contained job that reads from and writes to S3. The trap is reaching for one job type out of habit. I once ran an evaluation pass as a Training Job purely so it could mount FSx like the training step did, on the theory that consistency was tidy. It was not tidy, just wasteful: a CPU-only job paying for GPU plumbing it never touched. Match the primitive to the workload, not to the step before it. One pipeline habit worth building early: write each step’s output under the pipeline execution ID, so two runs at once cannot overwrite each other’s artifacts in S3. Decision 2: design the data layer like it is the main event The computer-vision core of this post. If you skim one section, make it this one. “We’ll cache the images” is not a design. There are real strategies with real tradeoffs, and the right one depends on dataset size and how often you re-run on the same data. No cache. Read and preprocess from S3 (or FSx) on every access. Simple, fine for small datasets and debugging, brutal at scale because you pay the full I/O and preprocessing cost every epoch. Generally not the right call for the kind of problem we are dealing with here, though depending on how heavy your preprocessing is, it can be acceptable. Local cache. Preprocess each image once, write it to instance disk, and read from disk after that. You can also choose to apply augmentations fresh per epoch so you do not freeze one augmentation outcome into the cache. Two details save you grief: key the cache on the full image path plus the target resolution, not the bare filename (or two files both called 001.png collide), and write through a temporary file and an atomic rename so a crash cannot leave a half-written file the next run trusts. Persisted preprocessed cache. My favorite for most projects! Run it as a preprocessing job once, write the results to S3 in large tensor shards or actual image files, and fingerprint the preprocessing config so that a re-run with the same config skips the work entirely. This is the one for large datasets you train on repeatedly. The main caching strategies for large-scale computer-vision jobs, and the tradeoffs that decide between them. It helps to separate two things that often get muddled here: how your samples are laid out in storage, and how the bytes reach the training box. They are independent choices, and they stack. Start with layout, and specifically sharding. Object storage charges a fixed overhead on every GET, so reading a million images as a million separate objects means a million tiny, latency-bound requests with the GPU idle in between. Sharding packs many samples into a handful of large container files, say a few thousand images per shard and a few hundred shards instead of a million objects, which turns those small random reads into a few big sequential ones that stream and parallelize cleanly across workers. This is exactly what the persisted cache above is doing when it writes large tensor shards. You can hand-roll that, which is what we did on that recent vision project, where the preprocessing was custom enough that a plain tensor dump was simplest, or you can reach for WebDataset, FFCV, or MosaicML Streaming, which give you the shard format and a tuned reader and shuffle buffer off the shelf. Same idea either way, the only question is whether you want to own the reader. The second axis is transport. On SageMaker, Fast File mode streams objects from S3 with filesystem semantics and no upfront download, and it is the lightest thing to try first. FSx for Lustre is the step up: a POSIX filesystem backed by S3 that serves reads at local-disk speed once it is warm. My favorite setup stacks the two ideas, persisted sharded tensors living on an FSx volume, so you get the cheap sequential reads of sharding and the low latency of a local mount. Once you are on FSx there is little reason to also keep a separate local cache, since the mount loads about as fast. Whichever transport you pick, make FSx fail loud: if the mount is configured but unreachable, raise immediately rather than silently falling back to S3, because silent fallback gives you a job that trains at a tenth of the throughput you are paying for with nothing in the logs to tell you. And if it turns out that JPEG decode, not transport, is what is starving your GPU, push decoding and augmentation onto the GPU with a library like NVIDIA DALI. Two knobs inside the data layer are pure computer vision, and worth setting on purpose rather than by accident. The first is what you persist. Re-encoded images (JPEG, PNG) are small and cheap to move but pay the decode cost on every read, and lossy JPEG re-compression can quietly degrade what the model sees, decoded tensors skip the decode but are much larger on disk and across the wire. The second is where augmentation sits. Cache after augmentation and every epoch sees the same frozen crops and color jitter, which throws away the regularization you wanted; cache the preprocessed-but-not-yet-augmented image instead and apply augmentation fresh at read time. For anything that leans on augmentation diversity, which is most vision training, persist before augmentation. Decision 3: let the platform run distributed training General distributed training, not vision-specific, but image batches make it bite sooner. The biggest mechanical change when you go multi-GPU on SageMaker is who owns the processes. Do not call torch.multiprocessing.spawn and set the master address yourself. Enable the distributed strategy on the training job and let the Deep Learning Container launch your script through torchrun. Your script becomes an ordinary single-process entry point that reads RANK, LOCAL_RANK, and WORLD_SIZE from the environment, and you never set the master address. torchrun sets it, and overriding it is a popular way to make a job hang forever. A few rules keep distributed training honest: use LOCAL_RANK, not the global rank, for device placement; scope all side effects (checkpoint writes, logging, progress) to rank 0; aggregate loss weighted by each rank’s sample count rather than as a mean of means; and give process-group initialization a generous timeout so a slow cache build does not look like a dead rank. Then there is the SageMaker special. Your first run will probably die on the first batch with “No space left on device,” which is baffling on an instance with terabytes of disk. The culprit is the 64 MB /dev/shm partition that SageMaker containers ship with, which PyTorch’s default DataLoader uses to pass tensors between workers. Vision hits this wall fast, because those tensors are decoded image batches, and a single batch at training resolution is easily tens to hundreds of megabytes. The fix can be a one-liner, set at import time: import torch.multiprocessing torch.multiprocessing.set_sharing_strategy(\"file_system\") That routes tensor IPC through the filesystem instead of /dev/shm shared memory, which can cost you throughput if that filesystem is slow. A few ways to keep it cheap: Put the temp directory on fast local storage. The strategy writes to your temp dir, so point TMPDIR at instance-store NVMe (or a tmpfs, if you have the RAM to spare) rather than network-backed EBS, and “going through disk” stops being slow. Move less data across the worker boundary. The IPC cost scales with how much each worker hands back, so decode and augment on the GPU (DALI, Kornia) or return compact uint8 tensors and convert on device, and there is simply less to ship. Reuse workers. Set persistent_workers=True with a sane num_workers so you are not paying worker startup every epoch. If you control the container you can size /dev/shm up and keep the default strategy instead; on managed SageMaker jobs you usually cannot, which is why the one-liner is the pragmatic fix. Two more things I would assume in any serious run but that are easy to leave out: mixed precision (use bf16 on modern GPUs for roughly double the memory headroom and throughput) and the fact that plain DDP only works while the model fits on one GPU. When it does not, you move to FSDP or DeepSpeed ZeRO, which shard the model across GPUs. Decision 4: make every job boundary explicit General MLOps hygiene, not vision-specific, included because at vision scale skipping it hurts most. A framework that passes data between steps implicitly is really cool right up until something breaks, at which point the implicitness is exactly what hides the cause. SageMaker jobs force you to spell out every boundary, and you should lean into that. Make each step a standalone script with a clear contract: command-line arguments for its config and input paths, environment variables for infrastructure, and a defined S3 location for output. No shared in-memory state, no magic serialization. You can run any step by hand with the same arguments the pipeline would pass it. Identity is part of that contract. Key everything off a job name you set when the run starts, and build the checkpoint path from it, so downstream steps reconstruct the path by string-building rather than querying a metadata service. (Watch for reserved names. SageMaker sets its own TRAINING_JOB_NAME inside training containers, so give yours a prefix.) Emit structured JSON logs tagged with that job name so your logs are queryable instead of a wall of text, and connect experiment tracking through an explicit endpoint rather than letting the orchestrator inject it for you. The bonus: making every boundary explicit, and then running real data through at scale, tends to surface latent bugs that implicit wiring kept hidden for years. Explicit boundaries are not just operational hygiene, they are a debugging tool. Finally, my summary list of problems that may bite you! A quick list to scan before you start, most of which are not in most tutorial: First batch dies with a disk-space error. The 64 MB /dev/shm limit. Move DataLoader tensor IPC off it with the file-system sharing strategy (Decision 3), backed by fast local storage. A custom environment variable gets silently overwritten. SageMaker reserves some names. Prefix yours. A downstream step cannot find the checkpoint. The path depended on something non-deterministic. Build it from a name you set up front. Distributed training launches and hangs. Usually a base image without the SageMaker training toolkit, so torchrun never launches. Use the AWS Deep Learning Container. A corrupt image halts a multi-day run. At a million images it will happen. A bounded skip in the loader is a backstop; a cheap validation pass before training is the real answer. GPU utilization sits at half. Not a crash, just money on fire, and it sends you back to the data layer. Where your situation will differ This post mostly went into classification-style training on fixed-size images, scored offline. A few axes move the details, and the most common task types each have particularities worth a sentence: Classification is the easy case: a tiny scalar or one-hot label that caches for free, evaluated with accuracy or AUC. Object detection, which is most of my own background, attaches a variable number of boxes to each image, so targets are variable-length and you need a custom collate function. It is evaluated with mAP and IoU, and inference adds non-maximum suppression and usually wants a GPU, which flips the fixed-shape cache and CPU-inference choices above. Semantic and instance segmentation carry full-resolution mask targets, so augmentation has to be applied identically to image and mask, the cache roughly doubles in size, and large images force tiling. Generative models (diffusion, GANs) lean on latent caching (encode each image once, then train on the latents, the same idea as the persisted cache), use aspect-ratio bucketing to batch mixed sizes, and are judged by FID or CLIP score rather than accuracy. Two more axes, briefly. Your images: gigapixel scans or satellite tiles cannot go into a batch whole, so you tile them and sample patches, and non-RGB or high-bit-depth data changes normalization and storage. Your serving mode: offline batch scoring is one world; real-time, asynchronous (great for large payloads like video), and serverless endpoints are another, and the latency you ship usually comes from inference-time optimization like ONNX, TensorRT, or quantization rather than from the training recipe. And before any of this, split your data so that no group leaks across train and test (all images from the same source or subject in one split) and de-duplicate near-identical images first, or your metrics will look better than your model actually is. Closing A million images is an infrastructure problem with four moving parts: the job primitive per step, the data layer, how distributed training is launched, and how explicit your job boundaries are. Get those right and the model training itself becomes the easy, almost boring part, which is exactly where you want it. Further reading Streaming data formats: WebDataset, FFCV, MosaicML Streaming NVIDIA DALI for GPU-side decoding and augmentation SageMaker training input modes and data sources and inference options PyTorch FSDP, DeepSpeed ZeRO, and PyTorch automatic mixed precision"},{"href":"/pushing-open-source-tts-models-to-their-limits-six-paradigms-14-models-one-production-reality/","title":"Pushing Open-Source TTS Models to Their Limits: Six Paradigms, 14 Models, One Production Reality Check","description":"In the digital audio subset of AI, the questions currently on everyone’s mind are","abstract":"In the digital audio subset of AI, the questions currently on everyone’s mind are","tags":["Open Source","TTS","Audio","Deployment"],"topics":[],"authors":["Ervin Shaqiri","Alexandre Domingues"],"text":"In the digital audio subset of AI, the questions currently on everyone’s mind are Which models can express emotion? Are any of them actually usable in production? And do open source models provide the same performance? To investigate, we ran a single sentence through 14 open-source text-to-speech (TTS) models over several weeks, benchmarking each against AWS Nova Sonic v2 as a production reference. The takeaway is that the AI audio space is more fragmented than expected and more capable than the discourse suggests. It’s also hiding several traps that will cost you time if you don’t know where to look. This is the short version. The full technical breakdown lives on the deep-dive page, which covers the architecture-by-architecture analysis, the complete benchmark tables, the latency chart, and an interactive matrix where you can hear every model on every emotion. Why Emotion Is the Hard Problem in TTS Generating intelligible speech is largely a solved problem. Every one of the 14 models can read a sentence clearly. The gap between a demo and a deployable product is almost never intelligibility. Instead, it’s affect. Does the voice sound like it means what it says? Can it express urgency without sounding robotic? Can it laugh without sounding like a waveform artifact? This type of nuance turns out to be a much harder architectural problem than clarity is. Clarity is a function of the acoustic model learning correct phoneme mappings, but affect requires the model to encode prosodic variation pitch contour, timing, breathiness, vocal effort in a way that is semantically interpretable, temporally consistent, and controllable at inference time. These are three separate requirements, and most models only satisfy one or two of them. The result is six distinct paradigms across the fourteen models, with almost no overlap between approaches and no consensus on which is correct. The Six Emotion Paradigms The biggest surprise was not any individual model’s quality, but how differently the field has conceptualized the problem of emotion control. These are not interchangeable design choices. They encode fundamentally different assumptions about where in a pipeline emotion should be decided, represented, and executed. 1. Inline Tag Injection AWS Nova Sonic v2, CosyVoice 3, Maya1 Emotion tags are inserted directly into the text: [laugh], [sigh], <whisper>, <gasp>. The upstream LLM decides where they go; the TTS model conditions on them. This is the most composable architecture for agentic pipelines. The LLM becomes the emotion director with zero extra infrastructure, since its output is already the input to TTS. Maya1 extends it with 20+ tags plus natural-language zero-shot voice descriptions (specify a voice entirely in prose). The limitation: tags are fixed before generation. Once the audio is streaming, you can’t retract a <laugh>. 2. Parenthetical Markers fishspeech S1 mini 49 tags: (laughing), (sobbing), (whispering), (angry), (disgusted), (panting) and 39 more. That’s the largest expressive vocabulary in the set by a factor of two. Trained on 2M+ hours across 13 languages with online RLHF, with strong intelligibility on paper (WER 0.011, CER 0.005). But in practice its base voice rated the weakest of all locally-runnable models tested. The tag vocabulary is a ceiling, not a floor: a well-delivered neutral is worth more than 49 tags on a voice that doesn’t sound right. 3. Continuous Exaggeration Slider Chatterbox No tags, no emotion selection. Just a CFG exaggeration dial (0.0 to 1.0+) plus a Pace dial. The model infers the emotional quality from the text and scales it up or down. It’s the closest paradigm to how a voice director actually works (“give me 30% more on that line”). The catch is an uncanny valley somewhere between 0.7 and 1.0 (varying by sentence, voice, and content) where the output stops sounding like a person. Chatterbox is also the standout for combining zero-shot voice cloning with independent control of expressiveness. 4. Fine-Grained Parameter Control Ming-Omni-TTS-0.5B Independent axes set at inference time: rate, pitch, volume, emotion, dialect. Emotion accuracy benchmarks at 76.7% on CV3-Eval. It’s the only model in the set with a published emotion-accuracy number, and architecturally the most complete control surface. The problem is the base voice: Ming-Omni produced the least natural output of any model tested, a tradeoff of its unified speech-plus-ambient-plus-music generation channel. The knobs are real; they’re operating on a weak starting point. 5. Voice Style Presets Voxtral-4B-TTS (Mistral AI) Twenty named presets (cheerful_female, casual_male, neutral_male, casual_female) where emotion is encoded in the persona, not in markup. It reframes the question from “what emotion should this line have?” to “who is saying this line?” That’s a casting decision, not a direction decision. A customer-service agent doesn’t need [excited] on every happy response; it needs to be cast as a naturally warm persona. 6. Built-In Contextual Emotion Qwen3-TTS Emotion is a first-class property of the model itself. No tagging required; it infers affect from text semantics. The highest-trust paradigm, with zero engineering overhead for emotion. The risk is that you cede control: when the model’s interpretation diverges from what you intended (and it will), there’s no lever short of rewriting the input text. Does Scale Actually Help? This is the question that the data answers most clearly, and the answer is no, not in the way conventional ML intuition suggests. DiVA at 8B parameters is the most computationally expensive locally-runnable model in the set, and it produces the worst output: robotic. fishspeech was trained on 40× more data than Magpie and rated significantly worse. Kokoro-82M, trained on a few hundred hours for roughly $1,000 of compute, rated alongside models trained on orders of magnitude more data and cost. The differentiator is architecture and data curation, not scale. Kokoro’s training data was hand-selected from CC-licensed and public-domain sources; Magpie used well-documented, curated multilingual datasets; fishspeech used a large but unlabeled proprietary corpus. And Magpie hits a CER of 0.34% on LibriTTS test-clean with a fully disclosed, reproducible training set. That’s a state-of-the-art result on an open model under 400M parameters. Scaling laws in TTS are not what they are in language modeling. Embedded content Params vs. training data vs. naturalness. The most and least natural models sit at opposite ends of what scale would predict. Hardware Reality: What Actually Runs Where This matters more than most model cards acknowledge. The practical split is clean: Maya1, Kokoro, Magpie, VibeVoice, and Chatterbox run well on Mac and represent the realistic local-first stack. Everything else requires infrastructure investment. Some, like Voxtral, PersonaPlex, and fishspeech, require it as a hard prerequisite (Voxtral needs ≥16GB VRAM and isn’t Mac-compatible). For Mac-first development, the local tier is surprisingly strong. Maya1 at sub-100ms with ElevenLabs-level quality sets a bar that would have been considered cloud-only two years ago. Embedded content What actually runs where: Mac, GPU, VRAM, and latency across the full set. Production Gotchas Latency benchmarks lie at single concurrency. Voxtral’s 70ms single-request latency climbs to 331ms at 16 concurrent requests and 552ms at 32. That’s an ~8× jump, and not a linear degradation. It reflects contention on the flow-matching acoustic transformer. Benchmark at your expected p95 concurrency, not at one. Watermarking is absent almost everywhere. 12 of 14 open models ship with no audio-provenance mechanism. Only VibeVoice (dual: imperceptible digital + audible disclaimer) and Chatterbox (Perth watermarking; survives MP3 compression, editing, and mixing) provide attribution. As synthetic-media regulation matures, this gap goes from optional to mandatory. Building on a model with no watermarking now means retrofitting later. Two models are non-commercial, and HuggingFace doesn’t make it obvious. fishspeech S1 mini is CC-BY-NC-SA-4.0; Voxtral-4B-TTS is CC BY-NC 4.0 (notable given Mistral’s usual Apache/MIT licensing). Both sit in search results next to permissive models with no visual differentiation. Read the license before building any pipeline dependency. Chatterbox’s exaggeration slider has no safe default. The docs suggest 0.5, but testing showed 0.5 is too low for expressive content and too high for matter-of-fact sentences. Plan for calibration time. CosyVoice 3 is architecturally compelling and operationally painful. Its cross-lingual zero-shot voice cloning (77.4 to 78% speaker similarity: clone an English speaker, generate German in their voice) is the most powerful capability in the comparison. But the Mac implementation complexity was high enough that testing was abandoned. Budget for a Linux GPU server. Emotion Expressiveness (Listen for Yourself) Eight of the fourteen models support explicit emotion control. We ran the same nine emotion categories (angry, breath, excited, fearful, laugh, sad, sigh, surprised, and whisper) through all eight, from a single charged sentence: “I can’t believe you actually did that — I’ve been waiting for this moment for years.” Reading about affect only goes so far; you have to hear it. The deep-dive page has an interactive matrix where every cell is a real local-inference clip you can play (empty cells mark emotions a model doesn’t expose), spanning AWS Nova Sonic v2, Qwen3-TTS, Chatterbox, fishspeech S1 mini, Ming-Omni-TTS, Maya1, Voxtral-4B-TTS, and Magpie TTS 357M. You can play every clip on the interactive version. The Missing Piece The most important capability that doesn’t exist in any of these models is continuous real-time emotion modulation during streaming generation. Every system here requires the emotional direction to be decided before or during text generation: in the prompt, the tags, the preset, the exaggeration value. Once audio starts, the emotional character is fixed. No model can shift its affective tone mid-stream in response to live conversational context the way a human does. The full-duplex models (Nova Sonic v2, PersonaPlex) are the only ones where the architecture even makes it possible in principle, since the encoder and decoder run simultaneously. But none is doing it yet. The Verdict The gap between open-source TTS and production cloud systems is narrower on naturalness than most engineers assume, and wider on infrastructure than most engineers plan for. VibeVoice at 0.5B on a local Mac rated nearly equivalent to Nova Sonic v2 in naturalness. Kokoro-82M, trained for ~$1,000, produced competitive output. Maya1 at sub-100ms rated at ElevenLabs quality. These are not consolation prizes. Emotion control is where the fragmentation hurts: no common benchmark, no consensus paradigm, and no single model that combines voice quality, expressive range, production-grade latency, and a permissive license. So the question worth asking before you pick a model isn’t “Which model is best?” It’s “Where does emotion get decided in my pipeline?” If it comes from an LLM upstream, inline tag injection is the natural fit. If it’s a casting decision, Voxtral’s presets fit. If you need studio-level control over individual dimensions, Ming-Omni’s parameter surface points the right direction. The architecture sets the control surface, which shapes the production workflow. Getting that mapping right before you commit saves a lot of refactoring later. Want the full picture? The complete technical write-up goes architecture-by-architecture, includes the full benchmark tables and the latency chart, and lets you play every emotion clip from every model side by side. Ervin Shaqiri & Alexandre Domingues · Loka · 2026 References “DiVA.” DiVA, diva-audio.github.io. “fishaudio/s1-mini · Hugging Face.” Hugging Face, 6 February 2026, huggingface.co. Accessed 6 May 2026. “FunAudioLLM/Fun-CosyVoice3–0.5B-2512 · Hugging Face.” Hugging Face, 23 May 2025, huggingface.co. Accessed 6 May 2026. “hexgrad/Kokoro-82M · Hugging Face.” Hugging Face, huggingface.co. Accessed 6 May 2026. “inclusionAI/Ming-omni-tts-0.5B · Hugging Face.” Hugging Face, 21 April 2026, huggingface.co. Accessed 6 May 2026. “maya-research/maya1 · Hugging Face.” Hugging Face, huggingface.co. Accessed 6 May 2026. “microsoft/VibeVoice-Realtime-0.5B · Hugging Face.” Hugging Face, huggingface.co. Accessed 6 May 2026. “mistralai/Voxtral-4B-TTS-2603 · Hugging Face.” Hugging Face, 26 March 2026, huggingface.co. Accessed 6 May 2026. “nari-labs/Dia2–2B · Hugging Face.” Hugging Face, huggingface.co. Accessed 6 May 2026. “nvidia/magpie_tts_multilingual_357m · Hugging Face.” Hugging Face, huggingface.co. Accessed 6 May 2026. “nvidia/personaplex-7b-v1 · Hugging Face.” Hugging Face, 15 January 2026, huggingface.co. Accessed 6 May 2026. Poccia, Danilo. “Introducing Amazon Nova 2 Sonic: Our new speech-to-speech model for conversational AI | Amazon Web Services.” AWS, 2 December 2025, aws.amazon.com. Accessed 6 May 2026. “Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice · Hugging Face.” Hugging Face, 22 January 2026, huggingface.co. Accessed 6 May 2026. “ResembleAI/chatterbox · Hugging Face.” Hugging Face, huggingface.co. Accessed 6 May 2026. “sesame/csm-1b · Hugging Face.” Hugging Face, 13 March 2025, huggingface.co. Accessed 6 May 2026."},{"href":"/aws-bedrock-guardrails-implementing-an-allowlist/","title":"AWS Bedrock Guardrails — Implementing an Allowlist","description":"When building AI agents with AWS Bedrock, guardrails are your first line of defense for keeping conversations on topic. A common requirement is to restrict an agent to a pre-defined strict allowlist, blocking everything…","abstract":"When building AI agents with AWS Bedrock, guardrails are your first line of defense for keeping conversations on topic. A common requirement is to restrict an agent to a pre-defined strict allowlist, blocking everything…","tags":["Amazon Bedrock Guardrails","AI Agents","Strands Agents","Allowlisting"],"topics":[],"authors":["Guilherme Ribeiro"],"text":"4 Practical Approaches When building AI agents with AWS Bedrock, guardrails are your first line of defense for keeping conversations on topic. A common requirement is to restrict an agent to a pre-defined strict allowlist, blocking everything else. Consider you’re building a financial assistant that should strictly answer questions about investments, markets, or personal finance. Your developer intuition would most likely tell you to strictly define what constitutes a question around investments, markets, etc., and then block any question that does not pass that test. The problem? Bedrock Guardrails only supports denied topics. There is no native allowlist concept. This post walks through three approaches to work around that constraint. The Core Problem AWS Bedrock Guardrails lets you define denied topics. These are categories of conversation that should be blocked. Each topic is described in natural language, optionally with example phrases, and the service uses that description to classify incoming content. The API schema makes the limitation explicit: the type field only accepts DENY. There is no ALLOW value. Consider our previous example of a financial assistant. To express those constraints using Guardrails, your only tool is a denylist. There, you can only define what to block, but not what to allow. That’s the gap we need to work around. { \"name”: \"Off-topic Requests\", \"definition\": \"\"\" Any discussion unrelated to investments, personal finance, banking, credit, or financial markets such as cooking, sports, travel, or general knowledge. \"\"\", \"type\": \"DENY\" } This looks reasonable at first, but it’s explicitly unsupported. The AWS Bedrock Guardrails documentation states: Don’t define negative topics or exceptions. For example, ‘All contents except medical information’ or ‘Contents not containing medical information’ are negative definitions of a topic and must not be used. The definition above, “Any discussion unrelated to investments…”, is exactly this anti-pattern. AWS Bedrock Guardrails require clear, affirmative definitions of what to detect. A negation like “everything that is not finance” falls outside what the classifier is designed to handle, and AWS makes no guarantees about its behavior. Beyond being unsupported, it also doesn’t scale. The allowed set (financial topics) is small and well-defined, while its complement is essentially infinite. AWS Bedrock Guardrails have a hard limit of 30 denied topics per guardrail, so even if you tried to enumerate off-topic subjects you’d exhaust your budget long before getting close to complete coverage. So, if you need a true allowlist, you have to get creative. Approach 1 — System Prompt as Allowlist The simplest option: define the allowed topics directly in the system prompt and instruct the agent to respond with a static fallback message for anything outside that scope. from strands import Agent SYSTEM_PROMPT = \"\"\" You are a financial assistant. You may ONLY answer questions about: - Investments (stocks, bonds, ETFs, mutual funds) - Personal finance (budgeting, saving, retirement planning) - Banking and credit - Financial markets and economic indicators If the user asks about anything outside the financial domain, respond exactly with: \"I'm only able to help with financial topics. Please ask me about investments, banking, or personal finance.\" Do not deviate from this message for off-topic requests. \"\"\" agent = Agent(system_prompt=SYSTEM_PROMPT) Pros: Simple to implement, keeps the standard integration with AWS Bedrock Guardrails intact, no extra API calls. Cons: Relies on the LLM to enforce the boundary. A sufficiently creative prompt might coax the model into going off-script. It’s a soft boundary, not an infrastructure-level one. Approach 2 — Invert the Denied Topics List This is the clever one. Since AWS Bedrock Guardrails can only deny, the trick is to define your allowed topics as denied topics. Then you’d call the ApplyGuardrail API directly, before the agent, using the guardrail’s intervention as a signal that the topic is allowed. This is useful because ApplyGuardrail runs independently from model inference. You can evaluate the user request before retrieval, tool execution, or the agent loop begins, instead of relying on the agent itself to decide whether the request is in scope. The idea is to populate the denied topics list with your allowed topics. In this case, financial subjects like investments, banking, and personal finance. Then call ApplyGuardrail directly before the agent and invert the result: Allowlist decision flow: ApplyGuardrail intervention means the matched financial topic is allowed; no intervention means the input is blocked. Call ApplyGuardrail with the user’s input If the guardrail intervenes → the input matched a financial topic → it’s within the allowed domain → let it through If the guardrail does not intervene → the input didn’t match any financial topic → it’s off-topic → block it import boto3 bedrock = boto3.client(\"bedrock-runtime\", region_name=\"us-east-1\") def is_allowed_topic(user_input: str) -> bool: response = bedrock.apply_guardrail( guardrailIdentifier=\"your-guardrail-id\", guardrailVersion=\"DRAFT\", source=\"INPUT\", content=[{\"text\": {\"text\": user_input}}], ) # Guardrail intervenes = matched a financial topic = within allowed domain = allow it # Guardrail silent = no financial topic matched = off-topic = block it return response[\"action\"] == \"GUARDRAIL_INTERVENED\" Pros: Pre-model gating, operating independently of the main agent’s instructions and subsequent behaviour. This offers flexibility in working with the guardrails to suit your needs. You can apply the same guardrail for content safety policies like PII, violence and prompt injection or use two different ones: one for permitted topics and another for content policies. Cons: There is a hard limit of 30 denied topics per guardrail, so this only works if your “allowed-list” is enumerable. Note: AWS themselves documented this exact pattern in a Builder Center article. Approach 3 — Strands Hook + Inverted AWS Bedrock Guardrails This approach leans into the Strands SDK’s hook system to intercept the request before the agent invocation begins. Strands provides a BeforeInvocationEvent that fires once per user request, before the agent loop starts. The event exposes both a messages field (the full conversation so far) and a cancel field: set it, and the invocation is aborted with your custom message. Note: BeforeModelCallEvent also has a cancel field but fires before every model call, including intermediate tool-use rounds, and does not expose messages. For topic classification, BeforeInvocationEvent is the right hook: it runs once, at the entry point. from strands import Agent from strands.hooks import BeforeInvocationEvent async def topic_guard_hook(event: BeforeInvocationEvent) -> None: user_input = event.messages[-1][\"content\"] if not await is_allowed_topic(user_input): event.cancel = \"I'm only able to help with financial topics. Please ask me about investments, banking, or personal finance.\" agent = Agent(system_prompt=SYSTEM_PROMPT) agent.add_hook(topic_guard_hook, BeforeInvocationEvent) Making It Fast: Async Parallel Checks The real win here is that you can run both the allowlist classification and the content safety guardrail concurrently, so total latency is the max of the two, not their sum. For this, you can use asyncio.to_thread to make apply_guardrail awaitable: import asyncio import boto3 from strands import Agent from strands.hooks import BeforeInvocationEvent bedrock = boto3.client(\"bedrock-runtime\", region_name=\"us-east-1\") async def apply_guardrail_async(text: str, guardrail_id: str, version: str, source: str) -> dict: return await asyncio.to_thread( bedrock.apply_guardrail, guardrailIdentifier=guardrail_id, guardrailVersion=version, source=source, content=[{\"text\": {\"text\": text}}] ) async def topic_guard_hook(event: BeforeInvocationEvent) -> None: user_input = event.messages[-1][\"content\"] # Run both checks concurrently allowlist_check, content_safety_check = await asyncio.gather( apply_guardrail_async(user_input, \"allowlist-guardrail-id\", \"DRAFT\", \"INPUT\"), apply_guardrail_async(user_input, \"content-safety-guardrail-id\", \"DRAFT\", \"INPUT\"), ) # Allowlist: guardrail silent = no financial topic matched = off-topic (inverted logic from Approach B) if allowlist_check[\"action\"] == \"NONE\": event.cancel = \"I'm only able to help with financial topics. Please ask me about investments, banking, or personal finance.\" return # Content safety: standard logic — intervenes = blocked content if content_safety_check[\"action\"] == \"GUARDRAIL_INTERVENED\": event.cancel = \"I'm unable to respond to that request.\" agent = Agent(system_prompt=SYSTEM_PROMPT) agent.add_hook(topic_guard_hook, BeforeInvocationEvent) Approach 4 — Strands Hook + Lightweight LLM This one is a variant of the Hooks approach. It still uses the BeforeInvocationEvent to filter the content, however, instead of inverting the Guardrails denied list as your allowed list, you can use a fast model like Claude Haiku 4.5 as your topic classifier. This gives you more flexibility in defining the allowed domain without being constrained to 30 topics, and the natural-language definition can be more nuanced. import asyncio import json import boto3 bedrock = boto3.client(\"bedrock-runtime\", region_name=\"us-east-1\") CLASSIFIER_PROMPT = \"\"\" You are a topic classifier for a financial assistant. Determine if the user's question is within the financial domain. The financial domain includes: investments (stocks, bonds, ETFs), personal finance, banking, credit, financial markets, and economic indicators. Respond with JSON only: {\"allowed\": true} or {\"allowed\": false} \"\"\" async def classify_topic_with_llm(user_input: str) -> bool: response = await asyncio.to_thread( bedrock.converse, modelId=\"us.anthropic.claude-haiku-4-5-20251001-v1:0\", system=[{\"text\": CLASSIFIER_PROMPT}], messages=[{\"role\": \"user\", \"content\": [{\"text\": user_input}]}], inferenceConfig={\"maxTokens\": 50, \"temperature\": 0}, ) result = json.loads(response[\"output\"][\"message\"][\"content\"][0][\"text\"]) return result.get(\"allowed\", False) async def topic_guard_hook(event: BeforeInvocationEvent) -> None: user_input = event.messages[-1][\"content\"] # Run allowlist check (LLM) and content safety check (Guardrails) concurrently is_allowed, safety_check = await asyncio.gather( classify_topic_with_llm(user_input), apply_guardrail_async(user_input, \"content-safety-guardrail-id\", \"DRAFT\", \"INPUT\"), ) if not is_allowed: event.cancel = \"I'm only able to help with financial topics. Please ask me about investments, banking, or personal finance.\" return if safety_check[\"action\"] == \"GUARDRAIL_INTERVENED\": event.cancel = \"I'm unable to respond to that request.\" Pros: Pre-model enforcement (no LLM tokens wasted on blocked requests), concurrent execution keeps latency low, clean separation of allowlist logic from content safety, flexible classifier definition. Cons: Adds a classifier LLM call to every request (cost and latency of Haiku is low but non-zero). The Guardrails inverted-logic variant might be cheaper but inherits the 30-topic limit. Comparing the Four Approaches Approach Best for Enforcement point Topic scope Extra latency Main trade-off System prompt Quick prototypes Inside the main LLM Flexible None Easy, but relies on the model following instructions Inverted Guardrails Small, well-defined domains Before the agent/model Up to 30 denied topics +1 ApplyGuardrail call Model-independent from the main LLM, but still classifier-based App/Strands hook + Inverted Guardrails Production agent flows with small domains Before the agent loop Up to 30 denied topics +1 ApplyGuardrail call; can run alongside safety checks Clean lifecycle integration, but inherits Guardrails topic limits App/Strands hook + LLM classifier Broader or nuanced domains Before the agent loop Flexible +1 lightweight model call; can run alongside safety checks More flexible, but adds cost and another classifier to evaluate Note: Strands hooks are not required for the inverted Guardrails pattern. They are an integration point for Strands-based agents, letting you run the check before the agent loop starts and cancel the invocation when needed. Closing Thoughts Bedrock Guardrails does not currently provide a native “allow only these topics” control. But by combining ApplyGuardrail, inverted denied-topic logic, and Strands hooks, you can enforce topic boundaries before the agent loop starts. The key design choice is whether your allowed domain is small enough to enumerate. If it is, inverted Guardrails are simple and model-independent. If it is not, a lightweight classifier gives you more flexibility, at the cost of an extra model call. In either case, treat the allowlist check and safety guardrails as separate layers. Topic scoping decides whether the request belongs to your product domain. Safety guardrails decide whether the request is acceptable to process at all. If you’ve hit this constraint before or found another workaround that was not covered here, we’d love to hear about it. References Amazon Bedrock Guardrails — Denied Topics GuardrailTopic API schema ApplyGuardrail API Reference Use the ApplyGuardrail API independently On Explicit Allows with Amazon Bedrock Guardrails — AWS Builder Center Strands Agents — Hooks documentation Strands Agents — Hook events API reference Claude Haiku 4.5 Model Card — AWS Bedrock"},{"href":"/tts-emotion-benchmark/","title":"Pushing Open-Source TTS Models to Their Limits","subtitle":"Six Paradigms, 14 Models, One Production Reality Check","description":"Fourteen open-source text-to-speech models across six emotion-control paradigms, benchmarked against AWS Nova Sonic v2 on naturalness, expressiveness, latency, and licensing.","abstract":"Fourteen open-source text-to-speech models across six emotion-control paradigms, benchmarked against AWS Nova Sonic v2 on naturalness, expressiveness, latency, and licensing.","tags":["TTS","Nova Sonic","Emotion Control","Benchmarking"],"topics":[],"authors":["Ervin Shaqiri","Alexandre Domingues"],"text":"In the digital audio subset of AI, the questions currently on everyone’s mind are: Which models can express emotion? Are any of them actually usable in production? And do open source models provide the same performance? To investigate, a single sentence was run through 14 open-source text-to-speech (TTS) models over several weeks, benchmarked each of them against AWS Nova Sonic v2 as a production reference. The takeaway is that the AI audio space is more fragmented than expected and more capable than the discourse suggests. It’s also hiding several traps that will cost you time if you don’t know where to look. This post documents each model’s exact capability of producing emotion awareness when generating audio while also logging the difficulty in manipulating the expressiveness. Why Emotion Is the Hard Problem in TTS Generating intelligible speech is largely a solved problem. Every one of the 14 models can read a sentence clearly. The gap between a demo and a deployable product is almost never intelligibility. Instead, it’s affect. Does the voice sound like it means what it says? Can it express urgency without sounding robotic? Can it laugh without sounding like a waveform artifact? This type of nuance turns out to be a much harder architectural problem than clarity is. Clarity is a function of the acoustic model learning correct phoneme mappings, but affect requires the model to encode prosodic variation (pitch contour, timing, breathiness, vocal effort) in a way that is semantically interpretable, temporally consistent, and controllable at inference time. These are three separate requirements, and most models only satisfy one or two of them. The result is six distinct paradigms across the fourteen models, with almost no overlap between approaches and no consensus on which is correct. Architecture First: How These Models Are Built Before comparing emotion paradigms it is worth understanding what these models are at the architecture level, because the architecture determines what kinds of emotion control are even possible. Autoregressive Language Model Backbones Maya1, Chatterbox, and Voxtral-4B-TTS all use large language model backbones as their primary generation engine. Maya1 uses a Llama-style 3B decoder with a SNAC codec at 24kHz output. Chatterbox uses a 0.5B Llama backbone. Voxtral decomposes into three learned components: a 3.4B Ministral-3B transformer decoder, a 390M flow-matching acoustic transformer, and a 300M symmetric neural audio codec. The implication for emotion control is significant. Autoregressive LM backbones generate tokens sequentially and are sensitive to the full preceding context, including any emotion tags in the input text. This is why inline tag injection works so naturally on these architectures. The tags are just more input tokens; the model has been trained to condition its audio token predictions on them in the same way it conditions on any other semantic content. Flow-Matching and Diffusion Decoders VibeVoice-Realtime-0.5B uses a diffusion-based decoding approach on top of an acoustic tokenizer with 3200× downsampling. CosyVoice 3 uses a flow-matching decoder. Voxtral’s middle component, the 390M acoustic transformer, is also flow-matching based. Flow-matching models learn to iteratively refine a noisy acoustic representation into a clean one, conditioned on the text and any style inputs. This gives them strong control over prosodic style but makes streaming harder: You typically need several denoising steps before audio is ready to emit. CosyVoice 3 achieves bi-streaming by interleaving text encoding and audio decoding steps, but the implementation complexity reflects the underlying difficulty. Non-Autoregressive and Hybrid Architectures Kokoro-82M is a StyleTTS 2 model with an ISTFTNet vocoder. StyleTTS 2 uses a diffusion-based style encoder to capture prosody independently of content, then synthesizes waveforms directly via adversarial training. The architecture is what makes Kokoro fast and natural simultaneously; the vocoder is dramatically cheaper at inference than a full autoregressive decode, and the style encoder does expressive work that the parameter count alone does not suggest. Magpie TTS 357M uses multi-codebook prediction with a local transformer refinement step. Ming-Omni-TTS-0.5B is a unified generation model that jointly synthesizes speech, ambient sound, and music in a single channel, an architectural choice that explains both its unique ambient sound capability and its weaker base voice quality, because it’s optimizing across a much larger output space. Full-Duplex Architecture (A Different Problem Entirely) NVIDIA PersonaPlex and AWS Nova Sonic v2 operate on a different architectural premise from everything else in this comparison. They are dual-stream models: The encoder and decoder run simultaneously, enabling true listen-and-speak concurrency. PersonaPlex achieves a 90.8% smooth turn-taking success rate and 95.0% interruption success rate on FullDuplexBench, the only published benchmark numbers for open-model full-duplex capability. Every other model in this set is half-duplex that generates sequentially. The application layer has to manage turn-taking, VAD, silence detection, and barge-in logic manually. This is not a minor implementation detail. It’s a fundamental architectural constraint that no amount of prompt engineering removes. The Six Emotion Paradigms The biggest surprise was not any individual model’s quality, but how differently the field has conceptualized the problem of emotion control. These are not interchangeable design choices. They encode fundamentally different assumptions about where in a pipeline emotion should be decided, represented, and executed. 1. Inline Tag Injection Models: AWS Nova Sonic v2, CosyVoice 3, Maya1 Emotion tags are inserted directly into the text string: [laugh], [sigh], <whisper>, <cry>, <gasp>. The upstream LLM decides when and where to place them; the TTS model conditions its generation on them. This is the most composable architecture for agentic pipelines. The LLM becomes the emotion director with zero additional infrastructure. Its output is already the input to TTS, tags included. Nova Sonic v2 was designed precisely for this pattern: a language model upstream makes all expressive decisions, and the voice model executes them faithfully. Maya1 extends the paradigm with 20+ tags covering <giggle>, <chuckle>, <sigh>, <gasp> alongside the expected <laugh> and <whisper>. It also supports natural language zero-shot voice descriptions. You can specify a voice entirely in prose rather than selecting from a catalog, which opens up character voice design at a level that no other open model matches. The limitation: Tags must be placed before generation. You cannot change the emotional direction of a sentence mid-generation. If the LLM places a <laugh> and the audio is already streaming, you cannot retract it. 2. Parenthetical Markers Models: fishspeech S1 mini 49 tags: (laughing), (sobbing), (whispering), (angry), (sad), (excited), (proud), (disgusted), (panting), (groaning) and 39 more. The largest expressive vocabulary in this entire set by a factor of two. The implementation mechanism is similar to inline injection but the annotation syntax differs and the vocabulary is richer. fishspeech was trained on 2M+ hours of data across 13 languages with online RLHF and achieved strong intelligibility metrics: WER of 0.011, CER of 0.005. On paper, this is the most expressive system available. In practice, the base voice quality rated as the weakest of all locally-runnable models tested. This is the core problem with parenthetical markers at scale: the tag vocabulary is a ceiling, not a floor. If the model’s neutral voice is not good, none of the 49 tags will make the emotional outputs convincing. A well-delivered neutral is worth more than 49 tags on a voice that does not sound right. 3. Continuous Exaggeration Slider Models: Chatterbox No emotion type selection. No tags. A CFG exaggeration dial (0.0 to 1.0+) controls how intensely the model expresses the emotional content it infers from the text, combined with a Pace dial for delivery speed. The model reads the sentence, decides what emotional quality it contains, and scales that quality up or down. This is the closest paradigm to how a voice director actually works. The direction is not “say this line angry,” it is “give me 30% more on that line.” The model handles the semantic interpretation; the engineer handles the intensity. What makes this hard to use: There is an uncanny valley in the exaggeration range. Somewhere between 0.7 and 1.0, varying by sentence, voice, and content type, the output stops sounding like a person and starts sounding like an actor performing for an empty room. Finding the usable ceiling requires calibration per character and per content type that no documentation prepares you for. The pattern that emerged from testing: Simple, emotionally clear sentences tolerate higher exaggeration; complex or ironic sentences collapse into artifacts at values where simple sentences still sound natural. Chatterbox is also the most interesting model for voice cloning combined with emotion control. Zero-shot voice cloning from a short reference clip, combined with the exaggeration dial, means you can clone a voice and then independently control how expressively it performs, which is a capability no other open model in this set provides cleanly. 4. Fine-Grained Parameter Control Models: Ming-Omni-TTS-0.5B Independent axes: rate, pitch, volume, emotion, dialect. Each is set at inference time. Emotion accuracy benchmarks at 76.7% on CV3-Eval. The only model in this set with a published emotion accuracy number. The control surface is architecturally the most complete. In a studio-quality voice design workflow, independent knobs for rate, pitch, and emotion are exactly what you want because they map directly to the dimensions a sound designer would reach for. The model also handles math expressions, chemical equations, and rate/pitch/volume/dialect in a unified generation channel alongside ambient sound and music, which is a genuinely novel architectural capability. The problem is the base voice. In testing, Ming-Omni produced the least natural-sounding output of any model in the comparison. The unified multi-output architecture (speech + ambient + music in a single channel) appears to distribute model capacity across a much larger output space than pure TTS models, and the voice quality reflects that tradeoff. The parameter knobs are real and functional; they are operating on a voice that was already a weak starting point. 5. Voice Style Presets Models: Voxtral-4B-TTS-2603 (Mistral AI) Twenty named voice presets (cheerful_female, casual_male, neutral_male, casual_female) where emotion is encoded in the persona choice rather than in text markup. The model additionally handles neutral, happy, and sarcastic tones contextually from the input text, without explicit selection. This paradigm reframes the problem. Instead of asking “What emotion should this line have?” it asks “Who is saying this line?” The affective output follows from the character, not from the annotation. It is a casting decision, not a direction decision, and that maps onto a different set of production workflows. A customer service voice agent does not need [excited] tags on every happy response; it needs to be cast as a naturally warm persona. Hardware requirement: ≥16GB VRAM on a single GPU. Not Mac-compatible. vLLM is the recommended serving framework. Single-request latency is 70ms, but this climbs to 331ms at 16 concurrent requests and 552ms at 32, an 8× increase that matters enormously for multi-tenant deployments. 6. Built-In Contextual Emotion Models: Qwen3-TTS Emotion is a first-class property of the voice model itself. No explicit tagging required; the model infers appropriate affect from text semantics and delivers it without annotation. This is the highest-trust paradigm. You’re betting that the model’s interpretation of emotional content matches the intended delivery. The practical advantage is zero engineering overhead for emotion: no tags to insert, no sliders to calibrate, no presets to select. The practical risk is that you cede control. When the model’s interpretation diverges from the intended effect (and it will), there is no lever to correct it short of rewriting the input text. Does Scale Actually Help? This is the question that the data answers most clearly, and the answer is no, not in the way conventional ML intuition suggests. Model Params Training Data Naturalness Result Kokoro-82M 82M < few hundred hours Very natural, surprising Magpie TTS 357M 50,000 hours Very natural, surprising VibeVoice 0.5B Not disclosed Almost the same feel as Nova Sonic v2 Chatterbox 0.5B 500,000 hours Very natural when tuned correctly CSM-1B 1B Not disclosed Sounds great fishspeech S1 mini 0.5B 2,000,000+ hours Sounds funny DiVA 8B CommonVoice Robotic DiVA at 8B parameters is the most computationally expensive locally-runnable model in this set and produces the worst output. fishspeech trained on 40× more data than Magpie and rated significantly worse. Kokoro-82M was trained on a few hundred hours for roughly $1,000 of compute and rated alongside models trained on orders of magnitude more data and cost. The differentiator is architecture and data curation, not scale. Kokoro’s training data was hand-selected from CC-licensed and public domain sources. Magpie used well-documented, curated multilingual datasets. fishspeech used a large but unlabeled proprietary corpus. StyleTTS 2’s style encoder extracts prosodic features that the raw parameter count of an 82M model does not suggest it could capture. The architecture does efficiently what larger models achieve by brute force. The secondary finding: Magpie achieves CER of 0.34% on LibriTTS test-clean with a fully disclosed, reproducible training set. That is a state-of-the-art result on an open model under 400M parameters. Scaling laws in TTS are not what they are in language modeling. Hardware Reality: What Actually Runs Where This matters more than most model cards acknowledge. Model Mac (MPS/CPU) GPU Required VRAM Latency Kokoro-82M Yes, blazing fast No Minimal Unquantified (very fast) Magpie TTS 357M Yes No Minimal Unquantified (very fast) VibeVoice-0.5B Yes No Low ~300ms Chatterbox Yes No Low <200ms Maya1 Yes (MPS/CPU) No Low Sub-100ms (vLLM) Ming-Omni-TTS Yes No Low Not Specified CSM-1B Yes, slow No Medium Slow Dia-2B Yes No Medium Starts early Voxtral-4B-TTS No Yes (≥16GB VRAM) ≥16GB 70ms single / 552ms @32 CosyVoice 3 Tedious Yes preferred Medium ~150ms fishspeech S1 mini Extremely slow Yes (CUDA) Medium Very slow on Mac DiVA Very difficult Yes preferred High Not specified PersonaPlex No Yes (NVIDIA) High 170ms / 240ms The practical split is: Maya1, Kokoro, Magpie, VibeVoice, and Chatterbox run well on Mac and represent the realistic local-first stack. Everything else requires infrastructure investment, and some (Voxtral, PersonaPlex, fishspeech) require it as a hard prerequisite. For Mac-first development workflows, the local-capable tier is surprisingly strong. Maya1 at sub-100ms with ElevenLabs-level quality sets a bar that would have been considered cloud-only two years ago. Production Gotchas Latency benchmarks lie at single concurrency. Voxtral’s 70ms climbs to 552ms under 32 concurrent requests. That is not a linear degradation. It reflects contention on the flow-matching acoustic transformer, which is the compute-intensive middle component. If you are benchmarking for a production decision, test at your expected p95 concurrency, not at one. Concurrent requests Latency (ms) 1 request 70 16 concurrent 331 32 concurrent 552 View numeric chart data Series Concurrent requests Latency (ms) Latency (ms) 1 request 70 Latency (ms) 16 concurrent 331 Latency (ms) 32 concurrent 552 Figure 1. Voxtral-4B-TTS single-request latency scales roughly 8× from 1 to 32 concurrent requests: a number that looks great at concurrency 1 collapses under load. Watermarking is absent almost everywhere. 12 of 14 open models ship with no audio provenance mechanism. Only VibeVoice (dual: imperceptible digital + audible disclaimer) and Chatterbox (Perth watermarking; survives MP3 compression, audio editing, and mixing) provide attribution for generated audio. As regulatory frameworks for synthetic media mature, this gap will go from optional to mandatory. Building on a model with no watermarking now means retrofitting later. Two models are non-commercial, and HuggingFace does not make this obvious. fishspeech S1 mini is CC-BY-NC-SA-4.0. Voxtral-4B-TTS is CC BY-NC 4.0, notable given Mistral’s general track record of Apache/MIT licensing on their language models. Both appear in search results alongside permissively-licensed models with no visual differentiation. Read the license before building any pipeline dependency. Chatterbox’s exaggeration slider has no safe default. The documentation suggests 0.5 as a starting point. Testing showed that 0.5 is too low for expressive content and too high for matter-of-fact sentences. The usable range is narrower than the dial suggests and varies by content type. Plan for calibration time. CosyVoice 3 is architecturally compelling and operationally painful. Cross-lingual zero-shot voice cloning at 77.4 to 78% speaker similarity (clone an English speaker and generate German in their voice) is the most powerful capability in this entire comparison. The implementation complexity on Mac is high enough that testing was abandoned. If you want CosyVoice 3 in production, budget for a Linux GPU server and a non-trivial setup investment. Missing Pieces The most important capability that does not exist in any of these models is continuous real-time emotion modulation during streaming generation. Every system here requires the emotional direction to be decided before or during text generation in the prompt, the tags, the preset selection, the exaggeration value. Once audio generation starts, the emotional character of the output is fixed. What does not exist is a model that can shift its affective tone mid-stream in response to live conversational context, the way a human naturally modulates when they hear a laugh in the middle of a sentence and shift register accordingly. This is the architectural gap that separates current TTS from genuinely conversational speech synthesis. It requires a feedback loop between the audio decoder and the semantic context at generation time, not just at prompt time. The inline tag injection models (Maya1, CosyVoice 3) come closest because the LLM can insert tags mid-output before the full sentence is generated if the streaming architecture supports token-level handoff from LLM to TTS. But even this is a latency hack, not a true solution. The full-duplex models (Nova Sonic v2, PersonaPlex) are the only ones where the architecture makes real-time modulation possible in principle. They are not doing it yet either, but they’re the only systems where the encoder and decoder are running simultaneously, which is the prerequisite for building it. Emotion Expressiveness Eight of the fourteen models support explicit emotion control, each using one of the paradigms above. The same nine emotion categories were run through all eight from a single charged sentence: “I can’t believe you actually did that. I’ve been waiting for this moment for years.” Play any cell to hear it; only one clip plays at a time. Emotion AWS Nova Sonic v2 (Inline tags [laugh]) Qwen3-TTS (Built-in) Chatterbox (Exaggeration slider) fishspeech S1 mini (Parenthetical) Ming-Omni-TTS (emotion= param) Maya1 (Inline tags <laugh>) Voxtral-4B-TTS (Voice style presets) Magpie TTS 357M (Inline tags [angry]) Angry Audio Audio Audio Audio Audio Audio Audio Audio Breath Audio Audio Audio – Audio – Audio Audio Excited Audio Audio Audio Audio Audio Audio – Audio Fearful Audio Audio Audio Audio Audio Audio Audio Audio Laugh Audio Audio Audio Audio Audio Audio Audio Audio Sad Audio Audio Audio Audio Audio Audio Audio Audio Sigh Audio Audio Audio Audio Audio Audio Audio Audio Surprised Audio Audio Audio Audio Audio Audio Audio Audio Whisper Audio Audio Audio Audio Audio Audio Audio Audio The True State of the AI Audio Space The gap between open-source TTS and production cloud systems is narrower on naturalness than most engineers assume, and wider on infrastructure than most engineers plan for. VibeVoice at 0.5B parameters running on a local Mac was rated as nearly equivalent to Nova Sonic v2 in naturalness. Kokoro-82M trained for roughly $1,000 of compute produced output competitive with models trained at orders of magnitude higher cost. Maya1 running on MPS/CPU at sub-100ms was rated at ElevenLabs quality. These are not consolation prizes. Emotion control is where the fragmentation hurts. There is no common benchmark, no consensus paradigm, and no single model that combines voice quality, expressive range, production-grade latency, and a permissive license. The inline tag injection models are the most composable. Chatterbox’s slider is the most director-friendly. Voxtral’s presets are the most persona-driven. Qwen3’s contextual approach has the lowest engineering overhead. None of them does everything. The question worth asking before selecting a model is not “Which model is best?” It’s “Where does emotion get decided in my pipeline?” If emotion decisions come from an LLM upstream, inline tag injection is the natural fit. If emotion is determined by casting (by choosing a voice persona), Voxtral’s preset model is more appropriate. If you need studio-level control over individual expressive dimensions, Ming-Omni’s parameter surface is the right direction even if the current base voice is a limitation. The architecture sets the control surface, which in turn shapes the production workflow. Getting that mapping right before committing to a model saves a lot of refactoring later. Citation If you find this work useful, please cite: @misc{shaqiri2026tts, title = {Pushing Open-Source TTS Models to Their Limits: Six Paradigms, 14 Models, One Production Reality Check}, author = {Shaqiri, Ervin and Domingues, Alexandre}, year = {2026}, month = jul, howpublished = {Loka blog post}, url = {https://lokahq.github.io/tts_models_benchmark_blog/} } References DiVA. diva-audio.github.io fishaudio/s1-mini · Hugging Face. Hugging Face, 6 February 2026. huggingface.co/fishaudio/s1-mini FunAudioLLM/Fun-CosyVoice3-0.5B-2512 · Hugging Face. Hugging Face, 23 May 2025. huggingface.co/FunAudioLLM/Fun-CosyVoice3-0.5B-2512 hexgrad/Kokoro-82M · Hugging Face. Hugging Face. huggingface.co/hexgrad/Kokoro-82M inclusionAI/Ming-omni-tts-0.5B · Hugging Face. Hugging Face, 21 April 2026. huggingface.co/inclusionAI/Ming-omni-tts-0.5B maya-research/maya1 · Hugging Face. Hugging Face. huggingface.co/maya-research/maya1 microsoft/VibeVoice-Realtime-0.5B · Hugging Face. Hugging Face. huggingface.co/microsoft/VibeVoice-Realtime-0.5B mistralai/Voxtral-4B-TTS-2603 · Hugging Face. Hugging Face, 26 March 2026. huggingface.co/mistralai/Voxtral-4B-TTS-2603 nari-labs/Dia2-2B · Hugging Face. Hugging Face. huggingface.co/nari-labs/Dia2-2B nvidia/magpie_tts_multilingual_357m · Hugging Face. Hugging Face. huggingface.co/nvidia/magpie_tts_multilingual_357m nvidia/personaplex-7b-v1 · Hugging Face. Hugging Face, 15 January 2026. huggingface.co/nvidia/personaplex-7b-v1 Poccia, Danilo (2025). Introducing Amazon Nova 2 Sonic: our new speech-to-speech model for conversational AI. AWS. aws.amazon.com Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice · Hugging Face. Hugging Face, 22 January 2026. huggingface.co/Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice ResembleAI/chatterbox · Hugging Face. Hugging Face. huggingface.co/ResembleAI/chatterbox sesame/csm-1b · Hugging Face. Hugging Face, 13 March 2025. huggingface.co/sesame/csm-1b"},{"href":"/running-six-open-source-cofolding-models-on-aws-lessons-learned-from-a-compute-perspective/","title":"Running Six Open-Source Cofolding Models on AWS: Lessons Learned from a Compute Perspective","description":"What to know before you scale cofolding jobs from five structures to ten thousand.","abstract":"A compute benchmark of six open-source cofolding models on AWS, measuring runtime, memory, and estimated cost across 29 PROTAC ternary complexes.","tags":["AlphaFold","Drug Discovery","AI","Biology","Chemistry"],"topics":["biomedical-ai","benchmarks","inference"],"authors":["Julián F. Fernández","Andres Florian","Daniel Sabogal"],"text":"What to know before you scale cofolding jobs from five structures to ten thousand. Running modern cofolding models is no longer just a question of choosing the GPU with the most VRAM. In practice, different models stress different parts of the system: GPU inference, CPU-side preprocessing, system RAM, and orchestration overhead. The model with the smaller VRAM footprint can easily be the one that ties up an instance the longest. Models such as AlphaFold3, Boltz-2, and RoseTTAFold3 can now predict multi-chain biomolecular complexes (proteins, nucleic acids, and small molecules) with impressive accuracy. But published accuracy benchmarks rarely answer a practical question: how much does it actually cost to run them, and what hardware do you need? GPU compute is expensive and scarce: a mid-range cloud GPU instance (NVIDIA L4) costs close to $1 per hour on AWS, and top-tier accelerators (H100, L40S) command several times more, so picking the wrong model/instance combination wastes both money and time. To get concrete answers, we benchmarked six open-source cofolding models (Boltz-2, Chai-1, Protenix, RoseTTAFold3, OpenFold3, and ESMFold2) on a single demanding workload: PROTAC ternary-complex prediction. We measured compute, runtime, and cost behavior on AWS, not biological accuracy (that is covered in a companion analysis). The question throughout is the one you face before committing budget: which model and instance combinations are actually efficient before you scale up? The Benchmark Setup Our workload was deliberately demanding. PROTACs (PROteolysis TArgeting Chimeras) are bifunctional molecules that recruit an E3 ubiquitin ligase to degrade a target protein, a clinically compelling modality capable of reaching targets that conventional small-molecule inhibitors cannot. The resulting ternary complex (two proteins bridged by a flexible chemical linker) is a tough compute stress test: multiple chains, a flexible bifunctional small molecule, and non-trivial MSA inputs. For the benchmark set we used 22 solved ternary structures from TernaryDB, plus 7 PROTAC structures released to the PDB after the documented training cutoffs of all six models: 10AY (2026–04–22), 9Q03 (2025–10–15), 9SAF (2025–10–01), 9SAI (2025–10–29), 9YA9 (2026–02–18), 9SV3 (2025–12–03), and 9T32 (2025–12–03). The recent cases include large three-chain complexes (9SV3 at 816 aa, 9Q03 and 9YA9 at 753 aa), which widen the input-size range to 256–816 total amino acids and make the runtime-vs-size analysis below credible across a real spread. Model Upstream source Version / commit Boltz-2 jwohlwend/boltz boltz==2.2.1 (tag v2.2.1) Chai-1 chaidiscovery/chai-lab tag v0.6.1 ESMFold2 Biohub/esm commit c94ed8d OpenFold3 OpenFold3 (build clone) commit c9bfe23, ckpt of3-p2-155k Protenix bytedance/Protenix protenix==2.0.0, ckpt v1.0.0 RoseTTAFold3 RosettaCommons/foundry commit cd4d94f (RF3) Table 1: Model versions behind each container. Checkpoints as run. Each of the six models was containerized in a dedicated Docker image and deployed as a SageMaker Processing Job (on `ml.`-prefixed instances, e.g. `ml.g6.2xlarge`), running one structure at a time with a single random seed. Model versions are listed in Table 1. MSAs were pre-generated outside the benchmark and provided from S3 storage, so MSA search time is excluded from all reported runtimes. Every model ran with its published default hyperparameters, except that we normalised the number of diffusion samples to five per run for every model so the comparison is sample-matched (RoseTTAFold3 emits six: five plus a ranked best). We did no per-case tuning and did not otherwise equalise internal workloads (recycling steps, MSA depth) across architectures. The primary comparison ran all six models on a single instance type, `g6.2xlarge` (NVIDIA L4 GPU, 24 GB VRAM, 8 vCPUs, 32 GB RAM), for an apples-to-apples comparison. To see how GPU tier affects performance, we additionally ran Boltz-2 across four `2xlarge` instance types (8 vCPU held fixed, so the GPU is the main variable) spanning the T4 to L40S range (Table 2); those instance-level comparisons used a 5-case subset and should be read directionally. Instance GPU VRAM vCPU $/hr g4dn.2xlarge T4 16 GB 8 $0.75 g5.2xlarge A10G 24 GB 8 $1.21 g6.2xlarge L4 24 GB 8 $0.98 g6e.2xlarge L40S 48 GB 8 $2.24 Table 2: Instance types used (provisioned via SageMaker Processing Jobs as the corresponding ml. instances). Listed prices (from June 2026) are approximate raw EC2 on-demand rates for us-east-1 (Linux); SageMaker bills a premium over these, so they are lower bounds (see the cost discussion) Two Observed Runtime Profiles The most striking result from profiling these jobs is that not all models use compute in the same way. The figure below shows median model-compute time and peak memory footprint (VRAM and system RAM) for all six models on the `g6.2xlarge` instance. Figure 1: Median model-compute time (Panel A) and peak memory footprint (Panel B) for six cofolding models on g6.2xlarge (NVIDIA L4, 24 GB VRAM), across 29 PROTAC ternary complexes (5 diffusion samples per run). Panel B shows peak VRAM and peak system RAM, the two limits that gate which instance a model fits on; the dotted line marks the 16 GB tier. System RAM, not VRAM, is the binding constraint for OpenFold3 (26 GB). Hatched bars in Panel A mark models with a preprocessing-heavy profile. Inference-dominant profile. In our runs, Boltz-2, Protenix, RoseTTAFold3, and Chai-1 behaved as inference-dominant workloads in this benchmark. Mean GPU utilization ranges from 37% to 75%, median model-compute time falls between 74 and 424 seconds, and peak system RAM stays at or below 12.5 GB. Wall-clock time largely tracked GPU inference; preprocessing was fast relative to the forward pass in our setup. Preprocessing-heavy profile. ESMFold2 and OpenFold3 showed a different pattern. Mean GPU utilization across the full job is only 13% and 10%, respectively, not because the GPU is unused, but because GPU inference occupied only a fraction of total wall-clock time. In our runs, the remainder appeared to be spent on CPU/RAM-side work (OpenFold3 in particular ran the highest mean CPU load, about 22%, versus 13–15% for the others). Depending on the model, this may include MSA parsing and featurization, pair representation construction, ligand featurization, or other input-preparation steps. These stages likely contributed substantially to wall-clock time and, in our setup, did not translate into sustained GPU utilization, although we did not perform stage-level tracing. We therefore describe this as an observed deployment profile rather than an intrinsic architectural property. The first surprise was that VRAM was not always the limiting factor. For OpenFold3, the hard constraint was system RAM: it required over 26 GB in our runs, ruling out 16 GB instances, while ESMFold2 peaked at 18 GB (Panel B of the figure above and the RAM column of Table 3). For these two models, instance selection should consider CPU performance and system RAM, not only GPU tier. For OpenFold3 in particular, upgrading the GPU alone was not the main driver of performance in our instance comparison. Sample count is a memory knob. Normalizing every model to five diffusion samples exposed a second memory surprise. Going from one to five samples barely changed Boltz-2’s peak VRAM (≈10 GB) but roughly doubled its model-compute time (61 s to 126 s); for ESMFold2 the opposite held, with runtime essentially flat but peak VRAM growing enough to exceed the 24 GB L4 on most cases. ESMFold2 ran within the L4 for only 14 of 29 cases; 12 required a 48 GB L40S, and three (9Q03, 9SV3, 9YA9, the largest three-chain complexes) ran out of memory even on the L40S. How a model spends additional samples, in time or in memory, is therefore itself a deployment property: more samples can quietly change which instance you need, not just how long you wait. Does a better GPU pay off? The second practical question was whether a larger GPU actually paid for itself. For inference-dominant workloads, upgrading the GPU tier seems like a natural way to reduce runtime and cost. We tested this with Boltz-2, the model for which we have the strongest evidence of inference-dominant behavior: we ran it across multiple GPU tiers and observed meaningful runtime differences across instances. We used the same five TernaryDB cases and the same Boltz-2 container (the default single-sample build; this study isolates the GPU tier, and the speedup ratio is independent of sample count) on four `2xlarge` SageMaker instance types spanning T4 to L40S. Runtime below is split into model-compute time (the model process itself) and billed time (model compute + the near-fixed container/data overhead SageMaker also charges for); we lead with model-compute time because production would amortize the overhead by batching (see the cost section). The model container, inputs, and inference settings were held fixed; the instance type was varied. Note that CPU generation, vCPU count, memory, and I/O characteristics may vary across instance families, so the GPU is not the only difference between these instances. The Figure 2 and Table 3 below show the results. Given the small case count (five structures), these results are indicative rather than definitive. Figure 2: Boltz-2 across four 2xlarge GPU tiers (median over 5 cases, 8 vCPU held fixed so the GPU is the main variable). Bars show model-compute time and billed time; as the GPU gets faster, model compute shrinks steeply (T4→L40S 4.9×) while billed time shrinks less (2.3×) because a near-fixed container/data overhead does not scale with the GPU. Mean GPU utilization drops accordingly; VRAM stays flat at ≈10 GB, so the workload is not memory-bound. Instance GPU Model (s) Billed (s) VRAM (GB) GPU util (%) Speedup vs T4 g4dn.2xlarge T4 279 527 9.9 81 1.0x g5.2xlarge A10G 88 286 9.9 37 3.2x g6.2xlarge L4 93 276 10.1 44 3.0x g6e.2xlarge L40S 57 230 10.5 25 4.9x Table 3: Boltz-2 across four 2xlarge GPU tiers (median over 5 TernaryDB cases, 8 vCPU held fixed). Model-compute time is the model process itself; billed time adds the container + data overhead. Results are indicative; a larger case set may shift these numbers. On model-compute time the T4→L40S speedup is 4.9× (279 s → 57 s). On billed time it is only 2.3× (527 s → 230 s): the GPU-independent container/data overhead does not scale with the GPU, so it dilutes the apparent benefit. Isolating model compute shows the GPU helps substantially more than the billed number implies. This is reflected in the utilization numbers. As the GPU gets faster, the inference window shrinks and mean utilization drops: from 81% on the T4 to 25% on the L40S. The workload benefits from faster hardware without requiring larger batches or more memory. The cost tradeoff. The T4 (`g4dn.2xlarge`, $0.75/hr) has the cheapest hourly rate but, being 3–5× slower, is the MOST expensive per prediction. Multiplying median model-compute time by hourly price, the L4 (`g6.2xlarge`) is the lowest cost per prediction at ≈$0.025 — it runs nearly as fast as the L40S at less than half the hourly rate (A10G ≈$0.030, L40S ≈$0.036, T4 ≈$0.058). For batch workloads the L4 is the sweet spot; the L40S buys the lowest latency at a modest premium. Preprocessing-heavy models are the exception. For these, a newer instance family can still help, just for a different reason. Running OpenFold3 on the newer `g6.2xlarge` rather than the `g5.2xlarge` cut median runtime by 1.3× (944 s to 746 s) with VRAM essentially unchanged (≈7 GB), tracking faster CPU-side stages rather than the GPU: median CPU utilization fell from 62% to 52%. Boltz-2 saw only 1.04× from the same swap (Table 3). So for preprocessing-heavy workloads, faster CPU and memory can matter more than a bigger GPU. Input Size as a Runtime Proxy For production planning, runtime predictability matters almost as much as raw speed: if you can estimate a job’s runtime up front, you can provision and budget for a batch before launching it. Can you predict how long a job will take before you submit it? For the inference-dominant models in this benchmark, total amino acid count was a strong runtime proxy. The figure below shows model-compute time plotted against total amino acid count (the sum of residues across all protein chains in the complex). Figure 3: Model-compute time vs. total amino acid count for five cofolding models across 29 PROTAC ternary complexes on g6.2xlarge. Dashed lines show linear fits for models with r ≥ 0.70. The inference-dominant models track sequence length tightly (Boltz-2, Protenix, RoseTTAFold3, Chai-1); OpenFold3 (r = 0.62) correlates only moderately, with more scatter, consistent with CPU-side variance beyond sequence length. ESMFold2 is omitted: at five samples its cases span two GPU tiers (memory limits), so a single-tier size–runtime fit is not meaningful for it. Total amino acid count is a strong predictor of model-compute time for the inference-dominant models on this dataset: Pearson r = 0.97 for Boltz-2 and Protenix, r = 0.98 for RoseTTAFold3, and r = 0.89 for Chai-1. A small calibration run (a handful of representative cases) may be sufficient to fit this relationship before scaling to larger batches. OpenFold3 shows a moderate correlation (r = 0.62), but with considerably more scatter: in our runs, CPU-side preprocessing cost appeared to vary with factors beyond sequence length alone (likely MSA depth and feature construction load), adding variance that a linear fit on sequence length cannot fully capture. Practical implication. For large-scale screening campaigns, a pre-submission cost estimate based on FASTA length can help prevent over-provisioning. This appears reliable for Boltz-2, Protenix, and RoseTTAFold3 on inputs similar to the ones tested here. For Chai-1 and OpenFold3, empirical profiling on a representative sample is a safer approach. Cost Per Prediction The headline cost numbers look low, but they should be interpreted carefully. Table 4 combines median model-compute time with public raw EC2 on-demand pricing for the `g6.2xlarge` instance ($0.978/hr = $0.000272/s) to give an estimated cost per prediction. Note that the benchmark actually ran on SageMaker Processing Jobs (`ml.g6.2xlarge`), which are billed at about a 25% premium over the equivalent raw EC2 rate ($1.222/hr on SageMaker vs $0.978/hr raw EC2); we use the EC2 price as a transparent, widely quotable lower bound, so the true SageMaker cost is higher. These are lower-bound estimates in other respects too: they exclude MSA generation, container provisioning (≈49 s, unbilled), the per-run image-pull and data-download overhead (≈150–235 s, billed but amortizable by batching; see below), failed jobs, storage, orchestration overhead, and any idle or queueing time. Model Struct./run Model (s) Billed (s) VRAM (GB) RAM (GB) Est. cost Profile RoseTTAFold3 6 74 311 6.9 8 $0.020 Inference-dominant Protenix 5 118 300 7.3 5.4 $0.032 Inference-dominant Boltz-2 5 127 305 10.1 9.6 $0.034 Inference-dominant ESMFold2 * 5 222 356 20 18.1 $0.060 Preprocessing-heavy Chai-1 5 424 596 12.1 12.5 $0.115 Inference-dominant OpenFold3 5 493 722 11.7 26 $0.134 Preprocessing-heavy Table 4: Per-prediction resource and cost summary on g6.2xlarge (L4, 24 GB), median over 29 PROTAC complexes at 5 diffusion samples per run. Model is the model process; Billed adds the container + data overhead SageMaker charges for. Est. cost is model-compute time × raw EC2 on-demand price ($0.978/hr; SageMaker is ~25% higher). Struct./run is the number of structures each model emits, so the cost is per run, not per structure. Sorted by model-compute time. Under model-compute accounting, every successful prediction cost under $0.15 on `g6.2xlarge` (under $0.20 even counting the full billed overhead). At 10,000 predictions the most efficient models cost roughly $200 (RoseTTAFold3) to $340 (Boltz-2) in model compute, but $830–850 billed at the default per-run overhead, which is exactly why batching to cut that overhead matters at scale, before MSA generation, orchestration, storage, retries, and other overhead. Real production costs will be higher. Figure 4: Where the wall-clock goes, per model, on g6.2xlarge. Billed time is the model compute plus a near-fixed container-image pull and input download; provisioning is unbilled. For the fastest models most of the bill is plumbing, not compute, so it is amortizable by batching. For the fastest models, most of the bill is not compute. RoseTTAFold3 spends about 74 s in the model but is billed for roughly 310 s; the remaining ~75% is a near-fixed container-image pull and input download, paid once per instance because we launch a fresh instance per structure (see the timing-breakdown figure above). Batching many structures onto one warm instance amortizes that overhead across the batch and is the single largest cost lever here, larger than the choice of GPU tier. A note on Chai-1: with both models now emitting five diffusion samples, its ≈3.4× longer model-compute time than Boltz-2 (Table 4) is an architectural difference rather than a sampling artifact, and it carries straight into a proportionally higher cost per run. Whether that runtime is justified depends on the accuracy tradeoff, covered in the companion post. Conclusions and Deployment Lessons Across 29 PROTAC ternary complexes, the six models split into two profiles: inference-dominant models, whose runtime scaled predictably with input size, and preprocessing-heavy pipelines (ESMFold2 and OpenFold3), where CPU and system RAM, not GPU inference, drove wall-clock time. These are empirical observations from our AWS runs, not a literature-established taxonomy. The practical upshot is that VRAM alone is a poor guide to what an instance needs: OpenFold3 never approached its VRAM ceiling yet needed over 26 GB of system RAM, and a low mean GPU utilization often reflected a short inference burst after a long CPU phase rather than an idle GPU. A few caveats bound all this. It is a compute study only (no biological-accuracy claims, which the companion analysis covers) and limited in scope: a single workload, 29 structures (5 for the instance comparisons), one cloud provider, one seed, a single run per cell with no replicates (so small differences, such as the 1.04× g5→g6, are within cloud noise), and published defaults except a normalised five diffusion samples per model. One model, ESMFold2, could not hold five samples within the 24 GB L4 for most cases and was partly run on a 48 GB L40S. Reported costs are model-computed lower bounds, excluding MSA generation, startup, retries, storage, the SageMaker premium over raw EC2, and idle time, so read them as relative comparisons rather than budgets. With that scope in mind, what we would tell anyone about to run these models at scale: Don’t pick instances on VRAM alone. VRAM decides whether a model can run, not whether it runs efficiently. Match the instance to the workload’s profile: inference-dominant models reward a faster GPU, while preprocessing-heavy ones often gain more from faster CPU and memory. Runtime is a property of the whole pipeline. MSA handling, feature construction, input parsing, and container startup all add up, especially for inputs as complex as PROTAC ternary complexes. Profiling only the model, or only the GPU, can misrepresent end-to-end cost. Conversely, billing the whole pipeline can overstate the per-prediction cost of a fast model: for RoseTTAFold3 and Boltz-2 most of the bill is a fixed container and data overhead that a production deployment amortizes by batching, not model compute. We therefore report model-compute time as the primary metric and treat the overhead as a separately-optimizable line item. Calibrate before you scale. A small run on representative cases reveals whether runtime tracks input size, whether GPU use is sustained or bursty, and whether CPU or RAM will bind, enough to size instances before launching thousands of jobs. Compute efficiency is not biological accuracy. Faster or cheaper is not automatically better. Pair the profiling here with task-specific accuracy validation (in the companion analysis) before choosing a model. Batch, don’t launch one job per structure. Because we ran a fresh instance per prediction, a near-fixed container-image pull and data download was billed every time — for the fastest models, that overhead is most of the bill. Batching many structures onto one warm instance amortizes it across the run and is the largest cost lever we found, bigger than the choice of GPU tier. Used this way, these patterns help you size the right instance before you scale, rather than discovering the bottleneck after the bill arrives."},{"href":"/watching-a-python-to-rust-rewrite-was-painful-enough-to-build-this/","title":"Watching a Python-to-Rust rewrite was painful enough to build this","description":"How we built an agent that ports Python ML code to edge hardware for space.","abstract":"How we built an agent that ports Python ML code to edge hardware for space.","tags":["Python","Rust","Edge Computing","Space","AI Agents"],"topics":[],"authors":["João Afonso Pereira"],"text":"How we built an agent that ports Python ML code to edge hardware for space. A few years ago I was working at a company where almost everything was written in Python. A colleague of mine had been learning Rust on the side, and he kept lobbying to use it on something real. Eventually we got the go-ahead for one service, on the condition that we’d write it twice, once in Python and once in Rust, and compare them in parallel. The numbers were ridiculous. Rust was around five times faster and used roughly fifteen times less memory. We were both pretty happy with ourselves until I sat down and actually saw the code. Our hundred-line Python script had turned into something like five hundred lines of Rust. Every win came with a different cost: lifetimes, borrow checker fights, manual handling of things Python had been doing for us invisibly. That was the moment that stuck with me. The performance gain was real and the engineering cost was real, and there was no version of “just go learn Rust properly” that fit into the actual week I had in front of me. This was before AI for coding existed. The only option was to give up the speedup or give up everything else I was supposed to be doing. I’ve thought about that trade-off a lot since, and it’s basically the reason space-edge exists. It’s an internal tool we built at Loka that takes Python ML code, generates equivalent C and Rust for two different edge devices, compiles and runs both, and gives you back a side-by-side report so you can make the call without having to write either of them yourself. It’s an MVP today, focused on the aerospace industry, and already deployed on AWS for internal testing, but the loop works end to end and that’s the part worth talking about. What it does The premise is straightforward. ML engineers write Python. Most of the hardware these models eventually run on (a microcontroller in a drone, a small board in a satellite, a sensor in a factory) doesn’t run Python. Somebody has to bridge that gap, and that somebody usually spends quite some time setting up a toolchain before they write a single line of useful code. space-edge does that bridging step. You paste a piece of Python, pick which target you care about, and hit send. Behind the scenes a sequence of agents kicks off: ingestion → hardware → codegen → simulation → benchmark → report → packaging The output streams back live: a build log, a diff between your Python and the generated C/Rust, a benchmark table comparing the selected hardware devices, a markdown report with a recommendation, and a downloadable zip with all the artifacts. The available hardware to test right now are is ARM Cortex-M4 microcontroller (tiny, low-power, runs on a coin cell) and an NVIDIA Jetson Nano (small Linux board with a GPU). They sit at opposite ends of the edge spectrum, which is exactly why comparing them is useful: one is small and cheap, the other is fast and hungry, and the right answer depends on what you’re trying to ship. Here’s a very simple example of a Python code you can paste in: import numpy as np def run_inference(x: np.ndarray) -> np.ndarray: W1 = np.array([[0.5, -0.3], [0.2, 0.8]], dtype=np.float32) b1 = np.array([0.1, -0.1], dtype=np.float32) h = np.maximum(0, x @ W1 + b1) W2 = np.array([[0.4], [-0.6]], dtype=np.float32) b2 = np.array([0.0], dtype=np.float32) return h @ W2 + b2 A two-layer neural network. Out the other end: four source files (C and Rust for each target), both compiled, both executed in a CPU emulator, with their outputs checked against the original Python to make sure the conversion didn’t change the answer. The Space-edge interface combines pipeline logs, generated code, hardware benchmark results, and a report. The CPU emulator is QEMU, a piece of software that pretends to be a different CPU: you feed it a binary compiled for an ARM Cortex-M4, and QEMU runs the instructions on an x86 server as if it were that chip. The reason this matters is operational. Keeping every supported board physically available, wired up, and reachable from a backend service gets painful fast, and it gets worse the more boards you add. With QEMU the M4 and the Jetson runs happen inside the same containerised pipeline, on demand, no hardware in the room. The catch is that QEMU is accurate on CPU behaviour but doesn’t model the real timing of memory accesses, interrupts, or the chip’s power profile. So the benchmark numbers are good for relative comparisons (M4 vs Jetson, version A vs version B) and weaker as absolute predictions for a real board. It also has a second mode, a Q&A assistant over the same knowledge base the codegen agent uses. You can ask things like “what’s the typical memory budget on a Cortex-M4?” and get a cited answer. Useful for the questions that come up while you’re staring at the benchmark report, mainly regarding the standards of the aerospace industry and MISRA compliance. Why aerospace, and what MISRA has to do with it This MVP is built specifically for aerospace work, and that choice shapes most of what’s interesting about the tool. If you’ve never worked in aerospace software, MISRA-C might be a new acronym. It’s a set of coding rules originally written for the automotive industry, now used across most safety-critical fields, including aerospace, medical devices, and defence. The rules ban the parts of C that are most likely to cause subtle bugs: undefined behaviour, implicit type conversions, certain pointer tricks, recursion in places where you can’t afford a stack overflow. If your code is going onto a satellite, somebody will eventually ask whether it passes MISRA, and the answer needs to be yes. space-edge runs a MISRA check after the codegen step and lists any violations in the report. The codegen agent itself pulls examples from the MISRA rules in the knowledge base while it writes, so most of the obvious violations get caught before the static analysis runs at all. The knowledge base holds two other sets of documents that are checked by the code generation agent. One is ECSS, the European Cooperation for Space Standardization. ECSS-E-ST-40C, for example, is the software engineering standard most relevant for European space projects, and it’s the kind of document where the question “have you checked your design against it?” has a real answer rather than a vague one. The other is the hardware developer manuals themselves: the ARM Cortex-M4 technical reference, the Jetson Nano data sheet, and similar specs. When the codegen agent writes Rust for the M4, it’s pulling from the actual ARM manual to get the right instructions, alignment requirements, and intrinsics, rather than guessing from training data. So the RAG corpus isn’t a generic “embedded knowledge” dump. It’s three deliberate piles: MISRA and edge-computing compliance, aerospace industry standards, and hardware specs. The codegen agent reaches into all three on every run. Architecture Agent pipeline from knowledge-base ingestion to code generation, hardware simulation, benchmarking, and report output. The agent layer uses Strands Agents on top of Bedrock (Claude Sonnet for codegen and report writing). Qdrant runs as a managed vector store, holding the three collections described above. The compilation and emulation happen inside dedicated containers (one per target hardware), and the backend talks to them through the Docker SDK. Artifacts go to S3, keyed by job ID, with presigned URLs in the download link. The whole thing is deliberately simple. A small agent graph, a fixed pipeline, a streaming UI on top. Why the pipeline isn’t agentic There’s a temptation when you’re building anything with “agents” in the name to let the LLM decide the next step. We chose not to. The pipeline steps always run in the same order. Ingestion is always followed by hardware profile loading. Code generation always comes after that. The static analysis step always needs the generated code. An LLM deciding “what’s next?” would only add cost, latency, and a new class of failure modes (imagine the agent deciding to skip the MISRA check because the code “looks fine”). We use the LLM where it earns its tokens: generating code, writing the report, routing the Q&A questions. Everywhere else, plain Python. You can see the split in the architecture diagram above: the boxes marked “LLM” or “RAG + LLM” use a model, the ones marked “No AI” don’t. The benchmark step, for example, is just arithmetic. It compares binary sizes and execution times and prints a table. Doing that with an LLM would be slower, more expensive, and less reliable, and the output would be mostly the same. I think this is the most honest thing we can say about agents right now: they’re great in certain spots and overkill in most. A pipeline with known transitions isn’t a place where you need autonomy. It’s a place where you need a clean function call. What surprised us Three things, in increasing order of usefulness. Strands’ event stream maps almost one-to-one onto a good streaming UX. We didn’t have to build a separate “agent thinking” channel; we intercepted the tool-use events Strands was already emitting, pushed them as thinking SSE frames, and let them disappear when a real progress event arrived. RAG over aerospace technical standards works embarrassingly well. These documents are dense, structured, and full of the exact terminology a developer would use in a question. A plain top-3 cosine similarity search has been good enough that we haven’t needed a reranker or hybrid search yet. The benchmark table changes how people talk about hardware choices. Before, “Jetson vs Cortex-M4” was a vibes conversation. Now it’s a row that says “Jetson Nano is 18× faster, Cortex-M4 has 1/200th the binary footprint, here’s the code that produced both.” That’s not a new insight to anyone who’s done this work, but having it auto-generated next to the source it came from is a different conversation to have with a customer. Where it goes next Real hardware in the loop is the obvious next milestone. Running in an emulator tells us the code compiles and behaves correctly; it doesn’t tell us how it actually performs on a board with real interrupts and real power draw. After that: more complexity input in the code generator (entire Python projects), proper sandboxing for the user-submitted code, and broadening beyond aerospace into the other safety-critical domains that share most of the same compliance vocabulary. The thing I keep coming back to is the version of me from a few years ago, stuck between a Python script and a Rust rewrite, with no time to do either properly. The whole point of this tool is to give that person a third option: keep working in the language you know, and let the agent do the translation that used to require a week and a colleague who’d been studying Rust on the side."},{"href":"/benchmarking-gpt-5-5-on-amazon-bedrock-vs-the-openai-api-the-engineering-walkthrough/","title":"Benchmarking GPT-5.5 on Amazon Bedrock vs. the OpenAI API: The Engineering Walkthrough with Loka","description":"The main post covers what we found: GPT-5.5 on Amazon Bedrock matches OpenAI API accuracy and comes out faster on every latency and throughput dimension we measured. This post covers how we ran it. If you want to…","abstract":"A reproducible, sequential comparison of GPT-5.5 on Bedrock Mantle and the OpenAI API across 1,319 GSM8K questions and three reasoning-effort settings.","tags":["AI","AWS","OpenAI","Machine Learning","LLM"],"topics":["inference","benchmarks"],"authors":["Petar Kalinovski","Bojan Jakimovski"],"text":"The Engineering Walkthrough The main post covers what we found: GPT-5.5 on Amazon Bedrock matches OpenAI API accuracy and comes out faster on every latency and throughput dimension we measured. This post covers how we ran it. If you want to reproduce the GSM8K numbers or adapt the harness for your own workload, this is the companion piece. The concrete question behind the benchmark was simple: Does routing GPT-5.5 through Amazon Bedrock Mantle cost you anything in answer quality, latency, or reliability compared to the native OpenAI API? We ran the full GSM8K test split — 1,319 grade-school math problems — through both provider paths at three reasoning levels (medium, high, xhigh), recording per-request streaming latency, output throughput, token usage, and failures. The benchmark harness is open and the results are saved in the repo. This post walks through the setup, the exact commands, the output format, and the design choices that made the comparison clean. For the main findings — accuracy tables, latency charts, and the two regulated-industry copilots we built on the path that passed — read the main Loka writeup: How Loka Evaluates and Builds with Frontier Models on AWS. Why GSM8K We needed a dataset that was long enough to produce stable latency distributions (1,319 requests per run means the p90 and p95 figures mean something), short enough to complete in a single session without batching or parallelism, and one where answer correctness is unambiguous and automatable. GSM8K satisfies all three. The final #### answer format makes accuracy scoring a string comparison after normalization, with no LLM judge in the loop. The math content also makes token budgets predictable. Each question fits in well under a hundred tokens. Reasoning answers are short — a few lines of working plus a numeric result. That keeps the benchmark from inflating latency through unusual output lengths and keeps costs bounded before you start. Tested Setup The measured runs used: Setting Value Bedrock model ID openai.gpt-5.5 Bedrock endpoint Bedrock Mantle, us-east-2 OpenAI model ID gpt-5.5 OpenAI endpoint https://api.openai.com/v1 Reasoning efforts medium, high, xhigh Dataset GSM8K test split, 1,319 questions Concurrency 1 (sequential) Max output tokens 4,096 Auth (Bedrock) AWS SigV4, bedrock-mantle service Auth (OpenAI) Bearer token via OPENAI_API_KEY Sequential requests were a deliberate choice. Client-side concurrency is a real variable in production, but it conflates queue effects at different concurrency levels with the underlying provider infrastructure. Running one request at a time isolates the thing we were measuring: what does each provider’s serving path cost a single in-flight request? Bootstrap the Environment The repo uses uv for dependency management. Python 3.12 or later is required. git clone https://github.com/LokaHQ/gpt-5-5-bedrock-openai-benchmark cd gpt-5-5-bedrock-openai-benchmark uv sync This installs httpx, boto3, python-dotenv, and tiktoken. The dev group adds pytest and ruff if you also want to run the test suite and linter. Configure Authentication The benchmark supports two authentication paths for Bedrock and one for OpenAI. Bedrock: AWS SigV4 (recommended) This is what we used for the main runs. The script picks up credentials from the active AWS session. For a named profile: export AWS_PROFILE=your-bedrock-profile The SigV4 signer is built in via botocore. No extra env vars are needed as long as your profile has bedrock-mantle:* and aws-marketplace:* permissions (required to subscribe to OpenAI models on Bedrock). To verify the auth is wired up before making any model calls: AWS_PROFILE=your-bedrock-profile uv run python scripts/benchmark_openai_latency.py \\ --provider bedrock \\ --auth-debug This prints the auth mode, endpoint, and signed header names without touching the model. A clean output looks like: auth_mode=sigv4 base_url=https://bedrock-mantle.us-east-2.api.aws/openai/v1 region=us-east-2 sigv4_service=bedrock-mantle signed_header_names=authorization, content-type, host, x-amz-date, x-amz-security-token, x-client-request-id Bedrock: Bearer token If your setup authenticates with a Bedrock API key instead of AWS credentials, set it in .env. You can generate one in the Bedrock console under API keys (short-term keys last up to 12 hours), with the aws-bedrock-token-generator package, or for a long-term key via aws iam create-service-specific-credential --service-name bedrock.amazonaws.com: BEDROCK_OPENAI_API_KEY=your-bearer-token # the script also reads the standard AWS_BEARER_TOKEN_BEDROCK OpenAI API Copy .env.example to .env and fill in your key: cp .env.example .env # edit .env: set OPENAI_API_KEY=sk-... The .env file is excluded from version control. Never commit it. Estimate Cost Before Running Before running against the full test split, use the cost estimator to know what you are committing to: uv run python scripts/estimate_openai_eval_cost.py \\ --dataset gsm8k \\ --split test \\ --model gpt-5.5 \\ --visible-output-tokens 256 \\ --reasoning-output-tokens 256 The estimator downloads the GSM8K test split, counts input tokens with tiktoken, and outputs a table like: Model Samples Avg input tok P95 input tok Output tok/sample Standard cost Batch cost gpt-5.5 1,319 93.5 136 512 $20.88 $10.44 The --reasoning-output-tokens figure is an estimate: OpenAI bills reasoning tokens as output tokens even though they are not returned in API responses. The actual reasoning budget at xhigh is higher than medium, so this estimate is a lower bound for xhigh runs. The cost caps in the benchmark command give you a hard stop regardless. Run the Latency Benchmark Bedrock (one reasoning effort) AWS_PROFILE=your-bedrock-profile uv run python scripts/benchmark_openai_latency.py \\ --provider bedrock \\ --region us-east-2 \\ --model openai.gpt-5.5 \\ --dataset gsm8k \\ --split test \\ --warmups 1 \\ --reasoning-effort medium \\ --max-output-tokens 4096 \\ --concurrency 1 \\ --timeout-seconds 240 \\ --max-billable-tokens 750000 \\ --max-estimated-openai-cost-usd 10.00 \\ --output-dir result/gsm8k-gpt55-medium OpenAI API (one reasoning effort) uv run python scripts/benchmark_openai_latency.py \\ --provider openai \\ --model gpt-5.5 \\ --dataset gsm8k \\ --split test \\ --warmups 1 \\ --reasoning-effort medium \\ --max-output-tokens 4096 \\ --concurrency 1 \\ --timeout-seconds 240 \\ --max-billable-tokens 750000 \\ --max-estimated-openai-cost-usd 10.00 \\ --output-dir result/openai-gsm8k-gpt55-medium Change --reasoning-effort to high or xhigh and update --output-dir accordingly for the other two runs. What the six main commands were The six benchmark runs that produced the numbers in the main post used these exact folder names: Effort Provider Output folder medium Bedrock result/gsm8k-gpt55-medium high Bedrock result/gsm8k-gpt55-high xhigh Bedrock result/gsm8k-gpt55-xhigh medium OpenAI result/openai-gsm8k-gpt55-medium high OpenAI result/openai-gsm8k-gpt55-high xhigh OpenAI result/openai-gsm8k-gpt55-xhigh-merged-clean The OpenAI xhigh folder name ends in -merged-clean because the original run hit a client-side DNS outage near the end — 181 requests failed to resolve on our own network, not on the provider’s. We retried those separately and merged the clean records back into a single JSONL before scoring, so the merged result shows 1,319 / 0 — all prompts answered, no failures — which is the number reported in the main post. That DNS outage was on our side and counts against neither provider. The genuine provider-side errors showed up elsewhere: the OpenAI medium and high runs each returned 5xx responses from OpenAI’s edge (2× HTTP 503, 1× HTTP 520), while Bedrock returned zero errors across all 3,957 requests at every effort level. What the Harness Does During a Run Each request goes through run_once(), which opens an httpx streaming connection and measures three timestamps: TTFB (time to first byte): the moment the first non-empty line arrives from the server, before any token is parsed. This is infrastructure-only: connection setup, auth, admission, routing. TTFT (time to first token): the moment the first response.output_text.delta event arrives. This includes model reasoning before the first output character is produced. Total latency: the moment the stream closes after [DONE]. Token usage — input, output, and reasoning tokens separately — comes from the usage block in the final response.done event. Output throughput (output_tokens_per_second) is derived as output_tokens / total_seconds. Each completed or failed record is written to a partial JSONL file immediately, so a crash partway through does not lose the records collected so far. The live progress line looks like this: bedrock openai.gpt-5.5 run 142/1320: ok; in=87 out=44 reasoning=312; cost=$0.003456; cumulative_tokens=18,432; cumulative_est_openai_cost=$0.4891 The cost caps (--max-billable-tokens, --max-estimated-openai-cost-usd) check after each completed request and stop the run cleanly if either threshold is crossed. Output Files Each run writes three files into the output directory: result/gsm8k-gpt55-medium/ ├── openai_responses_latency_20260610T083101Z.jsonl # per-request records ├── openai_responses_latency_20260610T083101Z_summary.json # aggregated stats └── openai_responses_latency_20260610T083101Z.md # human-readable summary The JSONL file has one record per request. Each record is a flat JSON object with the fields from BenchmarkRecord: { \"provider\": \"bedrock\", \"model\": \"openai.gpt-5.5\", \"run_index\": 142, \"prompt_index\": 141, \"prompt_id\": \"gsm8k-test-141\", \"started_at\": \"2026-06-10T08:52:13.441Z\", \"ok\": true, \"ttfb_ms\": 218.4, \"ttft_ms\": 1847.2, \"total_ms\": 2613.9, \"input_tokens\": 87, \"output_tokens\": 44, \"reasoning_tokens\": 312, \"output_tokens_per_second\": 50.2, \"output_text\": \"The total is 14 apples.\\n\\n#### 14\", \"expected_answer\": \"14 apples.\\n\\n#### 14\", \"estimated_openai_cost_usd\": 0.003456, \"request_id\": \"...\", \"error\": null } The summary JSON contains the LLMPerf-style aggregate statistics: full distributions (p25, p50, p75, p90, p95, p99, mean, min, max, stddev) for each metric across all successful requests. The Markdown file is the same summary in readable form, including a failure log if any requests errored. Score Accuracy Offline The accuracy scorer is a separate script that never touches the API. It works entirely from the saved JSONL files, which is important: you can re-score a run with an updated normalization rule without paying for another API call. To score all six main runs at once: uv run python scripts/score_gsm8k_accuracy.py --main-runs This downloads the original GSM8K test split from GitHub, extracts the #### <answer> line from both the reference and the saved model response, normalizes both (strips commas, dollar signs, trailing periods, handles Unicode minus), and compares them. The output goes into each run’s folder plus an aggregate comparison: result/ ├── gsm8k_accuracy_main_runs.json # aggregate across all six runs ├── gsm8k_accuracy_main_runs.md # Bedrock vs OpenAI deltas by effort level ├── gsm8k-gpt55-medium/ │ ├── gsm8k_accuracy_summary.json │ └── gsm8k_accuracy_summary.md └── ... To score a single run, pass --benchmark-jsonl and optionally --output-dir: uv run python scripts/score_gsm8k_accuracy.py \\ --benchmark-jsonl result/gsm8k-gpt55-medium/openai_responses_latency_20260610T083101Z.jsonl The normalization logic handles most of the common failure modes: a model writing $14.00 instead of 14, writing 14,000 with a comma, or using a Unicode minus. The scorer extracts the last #### match in the output, so reasoning steps that mention intermediate numbers do not pollute the answer comparison. The Normalization Detail That Matters The answer extractor uses the #### prefix that GSM8K itself defines. Both the reference answers from the dataset and the model answers from the benchmark follow the same format because the benchmark prompt asks the model to use it: Solve this grade-school math problem. Show concise reasoning, then put the final numeric answer on a separate line prefixed with ####. This makes the scorer deterministic and fast. The only edge cases are models that skip the #### prefix entirely (scored as missing_model_answer) or produce a format the normalizer cannot parse to a canonical number. In practice, GPT-5.5 followed the format consistently across all 1,319 questions in every run. Running at Reduced Scale Before committing to the full 1,319-question run, use --limit to test against a small slice: AWS_PROFILE=your-bedrock-profile uv run python scripts/benchmark_openai_latency.py \\ --provider bedrock \\ --model openai.gpt-5.5 \\ --dataset gsm8k \\ --split test \\ --limit 20 \\ --reasoning-effort medium \\ --max-output-tokens 4096 \\ --output-dir result/smoke-test This runs the first 20 questions, produces all the same output files, and lets you verify auth, output format, and metric collection before spending the full budget. Caveats This benchmark is intentionally narrow: It measures sequential single-stream requests from one client location. Concurrent-request behavior and multi-region comparisons are out of scope. The dataset is grade-school math. Short math prompts with compact answers are not representative of all enterprise workloads. Longer prompts or longer outputs would shift the TTFT and throughput numbers. Latency and error rates are point-in-time properties of a serving fleet. Bedrock’s zero-error rate and lower TTFB reflect the fleet as it stood in June 2026, weeks after the Bedrock launch. Both can change as load grows. Cost estimates use OpenAI’s published list prices as of June 2026. Bedrock list prices differ slightly; the main post notes the specific numbers. Those caveats do not change the main result: same model, same answer quality, faster serving on Bedrock with zero errors across nearly 4,000 requests. But they do matter when you translate these numbers to a production SLO. Takeaway The useful part is not only the latency numbers. It is the measurement discipline. The harness records every request, separates warmup from measured runs, writes partial results during the run, and scores accuracy offline from saved artifacts. That structure makes the comparison clean and reproducible. You can rerun against your own region, your own workload shape, and your own concurrency level and get numbers that mean something for your system, not just ours. For teams evaluating OpenAI on Bedrock against the first-party API, that is the starting point: run the benchmark against your own traffic shape before committing an SLO to results from someone else’s setup."},{"href":"/openai-bedrock/","title":"How Loka Evaluates and Builds with Frontier Models on AWS","subtitle":"Benchmarking GPT-5.5 on Amazon Bedrock, then building two regulated-industry copilots","description":"A comparison of GPT-5.5 through Amazon Bedrock and the OpenAI API across answer quality, latency, throughput, and reliability, followed by two production-shaped copilot builds.","abstract":"On 1,319 GSM8K questions, GPT-5.5 accuracy differed by at most 0.22 percentage points between Bedrock Mantle and the OpenAI API; Bedrock had lower time-to-first-byte and higher measured output throughput in the June 2026 sequential test.","tags":["OpenAI","GPT-5.5","Amazon Bedrock","Evaluation"],"topics":["benchmarks","inference"],"authors":["Petar Kalinovski","Bojan Jakimovski"],"text":"Introduction OpenAI GPT-5.5, GPT-5.4, and Codex are now generally available on Amazon Bedrock. For enterprises, that is more than a new catalog entry. It creates a path to use OpenAI capabilities inside the AWS security, governance, procurement, and operational controls they already run. Loka is one of only five OpenAI launch partners globally, giving us a front-row role in helping customers turn this new path into production systems. That designation is both a milestone and a practical signal. Since 2023, Loka teams have helped lead more than 500 GenAI and agentic AI launches, with over half already in production or moving there. OpenAI on Bedrock gives that work a cleaner route from experimentation to secure, scalable enterprise systems in the AWS environments customers already trust. A launch is easy to celebrate and hard to substantiate. So this post covers two things: A benchmark: GPT-5.5 on Bedrock vs. the native OpenAI API. Before we built anything, we asked the foundational question: does routing GPT-5.5 through Amazon Bedrock change the model you get? We ran the full GSM8K test split (1,319 questions) through both provider paths at three reasoning levels and compared accuracy, latency, throughput, and reliability head to head. The benchmark confirmed the same answer quality, faster serving, and zero failures on Bedrock. Two regulated-industry copilots, built on the path that passed. Using Loka’s production agent architecture and delivery patterns, we stood up the FSI Evidence Copilot (financial services: evidence packets for small-business lending, KYC refresh, and AML alert review) and the Clinical Evidence Copilot (healthcare & life sciences: synthetic-patient evidence packets for coverage and medication reviews). The point is not to expose implementation mechanics; it is to show how authentication, scoped data access, observability, guardrails, deployment, and human review can travel across use cases. They share production obligations: governed access, traceability, guardrails, deployment discipline, and, most importantly, a human-review boundary. Both prepare evidence for a human; neither makes the decision. The domain services and data sources differ by use case, but the validated model path is the same: OpenAI on Bedrock, benchmarked before it was trusted with production workloads. For the engineering walkthrough behind the benchmark harness, commands, result files, and scoring logic, read our companion blog post: Benchmarking GPT-5.5 on Amazon Bedrock vs. the OpenAI API. What we want you to take away. The useful unlock is the combination of a model-agnostic production architecture, Bedrock’s governance surface, and OpenAI-compatible APIs, all verified to be production-grade before the first line of copilot code was written. Together, they let teams move regulated workloads from prototype to production while preserving the AWS controls their security and platform teams already understand. Why OpenAI on Bedrock matters for the enterprise For enterprises already running regulated workloads on AWS, the biggest obstacle is often the operational change that follows when data, access controls, audit trails, procurement terms, and procedures move outside the approved cloud environment. A new model vendor can trigger security review, legal review, data-processing review, vendor onboarding, logging changes, and new runbooks. OpenAI models on Bedrock make the shift materially smaller because the model choice sits inside the AWS control plane teams already trust: Concern What Bedrock gives you Data residency & privacy Inference runs in the selected Bedrock Region; prompts and responses are not used to train models or shared with model providers. Identity & access Standard AWS controls such as IAM, VPC connectivity, and CloudTrail around the model invocation path. Safety Amazon Bedrock Guardrails and platform controls can be applied through supported Bedrock APIs and model paths. API fit & portability Use AWS-native APIs such as Converse for supported models, or OpenAI-compatible Responses and chat-completions APIs on Bedrock when that is the better fit. That last row is the one that compounds. For existing Bedrock-native workloads, Converse keeps a common interface across supported model families. For GPT-5.5, GPT-5.4, and Codex on Bedrock, AWS points developers to the OpenAI-compatible Responses API on the Bedrock Mantle endpoint. The exact adapter can change by workload, while the architecture stays steady: model selection belongs in configuration, while auth, evidence access, auditability, streaming, and deployment stay stable. Capability is part of the enterprise case The governance story only matters if the models are worth adopting. Today, the evidence is strongest in agentic software work: on Datacurve’s DeepSWE benchmark, which measures long-horizon repository tasks, GPT-5.5 leads the published sweep while using fewer output tokens than Opus 4.8 at comparable and higher reasoning levels. Opus 4.8 improves as reasoning effort rises and has strong results too, but its max configuration spends far more output tokens and time for a lower pass@1 than GPT-5.5 xhigh. The enterprise takeaway is that the Bedrock launch brings one of the current frontier leaders into the AWS operating model teams already use. Anthropic has since released Claude Fable 5, the first of its Claude 5 family and a tier in positions above Opus. It is new enough that the published sweeps in this post do not yet include it, and nothing in this post turns on it. Since our comparison is about provider paths for models of comparable weights, and not whatever lab holds the leaderboard for best model, we decided not to include it here. DeepSWE snapshot from Datacurve, updated May 30, 2026. X axis is mean output tokens per task; Y axis is pass@1. Each point is labeled by reasoning level. Tooltips include cost and time per task. Codex adds the adoption signal behind the benchmark story. OpenAI reports that more than 5 million people use Codex every week, with non-developers now making up about 20% of users and growing more than three times as fast as developers. That matters for enterprises because the same agentic pattern is moving from coding into analysis, reporting, workflow automation, and other knowledge work, exactly the kind of operational surface where AWS governance and procurement matter. Benchmarking GPT-5.5 on Bedrock against the OpenAI API Capability is only half the enterprise question. The other half is whether the governed model path costs you anything in accuracy, in the latency users feel, or in reliability. So we measured it. We ran the full GSM8K test split (1,319 questions) through both provider paths, with openai.gpt-5.5 on Amazon Bedrock Mantle in us-east-2 and gpt-5.5 on the OpenAI first-party API, at three reasoning efforts (medium, high, xhigh). Same prompts, same OpenAI-compatible Responses shape, same output caps, same streaming metric definitions, and sequential requests so client-side concurrency never pollutes the numbers. That setup answers two questions at once. Does quality survive the provider change, and which path is faster in practice? Accuracy survives the provider change Reasoning effort Bedrock openai.gpt-5.5 OpenAI gpt-5.5 Delta medium 97.57% 97.42% −0.15 pp high 97.57% 97.35% −0.22 pp xhigh 97.42% 97.35% −0.07 pp Bedrock edges ahead in all three runs, but the honest read is parity. The gaps are one to three questions out of 1,319, well within run-to-run noise for a sampled model. That is the result an enterprise team wants to see. It says the weights behind both endpoints behave the same, so moving the workload onto the governed AWS path costs nothing in answer quality, and everything that does differ between the two paths is serving infrastructure. Bedrock is faster where it matters Effort Provider TTFB p50 TTFT p50 Total p50 Total p90 Mean tok/s Failed medium Bedrock 220 ms 1,939 ms 2,881 ms 4,369 ms 47.4 0 / 1,319 medium OpenAI 484 ms 1,956 ms 2,859 ms 4,908 ms 39.1 2 / 1,319 high Bedrock 224 ms 2,662 ms 3,455 ms 4,801 ms 48.5 0 / 1,319 high OpenAI 497 ms 2,356 ms 3,248 ms 5,712 ms 41.3 1 / 1,319 xhigh Bedrock 223 ms 3,250 ms 3,803 ms 5,792 ms 51.8 0 / 1,319 xhigh OpenAI 502 ms 3,280 ms 4,334 ms 8,273 ms 39.7 retried* *The OpenAI xhigh run needed failed requests retried to complete all 1,319 samples; the published numbers come from the merged clean run. Bedrock completed all 3,957 requests across the three efforts with zero errors. Time to first byte (p50) by reasoning effort. TTFB is measured before any token is generated, so this is purely the API path. Bedrock answers in ~220 ms at every effort level, and the OpenAI API takes about 2.2× longer. End-to-end streamed latency, p50 (solid) and p90 (translucent). Medians are close at medium and high; the gap opens at xhigh and at the tails, where Bedrock's p90 stays 0.5–2.5 s ahead. Mean per-request output throughput. Bedrock decodes 20–30% faster at every effort level, and the gap widens as reasoning effort (and output length) grows. The medians deserve an honest read. At medium and high effort the median end-to-end latencies are effectively tied (the Bedrock high run actually spent slightly more reasoning tokens, which costs it the p50 comparison there). But every other dimension leans one way. Time to first byte is ~220 ms on Bedrock versus ~480–500 ms on the OpenAI API at every effort level. Mean output throughput is 20–30% higher on Bedrock. The tail percentiles (p90/p95) favor Bedrock in all three runs and the gap grows with effort. At xhigh, p95 is 9.2 s on Bedrock versus 11.4 s on OpenAI. Reliability went one way only. Bedrock finished nearly 4,000 calls without a single failure, while every OpenAI run had errored requests, including stalled outliers that ran past 100 seconds. Why is Bedrock faster? Our three cents The accuracy parity above is what makes the latency question interesting. If the model is the same, the difference is the serving path. Three observations from the data, offered as informed interpretation rather than inside knowledge: The TTFB gap is infrastructure, not the model. Time to first byte is measured before a single token is generated, so it captures connection setup, authentication, admission, and routing. Bedrock’s regional endpoint held a flat ~220 ms p50 across all three runs regardless of effort; the OpenAI API hovered around ~480–500 ms with a much heavier tail (p99 of ~3 s, worst cases over 100 s). That is the difference between a dedicated regional AWS endpoint and a globally shared API front door absorbing the world’s GPT-5.5 traffic. OpenAI’s throughput looks paced; Bedrock’s looks unconstrained. Across ~3,950 OpenAI requests, per-request decode speed clustered tightly (stddev ~9.5 tok/s) and never once exceeded ~67 tok/s. The observed maximum was 66.2, 66.7, and 66.7 tok/s in the three runs, which looks like a deliberate per-request ceiling or aggressive batching on a heavily multi-tenant fleet. Bedrock requests ranged up to ~108 tok/s with means of 47–52. Consistent with newer, less-contended capacity that is not yet rationing decode speed. Demand asymmetry, for now. The first-party API serves the bulk of global GPT-5.5 demand; the Bedrock endpoint launched weeks ago. Lower utilization means shorter queues, faster admission, and tighter tails, which is exactly the shape of the data, including Bedrock’s zero error rate. The honest caveat is that this part of the advantage can narrow as Bedrock adoption grows. There is also a hardware angle. Amazon’s $50 billion investment in OpenAI comes with a commitment of roughly 2 gigawatts of Trainium capacity, and in March AWS and Cerebras announced a serving architecture that splits inference across purpose-built silicon, with Trainium handling the parallel prefill phase and Cerebras wafer-scale chips handling the bandwidth-hungry decode phase. AWS is pitching it as “the fastest AI inference available through Amazon Bedrock.” We don’t know what hardware served our requests, since neither company says. The only public speed figure for OpenAI on Cerebras, at over 1,000 tokens per second, comes from a much smaller model built specifically for that hardware, so it says little about what GPT-5.5 would do there. The more useful signal is AWS’s own framing. The announcement describes the new stack as launching months later and as “an order of magnitude faster” than what Bedrock serves today. A 20–30% throughput edge is not an order of magnitude, so whatever served our requests, the new silicon doesn’t explain the gap we measured. What it does tell you is where this is going. AWS is building Bedrock to be the fastest place to run these models, and the advantage we measured is probably the early version of it. Independent corroboration. We are not the only ones measuring this. Artificial Analysis’s GPT-5.5 provider comparison reaches the same conclusion on a different workload, measuring Bedrock at 52.3 output tok/s versus OpenAI at 50.5, with materially lower end-to-end latency on their xhigh measurement (~76 s vs ~100 s to first answer token), summarized on their page as “Amazon offers the best performance with both the highest speed and lowest latency.” Their medium-effort page shows the same shape, 53.8 vs 48.3 tok/s and 7.9 s vs 9.5 s to first answer token, independently matching the direction of every latency and throughput number we measured. The flip side is also theirs. OpenAI’s list price is slightly lower ($5.00/$30.00 vs $5.50/$33.00 per 1M input/output tokens), so the trade is roughly 10% on price for the faster, more reliable path that also lives inside AWS governance. Our six GSM8K runs as a quadrant, with median end-to-end latency against mean output throughput and both axes starting at zero. Points are labeled by reasoning effort. Up and to the left is the good corner. Bedrock streams faster at every effort, while the latency medians stay close at medium and high and separate at xhigh. Scope of these numbers. One model (GPT-5.5), one Bedrock Region (us-east-2), one client location, sequential single-stream requests, short math prompts, measured in June 2026. Latency and error rates are point-in-time properties of a serving fleet, not constants. Rerun against your own region, workload shape, and concurrency before committing an SLO to these. Production service pattern That was the measurement half of this post. The benchmark validated the model path, with the same answer quality, faster serving, and zero failures on Bedrock, so from here on we switch from measuring to building: everything below is about the two copilots we shipped on that path. What gets easier with OpenAI on Bedrock In the examples below, the announcement matters because teams can pair OpenAI’s strongest reasoning and agentic models with the AWS controls that already govern regulated workloads: Build pressure Why OpenAI on Bedrock helps Hard reasoning over messy evidence GPT-5.5 and GPT-5.4 are available for complex professional and agentic work, so the same review workflow can use stronger models without leaving AWS. Security and platform review Inference stays in the selected Bedrock Region and runs under AWS controls like IAM, PrivateLink/VPC isolation, KMS encryption, and CloudTrail logging. Procurement and scale-up Usage can count through existing AWS commitments, which removes a common blocker between prototype approval and production rollout. Engineering velocity The OpenAI-compatible Responses API lets teams adapt existing OpenAI patterns while keeping deployment, auth, observability, and data access on AWS. One governed pattern, two copilots The healthcare and financial-services demos share something more useful than a shared implementation: a governed service pattern. Each one starts with authenticated access, retrieves only scoped evidence, maps that evidence to policy, labels gaps and stale records, emits observable traces and artifacts, applies guardrails around scope, and leaves the final decision with a qualified human. This is the useful kind of reuse. The healthcare and financial-services examples read different sources and produce different review artifacts because the work is different. What stays the same is the operating contract: cite the evidence, expose gaps, preserve auditability, keep the run observable, and refuse the final call. OpenAI on Bedrock matters here because the model can change without moving the workflow out of the governed AWS environment. For GPT-5.5, GPT-5.4, and Codex, AWS points developers to the OpenAI-compatible Responses API on Bedrock Mantle. The adapter changes; the domain services, source IDs, auth boundary, audit trail, and human-review output contract should stay intact. That also makes model migration more practical. Teams already running Bedrock workloads on Anthropic, Amazon Nova, or other supported model families can add OpenAI where it fits without rebuilding the surrounding product. The work is still an engineering migration, not a string replacement: model IDs, invocation adapters, streaming behavior, tool contracts, observability hooks, and regression checks all need attention. But the business workflow, AWS security posture, and production service boundary can remain recognizable. Financial services: the FSI Evidence Copilot We lead with financial services because the cost of a wrong call is unambiguous. Lending, KYC, and AML review are evidence-assembly problems wearing a decision’s clothing: an analyst has to find the policy, locate every qualifying fact across statements and alerts, decide what is missing, and document the chain before any human judgment is even possible. The FSI Evidence Copilot does the assembly and, critically, never approves credit, files a SAR, closes an alert, or freezes funds. Question Answer What is manual today? An analyst hunts across bank statements, case notes, policies, and alerts before the real review can begin. What does the copilot do? It assembles a requirement-by-requirement evidence packet with source IDs, missing items, and stale documents called out. Where does the human stay in control? The analyst still approves, denies, escalates, files, or closes. The agent only prepares the packet. What changes operationally? Less prep time, fewer uncited claims, and a clearer audit trail for every exception. Tool What it does fsi_list_cases / fsi_get_case_brief Enumerate synthetic cases and pull case facts with source IDs. fsi_map_policy_evidence Map each policy requirement to evidence, with explicit gap and staleness flags. fsi_create_chart_artifact Generate cash-flow / risk chart artifacts for the packet. fsi_draft_review_packet Assemble the draft, human-review-only packet. Walkthrough: small-business credit renewal (Atlas Industrial Supplies) Atlas, a regional industrial-parts distributor, asks to raise its credit line from $450K to $700K. The copilot opens the case, maps the Small Business Credit Policy 2026, and immediately sorts the file into supported evidence and open gaps: FSI Evidence Copilot · SBL-2026-0417-ATLAS: evidence checklist (excerpt) Requirement Status Evidence DSCR ≥ 1.25× for increases above $500K unclear Trailing six-month DSCR averages 1.19×; only Nov & Feb clear 1.25× DOC-ATLAS-BANK-APR Ownership attestation < 365 days not found Attestation on file is 412 days old CASE-ATLAS-APP Most recent 90 days of statements found Feb–Apr 2026 indexed; April 20 days old DOC-ATLAS-BANK-APR AR aging reviewed for distributors not found No AR aging document in the case index The first graph earns its keep by putting the underwriting exception in one glance. The policy says credit increases above $500K need DSCR at or above 1.25×. Atlas is below that floor in four of the last six months, with a January trough at 1.11× and an April reading of 1.08×. Instead of producing an automated denial, the copilot gives the analyst the evidence behind a request that cannot be rubber-stamped. Atlas monthly DSCR vs. the 1.25× policy threshold (dashed). Source: DOC-ATLAS-BANK-APR. The second graph needs more context, because wire counts alone cannot prove suspicious activity. We include it because it shows the same review pattern in a different financial-services workflow: the agent spots a jump, attaches it to the source alert, and explains why a human should look. Atlas jumps to 17 outgoing wires in April against a five-month average of seven. Northstar, an AML case, spikes to 19 against an expected five. The copilot routes the anomaly into the review packet for a human to evaluate. Monthly outgoing wire count. The chart gives reviewers a triage cue: the copilot surfaces the spike, cites the source alert, and routes the anomaly to a human reviewer. When asked to just approve the increase, the copilot refuses the decision and offers the next analyst action instead: Out of bounds: declined “I can’t approve or deny this credit increase. That’s a human underwriting decision. The DSCR exception (1.18× vs. 1.25×) and the 412-day-old ownership attestation both require review before any recommendation.” In bounds: delivered Draft packet with executive snapshot, requirement-to-evidence map, three ranked risk indicators, and recommended next actions: request AR aging and a refreshed attestation, explain the April wire spike, route the DSCR exception to underwriting. Video The FSI Evidence Copilot launch walkthrough: case brief → checklist → cash-flow chart → draft packet, with the decision boundary held throughout. Healthcare: the Clinical Evidence Copilot Swap the industry, keep the pattern. Utilization review and prior authorization are the same evidence-assembly problem with different policies: find the relevant policy, locate every qualifying fact in a messy chart, and decide what is missing, all while keeping the same hard boundary around the judgment. The Clinical Evidence Copilot does the assembly; a clinician makes the call. Question Answer What is manual today? A reviewer reads chart notes, labs, medication history, and coverage policy to determine whether the file is ready for review. What does the copilot do? It maps each policy criterion to chart evidence, labels stale or missing documentation, and exports a draft packet. Where does the human stay in control? A clinician still decides coverage, medical necessity, or next clinical action. The agent never declares eligibility. What changes operationally? Faster chart prep, clearer missing-document requests, and a review record that can be defended. It works one synthetic patient at a time, and for every claim it cites a source ID returned by its tools: Tool What it does clinical_evidence_workspace Patient brief, timeline, criteria mapping, and missing-documentation review. list/read/save_clinical_policy Inspect Markdown coverage policies, or draft one (flagged for human review). save_clinical_evidence_packet Export a draft evidence packet as a downloadable artifact. Demo 1: Home oxygen therapy (CEC-1003) A 71-year-old synthetic patient requests a home oxygen concentrator. There is no policy on file, so the copilot drafts one (marked DRAFT, REQUIRES HUMAN REVIEW), then maps 17 criteria to the chart: 11 supported, 4 needing review, 2 missing. It surfaces the clinically decisive fact: a six-minute walk test where SpO₂ fell to 86% on room air and recovered to 93% on 2 L/min. It also clearly flags the gaps a reviewer must close, like the absent ICD-10 code. Demo 2: GLP-1 diabetes medication review (CEC-1001) A 56-year-old synthetic patient is up for a GLP-1 (semaglutide) review. The copilot pulls the chart timeline, maps the policy checklist, and lands on the kind of subtle, easy-to-miss finding that makes or breaks a review: Clinical Evidence Copilot · CEC-1001: policy-derived checklist (excerpt) Criterion Status Evidence Adult member found Age 56 Diagnosis found T2DM documented since 2021-08-14 Glycemic evidence needs human review A1c 8.1% is 131 days old; policy requires ≤ 90 days Prior therapy found Metformin ER trial, intolerance documented Safety screening needs human review Pregnancy status and MTC/MEN-2 screening not documented Draft packet status: ready for human review, with caveats: glycemic evidence is stale (131 vs 90 days) and safety documentation is incomplete. The copilot routes the exception to a human without declaring the patient approved or eligible. Video The Clinical Evidence Copilot preparing the GLP-1 review (CEC-1001) end to end. The final chart gives reviewers a readiness view. Green means the file has evidence for that criterion. Amber means the criterion may be supportable but needs human review, for example, stale A1c or incomplete safety screening. Red means the record is missing something the reviewer should request before spending time on a final determination. Criteria status by review. The useful signal includes what is supported, stale, ambiguous, or missing before the clinician opens the chart. The shared pattern: evidence over decisions These two copilots feel like the same product because of the operating contract baked into the product behavior and enforced by guardrails. In regulated work, this contract is the difference between a tool people are allowed to use and a demo that never ships: Cite everything. Every material claim references a source ID (a chart note, a bank statement, an alert) or a policy section. No uncited assertions. Name the gaps as loudly as the matches. Each criterion gets exactly one status: found, not found, unclear, or needs human review. Stale and missing evidence are first-class outputs. Refuse the final call. No “approved,” “denied,” “eligible,” or “file the SAR.” The copilot drafts; a licensed human decides. Stay in scope. One patient or one case at a time, synthetic data only, no invented facts. Why the boundary helps. The temptation with a capable model is to let it decide. In healthcare and financial services, that judgment belongs with a qualified human. By designing the agent to be excellent at assembly and deliberately incapable of determination, the human reviewer gets leverage without inheriting a black-box decision they can’t defend. From migration to production The reason we can present two copilots instead of one is that the architecture is service-oriented and repeatable without exposing business logic as product glue. A production agent service needs clear separation between the model path, domain services, policy assets, authentication, session controls, observability, guardrails, evaluation, and deployment. In practical terms, that means teams can migrate or extend OpenAI workloads by changing the model adapter and deployment posture while preserving the surrounding service: identity, audit trails, scoped retrieval, token streaming, artifact generation, monitoring, and human-review controls. Bedrock becomes the governed model path, while the product experience and domain services remain stable. Because the model path lives behind Bedrock, choosing OpenAI for the next engagement becomes a platform decision the team can make per workload: openai.gpt-5.5 for the hardest reasoning, openai.gpt-5.4 for price-performance-sensitive professional work, or an open-weight openai.gpt-oss-120b / openai.gpt-oss-20b model when throughput and cost dominate. The product architecture isolates the adapter from the review workflow, so adapters can change without disturbing the operating model. This is the same muscle behind 500+ GenAI and agentic launches since 2023, more than half of which are moving to or already running in production. The launch of OpenAI on Bedrock keeps that playbook intact and adds a powerful new option to the one slot in it that was always meant to be swappable. Conclusion OpenAI models on Amazon Bedrock give enterprises a path to build secure, scalable GenAI inside the AWS ecosystem they already trust. The two copilots here make the case in practical terms: one architecture pattern, one human-in-the-loop discipline, two regulated industries, and a model/provider boundary narrow enough to change without rebuilding the product. If you’re trying to move from AI experimentation to production at scale, this is the conversation we want to have. Let’s talk about what an evidence-first copilot looks like for your team, built with OpenAI on Amazon Bedrock by a launch partner who has taken hundreds of GenAI and agentic systems from idea to launch. Catch the announcement → OpenAI models and Codex on Amazon Bedrock are now generally available. Want to build with OpenAI on Amazon Bedrock? Let’s connect. Citation If you find this work useful, please cite: @misc{loka2026frontiermodels, title = {How Loka Evaluates and Builds with Frontier Models on AWS}, author = {Kalinovski, Petar and Jakimovski, Bojan}, year = {2026}, month = {jun}, howpublished = {Blog post}, url = {https://techblog.loka.com/openai-bedrock/} } Further reading AWS (2026). OpenAI models and Codex on Amazon Bedrock are now generally available. AWS Machine Learning Blog. aws.amazon.com AWS (2026). APIs supported by Amazon Bedrock. API support, endpoints, and model invocation reference. docs.aws.amazon.com AWS (2026). Get started with OpenAI GPT-5.5, GPT-5.4 models, and Codex on Amazon Bedrock. AWS News Blog. aws.amazon.com AWS (2026). Inference using Responses API. Amazon Bedrock User Guide. docs.aws.amazon.com AWS (2026). GPT-5.5 model card. Programmatic access details for the GPT-5.5 Bedrock Mantle endpoint. docs.aws.amazon.com OpenAI (2026). OpenAI frontier models and Codex are now available on AWS. openai.com OpenAI (2026). API pricing. Model token pricing, Batch pricing, and reasoning-token billing notes. platform.openai.com Datacurve (2026). DeepSWE. Long-horizon software engineering benchmark and leaderboard. deepswe.datacurve.ai Artificial Analysis (2026). GPT-5.5: API provider comparison. Independent cross-provider measurements of output speed, latency, and price, at xhigh and medium reasoning effort. Amazon (2026). OpenAI and Amazon announce strategic partnership. The $50B investment and the ~2 GW Trainium capacity commitment. aboutamazon.com Amazon (2026). AWS and Cerebras collaboration aims to set a new standard for AI inference speed and performance in the cloud. Disaggregated inference: Trainium prefill, Cerebras wafer-scale decode. press.aboutamazon.com The New Stack (2026). AWS lands OpenAI on Bedrock, but Trainium is the real story. Analysis of the silicon strategy behind the Bedrock launch. thenewstack.io OpenAI (2026). Codex for every role, tool, and workflow. Codex usage and adoption update. openai.com"},{"href":"/carbon-trainium2/","title":"Running Hugging Face Carbon on AWS Trainium2","subtitle":"A first NxD Inference benchmark for open DNA foundation models","description":"A practical benchmark showing Hugging Face Bio Carbon running on AWS Trainium2 with NxD Inference, covering what worked, what we measured, and why it matters for bio and HCLS teams moving open models into production.","abstract":"Carbon-500M, Carbon-3B, and Carbon-8B compiled and ran through NxD Inference on one trn2.3xlarge; the benchmark reports fixed-shape throughput, DNA-suite output, and a separately qualified A100 reference comparison.","tags":["Carbon","AWS Trainium","NxD Inference","Genomics"],"topics":["trainium","biomedical-ai","benchmarks","inference"],"authors":["Bojan Jakimovski","Loka Applied Research"],"text":"Introduction The Human Genome Project, completed in 2003, cost around $3 billion over 13 years to sequence the first human genome. Today, the sequencing bill is measured in hundreds of dollars. That changes the problem. For many bio and HCLS teams, the hard part is no longer getting enough sequence data. The hard part is turning that data into something useful: variant effect prediction, regulatory annotation, gene expression modeling, therapeutic sequence design, and repeated scoring runs that need to happen inside a secure cloud environment. This is where DNA foundation models become interesting. The idea is simple enough: DNA is a sequence, and modern foundation models are extremely good at learning from sequences. Models such as HyenaDNA, the Nucleotide Transformer, and Evo2 showed that models trained on raw genomic sequence can learn useful biological representations without hand-built feature pipelines. But many of these releases also came with a practical catch: unusual architectures, closed or constrained access, large GPU requirements, or tokenization choices that make long-context inference expensive. Carbon, released by Hugging Face Bio, is a very good step in the other direction. It is open, Apache 2.0, available in 500M, 3B, and 8B sizes, and trained on roughly six trillion base pairs of eukaryotic genomic DNA, mRNA transcripts, and bacterial genomes. It uses a 6-mer tokenizer, so six DNA bases become one model token, while Factorized Nucleotide Supervision keeps the training objective aware of base-level prediction. Carbon-3B is reported to match Evo2-7B on key DNA benchmarks while being smaller and much faster. For infrastructure teams, the biggest gift is even more practical: Carbon is built on a familiar Llama 3-style Transformer backbone. That matters because a model card is not a production deployment. Bio teams usually want the model running inside an AWS VPC, close to their data, with security and procurement teams comfortable with the path. They also need hardware they can actually reserve. The A100-80GB reference used in the Carbon report is a strong baseline, but on AWS that capacity is commonly exposed through larger nodes such as p4de.24xlarge. For a team that wants to test one genomics model, that can mean reserving an 8-GPU node when the first workload does not need eight GPUs. So when Carbon shipped, we tried the thing customers actually ask us about at Loka: can we take this fresh Hugging Face checkpoint and make it run on AWS-native accelerator infrastructure without turning the first experiment into a custom kernel project? The answer was yes. On launch day, we ran Carbon-500M, Carbon-3B, and Carbon-8B on a single trn2.3xlarge using NxD Inference: one Trainium2 accelerator, 96 GB of accelerator memory, and a public Capacity Blocks rate of about $2.23/hr, checked on May 21, 2026. No model rewrite. No model-specific kernels. A small tokenizer/config compatibility patch was enough for Carbon to ride the existing NxDI Llama causal path. In the batch-16 sweep shaped after the Carbon technical report’s A100 reference, Carbon-500M reached 18.83 kbp/s, Carbon-3B reached 11.00 kbp/s, and Carbon-8B reached 8.21 kbp/s. This is not a final service benchmark and it is not a biological evaluation. It is something more basic, and honestly more useful for executives: proof that the distance between an open model release and a production-shaped AWS serving artifact is getting shorter. What makes Carbon different Why this section matters: Carbon is not “just another LLM for DNA.” It is open, it uses a familiar Llama-style backbone, and it adds the DNA-specific pieces where they actually matter: tokenization and training. That combination is what made a fast Trainium2 path possible. The architecture is intentionally familiar: decoder-only autoregressive modeling, RMSNorm, SwiGLU, RoPE, GQA, and a Llama-style causal path. That is not the most exotic design choice, and that is the point. In enterprise AI, boring architecture is often a feature. It means the model has a better chance of working with the compilers, runtimes, profiling tools, and deployment patterns that customers already trust. The DNA-specific part is the tokenizer. Carbon uses non-overlapping 6-mer tokenization, so six nucleotides become one model token. A 1080 base-pair input becomes roughly 180 DNA tokens in DNA mode. That compression is what makes long genomic spans more practical on a standard Transformer backbone. Instead of paying attention cost on every single base, the model can work over a shorter token sequence while still learning from nucleotide-level supervision during training. The tradeoff is also worth being honest about. Single-base tokenization gives a cleaner interface, but it makes every sequence six times longer. Carbon takes the more deployment-friendly route: compact 6-mer tokens, plus Factorized Nucleotide Supervision to keep the model aware of base-level prediction. For this Trainium2 benchmark, we measured direct 6-mer generation. FNS base-pair-level inference is the next obvious follow-up because it would make the biological interface even cleaner. This is the part we like the most about the release from Hugging Face Bio: Carbon is not only a benchmark result. It is a model family that infrastructure teams can actually touch. The weights are open, the model cards are public, the sizes are practical, and the architecture gives cloud teams a real shot at making it production-shaped without starting from a blank page. The table below summarizes the three Carbon sizes we tested. The main deployment-relevant difference is not only parameter count, but also the attention shape: hidden size, layer count, attention heads, and KV heads all affect how cleanly the model maps onto tensor parallel inference. Model Hidden Layers Attention heads KV heads Vocabulary Carbon-500M 1024 28 16 8 155,776 Carbon-3B 3072 30 32 4 155,776 Carbon-8B 4096 32 32 8 155,776 Why Trainium2 Bio workloads are not chat workloads with a lab label on top. They often involve private sequence data, long context, repeated scoring, likelihood comparisons, perturbation sweeps, and compliance constraints. Cost matters, but so do data locality, procurement shape, security review, and the ability to keep the model in the same AWS environment where the rest of the platform already runs. This is where AWS Trainium2 deserves real praise. It gives teams an AWS-native accelerator option that is purpose-built for deep learning, starts at a practical one-chip instance size, and scales to larger Trn2 fleets when the workload is proven. For customers already building on AWS, that is not a small detail. It means the accelerator strategy can fit the cloud strategy instead of forcing a separate GPU-only operating model from day one. Why Trainium2 matters here: the value is not only lower cost. The value is having an AWS-native accelerator path that starts small, stays inside the customer environment, and can scale when the workload is real. Carbon was a good test case because it is not a generic chat model, but it is shaped like one. Its configs advertise LlamaForCausalLM. NxD Inference already has a strong Llama causal path. The bet was simple: if the tokenizer and model config cooperate, Carbon should be able to use the existing NxDI path. At Loka, this is the question we hear whenever a serious open model ships: not only “is the model good?”, but “how fast can we stand it up on infrastructure we already operate, at a cost we can explain to procurement?” Carbon gave us a clean way to answer that question on real Trainium2 hardware. The timing also fits the broader AWS BioFM story. In April 2026, AWS published a multimodal biological foundation-model overview that describes BioFM adoption as a combination of model development, governed biological data, scalable infrastructure, and implementation support. Importantly for us, AWS also names Loka alongside Deloitte and Accenture as implementation partners for organizations moving multimodal BioFM work from proof-of-concept to production. Carbon on Trainium2 is a very concrete example of that motion: an open Hugging Face Bio model, running on AWS accelerator infrastructure, with cost, throughput, and deployment details that enterprise teams can actually evaluate. Benchmark setup We ran the benchmark on a single trn2.3xlarge. The instance exposes one Trainium2 device, four logical NeuronCores, and 96 GB of accelerator memory. The run used tensor parallel degree 4, BF16 weights, batch size 1, on-device sampling, and NxDI bucketing. The main benchmark shape mirrors the Carbon report’s Figure 1 framing: 1080 base pairs for prefill and 1080 base pairs for decode. With 6-mer DNA tokenization, that is about 180 input tokens and 180 generated tokens. We compiled a 512-token artifact with a 256-token context bucket and a 180-token decode budget. The setup table below captures the exact runtime, parallelism, and prompt shape used for the fixed-shape run. Component Setting Instance trn2.3xlarge Accelerator 1 Trainium2 device, 4 logical NeuronCores, LNC=2 Runtime PyTorch 2.9.1, torch-neuronx 2.9.0, torch-xla 2.9.0, Neuron SDK 2.29 stack NxDI neuronx-distributed-inference==0.9.0 Parallelism tp_degree=4, batch_size=1 Shape max_context_length=256, seq_len=512, max_new_tokens=180 Prompt 1080 bp sequence wrapped as <dna>...</dna> for the fixed-shape run Results and analysis The headline result is compatibility. All three Carbon checkpoints compiled and ran through NxDI with tokenizer handling plus a small compatibility/config patch. That is exactly what you want from a standard architecture: a domain model from Hugging Face Bio, running through a general AWS inference stack, without waiting for a bespoke serving path. Fixed-shape NxDI throughput We first measured compiled NxDI artifacts with the fixed report-shaped configuration. These numbers separate context encoding, token generation, and end-to-end behavior under one static shape, so they are useful for infrastructure comparison and future optimization work. The fixed-shape results table below reports compile/load time, context encode, token generation, and end-to-end latency for each model size. Model Compile + trace Load CTE p50 TKG p50 TKG throughput E2E p50 E2E throughput Carbon-500M 69.73 s 7.74 s 5.49 ms 3.35 ms 297.0 tok/s 693.76 ms 737.5 tok/s Carbon-3B 96.54 s 9.27 s 13.14 ms 6.68 ms 150.2 tok/s 1299.10 ms 394.4 tok/s Carbon-8B 144.33 s 10.25 s 18.90 ms 8.32 ms 120.4 tok/s 1604.55 ms 319.2 tok/s Figure 1. Fixed-shape NxDI throughput on trn2.3xlarge. Token generation throughput is the most relevant number for autoregressive decode; end-to-end throughput reflects the compiled benchmark harness shape. The scaling pattern is healthy. Carbon-500M is fast, Carbon-3B is comfortable on a single small Trainium2 instance, and Carbon-8B fits and runs with useful latency before any model-specific optimization work. For a first-pass enterprise test, that is the important part: the serving path works and the numbers are usable. DNA prompt suite A fixed-shape benchmark is useful, but it does not tell the whole story. We also ran a seven-prompt DNA suite using 1080 bp prompts: balanced DNA, CpG-rich, AT-rich, GC-rich, ORF-like, TATA-box-like, and CAG triplet-repeat. Each model ran one warmup and two measured runs per case, for 14 measured generations per model. The DNA-suite table below reports the median latency and throughput, plus a simple valid-DNA check on decoded A/C/G/T output. Model Median elapsed Median token throughput Median bp throughput Avg valid DNA Carbon-500M 0.689 s 261.3 tok/s 1568 bp/s 100.0% Carbon-3B 1.277 s 140.9 tok/s 846 bp/s 100.0% Carbon-8B 1.589 s 113.3 tok/s 679 bp/s 99.0% Figure 2. Median base-pair throughput for 1080 bp decode across seven DNA prompt regimes. Base-pair throughput is computed from decoded A/C/G/T characters, not assumed from token count. Carbon-500M and Carbon-3B generated 1080 valid base pairs in every prompt case. Carbon-8B did the same for six out of seven cases. On the CAG triplet-repeat stress case, 180 generated tokens decoded to 963 A/C/G/T characters because part of the output moved outside pure DNA vocabulary. That is not a Trainium issue, but it is a useful measurement caveat: base-pair throughput is cleanest when generation stays in DNA mode. Comparison with the A100 baseline Hugging Face Bio reports an A100 reference point in the Carbon technical report. The appendix measures Carbon-3B and Carbon-8B on a single A100-80GB with vLLM dynamic batching, n=16 prompts, and a 1 kbp output. We reran our Trainium2 benchmark with the same high-level workload shape: n=16, 1020 bp prompts, 1020 bp generated DNA per prompt, direct 6-mer generation, and greedy decoding. The comparison table below puts the published A100 reference beside our Trainium2 batch-16 run. This is not a perfect accelerator shootout. The A100 baseline uses vLLM dynamic batching. Our Trainium2 run uses a static compiled NxDI batch on one trn2.3xlarge. The useful reading is operational: how much of the published GPU throughput can a small AWS-native Trainium2 instance recover immediately after a model release? Model HF A100-80GB direct 6-mer HF A100-80GB FNS bp-level Our Trainium2 direct 6-mer Trainium / A100 direct Harness note Carbon-3B 18.9 kbp/s 12.3 kbp/s 11.00 kbp/s 58.2% A100: vLLM dynamic batch 16; Trainium2: NxDI static batch 16 Carbon-8B 12.0 kbp/s 12.3 kbp/s 8.21 kbp/s 68.4% A100: vLLM dynamic batch 16; Trainium2: NxDI static batch 16 Figure 3. Published Carbon A100-80GB throughput from the technical report compared with our Trainium2 batch-16 measurements. This is a reference comparison, not a controlled accelerator shootout. Fair reading: A100 plus vLLM is a strong optimized baseline. Trainium2 plus NxDI is the day-one AWS portability result. The important part is that Carbon-3B and Carbon-8B reached useful throughput on a single trn2.3xlarge, without turning the first experiment into a larger GPU deployment. Cost-normalized throughput Throughput only becomes useful for a business when it meets the buying motion. This is where the Trainium2 shape is important. As checked on May 21, 2026, AWS lists trn2.3xlarge Capacity Blocks at $2.235 per instance-hour for one Trainium2 accelerator. The larger trn2.48xlarge keeps the same listed per-accelerator rate at $35.7608/hr for 16 Trainium2 accelerators. That is a clean path for a team: start with one 96 GB accelerator, prove the model, then scale the same Neuron/NxDI stack when the workload is real. The A100 reference in the Carbon report is a single A100-80GB. On AWS, that class of capacity is commonly bought as a larger node such as p4de.24xlarge. The same May 21, 2026 Capacity Blocks pricing lists that node at $14.7663/hr for eight A100 accelerators. Normalizing that by eight GPUs is useful when a company already has a mature GPU fleet and can keep the whole node busy. It is less useful for a first genomics service, where the practical question is usually simpler: “What is the smallest serious accelerator unit we can reserve and defend?” Smallest serious start$2.235/hr Full A100 node floor$14.77/hr Carbon-3B first-service view$56 vs $217/Gbp Carbon-8B first-service view$76 vs $342/Gbp For this dollar-per-gigabase comparison, we only include Carbon-3B and Carbon-8B. Hugging Face Bio publishes the A100 reference points for those two models in the report table we used, but not for Carbon-500M. Carbon-500M is still a very useful Trainium2 result, especially for high-volume scanning and quick experiments, but adding it to the A100 comparison would make the chart look more complete than the evidence actually is. The cost table below uses the public Capacity Blocks rates above and should be read as a planning view, not a universal price/performance ranking. Model Measured bp/s on Trainium2 Base pairs / hour 30-day base pairs Trainium2 cost / Gbp A100 full-node floor / Gbp A100 full-utilization normalized / Gbp Mbp / dollar on Trainium2 Carbon-3B 10,998 39.59M 28.51B $56 $217 $27 17.7 Carbon-8B 8,212 29.56M 21.29B $76 $342 $43 13.2 Figure 4. Cost-normalized DNA generation throughput for Carbon-3B and Carbon-8B. Trainium2 uses AWS's published trn2.3xlarge Capacity Blocks rate of $2.235/hour, checked on May 21, 2026. The A100 full-node floor assumes a p4de.24xlarge reservation is used for one Carbon workload. The normalized A100 line divides that node by eight GPUs and assumes perfect utilization across all accelerators. Carbon-500M is intentionally excluded because the Carbon report table used here does not publish the matching A100 reference point for that model. The commercial reading is not “Trainium2 beats A100 in every possible view.” That would be the wrong claim. If a company already owns or reserves an A100 fleet and can keep every GPU saturated, the normalized GPU economics are strong. The same caveat applies beyond this AWS comparison: H100, H200, and GB200 capacity from AWS or specialized GPU clouds can be very competitive when the workload, discounts, availability, and utilization line up. We did not benchmark those options here. The Trainium2 win in this post is the starting shape: a one-chip AWS accelerator with 96 GB of memory, a direct path to a 16-chip Trn2 fleet, and a Neuron/NxDI stack that ran Carbon on day one. For CTOs and platform buyers, that is the difference between a model that is interesting in a report and a model that can be tested inside the real AWS environment quickly. What the numbers say: Carbon runs, the output is mostly clean DNA, and the throughput is already useful for early production planning. These are not final service economics, but they are enough to justify the next step: testing Carbon inside the customer’s own AWS environment. One more engineering note: Carbon-3B is the cleanest fit under TP=4 because its 4 KV heads align exactly to the tensor-parallel degree. Carbon-500M and Carbon-8B trigger a GQA-to-MHA sharding fallback, but both compile and produce correct output. Across all three sizes, the plain BF16 NxDI configuration was the best measured setup. No custom kernels were needed for this first pass. That leaves obvious headroom. These numbers are the baseline we got from the standard NxDI path, not the ceiling for Trainium2. The next optimization pass is where Neuron-specific work starts to matter: tighter bucketing, better serving shapes, and potentially NKI kernels for hot paths such as attention, projections, RoPE, or normalization. In other words, the current result already makes Trainium2 credible for Carbon, and the AWS stack still gives us engineering room to push the throughput and latency further. Why this matters for bio and HCLS For bio and HCLS leaders, this is not really a story about a model demo. It is a story about reducing the distance between scientific AI and a deployment path that a real enterprise can approve. A fresh open genomic model moved onto AWS-native accelerator infrastructure in a day, with numbers, caveats, and a buying shape that CTOs, platform leaders, security teams, and commercial buyers can reason about. Hugging Face deserves credit for making Carbon a practical open release, not just a research announcement. Open weights, public model cards, and an inspectable path give customers more control over fine-tuning, continued pretraining, auditing, and deployment. In biology, that matters because sensitive sequence workflows cannot always be sent to a black-box endpoint. AWS deserves credit for giving those teams a serious deployment lane. Trainium2 provides the accelerator. Neuron and NxD Inference provide the software layer. The AWS environment provides the security boundary, networking, IAM, procurement, and operational controls that enterprise teams already know how to use. Together, that makes open bio models much easier to move from slideware to a production-shaped proof. Put Hugging Face Bio, Carbon, AWS Trainium2, and NxD Inference together, and the question changes. It is no longer “can we even run this model?” It becomes “which latency, throughput, and cost point do we want for sequence generation, variant scoring, or perturbation sweeps?” That is a much better conversation for a CTO or CEO, because it turns the model from an interesting artifact into an infrastructure decision. Where Loka fits: this is the bridge we care about: take a strong open model, make it run on AWS infrastructure, measure it honestly, and turn it into something a customer can evaluate with security, cost, and procurement in the room. Conclusion The core result is simple: Carbon runs on Trainium2 through NxD Inference today. Not after a model rewrite. Not after model-specific kernels. Today, with tokenizer handling, a small compatibility patch, and the existing Llama causal path. That is good for Hugging Face because it shows the value of releasing open biology models in a form that infrastructure teams can actually adopt. It is good for AWS because it shows Trainium2 and NxDI can carry a fresh, domain-specific model without waiting for a long porting cycle. And it is good for bio and HCLS teams because it lowers the cost and friction of the first real deployment conversation. The numbers are already useful: Carbon-500M reaches 1,568 bp/s, Carbon-3B reaches 846 bp/s, and Carbon-8B reaches 679 bp/s in the batch-1 prompt suite. In the A100-style batch-16 sweep, the same instance reaches 18.83 kbp/s, 11.00 kbp/s, and 8.21 kbp/s respectively at $2.235/hr. The caveats are real, and this is still before the deeper Trainium2 optimization work: improved serving shapes, tighter NxDI tuning, and NKI kernels can all move these numbers in the right direction. But the bigger takeaway is clear: the bottleneck for genomic AI is increasingly the gap between an open model release and a production-grade serving artifact. With Carbon, Trainium2, and NxD Inference, that gap got shorter. If you are building with open bio models and need them running in production on AWS, reach out to Loka. This is exactly the problem we work on. Want the code-side walkthrough? We also prepared a companion engineering post that goes deeper on the tokenizer handling, NxD Inference compile path, benchmark harness, and optimization variants. Read it on the Loka Blog, or inspect the benchmark package in the public GitHub repository. A small thank-you: sincere thanks to Petar Kalinovski, Henrique Ribeiro Delgado da Silva, Tiago Gonçalves, João Correia, Telmo Felgueira, Pedro Dias, and Zafir Stojanovski for taking the time to review, sanity-check, and sharpen this work before it went out. Citation If you find this work useful, please cite: @misc{loka_carbon_trainium2_2026, title = {Running Hugging Face Carbon on AWS Trainium2 with NxD Inference}, author = {Jakimovski, Bojan and {Loka Applied Research}}, year = {2026}, month = {may}, howpublished = {Blog post}, url = {https://techblog.loka.com/carbon-trainium2/} } Further reading Hugging Face Bio (2026). Carbon: Open DNA Foundation Models. Technical report covering the 6-mer tokenization design, Factorized Nucleotide Supervision, pretraining setup, and benchmark comparisons for all three model sizes. github.com/huggingface/carbon Hugging Face Bio (2026). Carbon interactive demo and technical narrative. Public Carbon release page covering open weights, open code, the 6-mer tokenizer, long-context extension, throughput framing, and the live DNA generation demo. huggingface.co/spaces/HuggingFaceBio/carbon-demo Hugging Face Bio (2026). Carbon-500M, Carbon-3B, and Carbon-8B model cards. Open-weight checkpoints and tokenizer code on Hugging Face Hub. huggingface.co/HuggingFaceBio/Carbon-500M · huggingface.co/HuggingFaceBio/Carbon-3B · huggingface.co/HuggingFaceBio/Carbon-8B AWS Neuron (2024). NxD Inference: NeuronX Distributed Inference. Open-source library for deploying large language models on AWS Trainium and Inferentia accelerators, including tensor-parallel and bucketed autoregressive serving via the NxDI Llama causal path. github.com/aws-neuron/neuronx-distributed-inference Kwon, W., Li, Z., Zhuang, S., Sheng, Y., Zheng, L., Yu, C. H., Gonzalez, J. E., Zhang, H., & Stoica, I. (2023). Efficient Memory Management for Large Language Model Serving with PagedAttention. Proceedings of the 29th Symposium on Operating Systems Principles (SOSP 2023). The inference engine used in the Carbon technical report's A100-80GB baseline measurements; the direct 6-mer and FNS throughput figures compared in this post were generated with vLLM dynamic batching. arxiv.org/abs/2309.06180 AWS (2024). AWS Neuron SDK documentation. Official documentation for compiling, profiling, and serving models on the Neuron runtime, covering both Trainium and Inferentia generations. awsdocs-neuron.readthedocs-hosted.com AWS (2024). AWS Trainium and Trainium2. Amazon EC2 accelerator chip family purpose-built for deep learning training and inference workloads at scale. aws.amazon.com/ai/machine-learning/trainium AWS (2026). Applying multimodal biological foundation models across therapeutics and patient care. AWS overview of BioFM use cases, AWS infrastructure layers, and implementation partners for moving BioFM proof-of-concepts toward production. aws.amazon.com/blogs/machine-learning AWS (2026). Amazon EC2 Capacity Blocks for ML pricing. Published per-instance pricing for reserved ML capacity. Rates used in this analysis were checked on May 21, 2026: trn2.3xlarge at $2.235/hr in ap-southeast-2 (Melbourne), trn2.48xlarge at $35.7608/hr in us-east-2 (Ohio), and p4de.24xlarge at $14.7663/hr in US East/US West regions where listed. aws.amazon.com/ec2/capacityblocks/pricing AWS Neuron (2026). NKI samples and NKI library kernels. Public examples and references for optimized Neuron kernels, including attention, projection, RoPE, and normalization paths relevant to future Carbon optimization work. github.com/aws-neuron/nki-samples Zhang, B., & Sennrich, R. (2019). Root Mean Square Layer Normalization. NeurIPS 2019. Introduces RMSNorm as a computationally efficient alternative to standard layer normalization; used in Carbon's Transformer backbone. arxiv.org/abs/1910.07467 Shazeer, N. (2020). GLU Variants Improve Transformer. Foundational work on Gated Linear Unit variants including SwiGLU, the activation function used in Carbon's feed-forward layers. arxiv.org/abs/2002.05202 Su, J., Lu, Y., Pan, S., Murtadha, A., Wen, B., & Liu, Y. (2021). RoFormer: Enhanced Transformer with Rotary Position Embedding. Introduces RoPE (Rotary Position Embedding), the positional encoding scheme used in Carbon's attention layers. arxiv.org/abs/2104.09864 Grattafiori, A., Dubey, A., et al. (2024). The Llama 3 Herd of Models. Meta AI. Introduces the Llama 3 model family and the decoder-only Transformer architecture that Carbon adopts as its backbone, enabling compatibility with standard inference runtimes including NxD Inference. arxiv.org/abs/2407.21783 Ainslie, J., Lee-Thorp, J., de Jong, M., Zemlyanskiy, Y., Lebrón, F., & Sanghai, S. (2023). GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints. EMNLP 2023. Introduces Grouped-Query Attention, the attention variant used by Carbon and handled by NxDI's GQA sharding path. arxiv.org/abs/2305.13245 Nguyen, E., Poli, M., Faizi, M., Thomas, A., Birch-Sykes, C., Wornow, M., et al. (2023). HyenaDNA: Long-Range Genomic Sequence Modeling at Single Nucleotide Resolution. NeurIPS 2023. Long-context DNA modeling at single-nucleotide resolution; useful context for understanding the tokenization tradeoffs in Carbon's 6-mer design. arxiv.org/abs/2306.15794 Dalla-Torre, H., Gonzalez, L., Mendoza-Revilla, J., et al. (2025). The Nucleotide Transformer: Building and Evaluating Robust Foundation Models for Human Genomics. Nature Methods 22, 287-297 (2025). Transformer-based DNA foundation model from InstaDeep, Nvidia, and Technical University of Munich; part of the landscape of genomic sequence models that Carbon addresses with its efficiency-first 6-mer design. nature.com/articles/s41592-024-02523-z Arc Institute (2025). Evo 2: Genome-scale foundation model at single-nucleotide resolution. Long-context DNA foundation model; the primary throughput and capability baseline cited in the Carbon technical report. Carbon-3B matches Evo2-7B on variant effect prediction and long-context benchmarks while being 2.3× smaller and running more than 150× faster. arcinstitute.org/tools/evo National Human Genome Research Institute (NHGRI). The Cost of Sequencing a Human Genome. NHGRI fact sheet tracking the historical decline in human genome sequencing costs, from the ~$3 billion Human Genome Project to sub-$1,000 whole-genome sequencing; the original cost context cited in the introduction. genome.gov/about-genomics/fact-sheets/Sequencing-Human-Genome-cost"},{"href":"/running-hugging-faces-carbon-on-aws-trainium2-with-nxd-inference/","title":"Running Hugging Face’s Carbon on AWS Trainium2 with NxD Inference","description":"Hugging Face Bio’s Carbon release is interesting for two reasons at once. First, it is a biology model. Second, it is not an infrastructure outlier. Many genomic models come with custom architectures, specialized…","abstract":"Hugging Face Bio’s Carbon release is interesting for two reasons at once. First, it is a biology model. Second, it is not an infrastructure outlier. Many genomic models come with custom architectures, specialized…","tags":["AWS Trainium","Hugging Face","LLM Inference","AI","AWS"],"topics":[],"authors":["Bojan Jakimovski"],"text":"The Engineering Walkthrough Hugging Face Bio’s Carbon release is interesting for two reasons at once. First, it is a biology model. Second, it is not an infrastructure outlier. Many genomic models come with custom architectures, specialized operators, or runtime assumptions that make deployment harder to evaluate. Carbon is different: it is an open DNA foundation model family with 500M, 3B, and 8B checkpoints, Apache 2.0 weights, a Llama-style causal backbone, and a DNA-native 6-mer tokenizer. That made it a natural Trainium2 test, with one concrete question behind it Can a freshly released open genomic model run through NxD Inference, part of the AWS Neuron SDK, on a single Amazon Elastic Compute Cloud (Amazon EC2) Trn2 instance (`trn2.3xlarge`) without rewriting the model? The short answer is yes. We compiled and benchmarked all three Carbon checkpoints on one Amazon EC2 Trn2 instance (`trn2.3xlarge`): one AWS Trainium2 accelerator, four logical NeuronCores, 96 GB of accelerator memory, BF16 weights, and tensor parallel degree 4. This post is the code-side companion to the main benchmark writeup. The main article covers the business and platform story. This one covers the practical path: tokenizer handling, compile shape, benchmark harness, result interpretation, and what did not improve the baseline. For the full report, including the Trainium2 business case, A100 reference comparison, and cost-normalized throughput charts, read the main Loka writeup: Running Hugging Face Carbon on AWS Trainium2 with NxD Inference Why Carbon Was a Good Fit for NxD Inference Carbon is domain-specific, but its architecture is deliberately familiar. Under the hood, the configuration advertises a Llama causal model path. That matters because NxD Inference already has strong support for Llama-style autoregressive serving on AWS Trainium and AWS Inferentia. The unusual part is the tokenizer. Carbon uses non-overlapping 6-mer DNA tokens. Instead of treating every nucleotide as one token, it groups six bases into one model token. A 1080 bp DNA sequence becomes roughly 180 Carbon DNA tokens when the tokenizer is in DNA mode. That token efficiency is the reason the benchmark is operationally interesting. Shorter token sequences reduce attention cost, keep the runtime path close to a standard Transformer serving stack, and make a single Trainium2 accelerator a credible first deployment unit. Tested Platform The measured runs used: Category Configuration Instance trn2.3xlarge Accelerator 1 AWS Trainium2 device Accelerator memory 96 GB Neuron topology 4 logical NeuronCores, LNC=2 Tensor parallelism tp_degree=4 Dtype bfloat16 Runtime PyTorch 2.9, torch-neuronx 2.9, torch-xla 2.9, Neuron SDK 2.29 Serving stack NxD Inference 0.9.0 Models HuggingFaceBio/Carbon-500M, Carbon-3B, Carbon-8B The most important non-obvious setting is LNC=2, which exposes four logical NeuronCores from the single AWS Trainium2 device.. We used tp_degree=4 so the model shards across those logical cores. Bootstrap the Environment Start from an AWS Neuron Deep Learning AMI (DLAMI) or AWS Neuron Deep Learning Container (DLC) where the AWS Neuron driver and runtime are already configured. The repository helper script does three things: creates the Python environment, installs the AWS Neuron SDK 2.29 / PyTorch 2.9 stack, and installs a patched NxD Inference checkout. git clone <repository-url> cd carbon-neuronx-distributed-inference NXDI_REF=main ./scripts/bootstrap_nxdi.sh source .venv-carbon-sdk29/bin/activate The Carbon-specific NxD Inference patch is intentionally small. The important point is that Carbon does not require a model rewrite or model-specific kernels for the baseline path. The compatibility work is around configuration/tokenizer handling and keeping the model on NxDI’s existing Llama causal path. Download the Carbon Checkpoints Carbon uses Hugging Face custom tokenizer code, so make sure the checkpoints are downloaded with the repository files intact. huggingface-cli login ./scripts/download_carbon_models.sh \"$HOME/models/carbon\" To download a single checkpoint: MODELS=\"Carbon-500M\" ./scripts/download_carbon_models.sh \"$HOME/models/carbon\" The Tokenizer Detail That Matters This is the part most likely to poison the benchmark if missed. Carbon requires trusted custom tokenizer code. DNA prompts should also use Carbon’s DNA mode prefix: <dna>{sequence}. Without those two details, the model may still run, but you are not measuring the intended compact 6-mer DNA path. In Python: from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained( \"/home/ubuntu/models/carbon/Carbon-500M\", trust_remote_code=True, padding_side=\"right\", ) tokenizer.pad_token_id = 151643 inputs = tokenizer( [\"<dna>ACGTTGCAACGTTGCAACGTTGCA\"], return_tensors=\"pt\", padding=True, ) From the NxD Inference demo entrypoint, the same ideas show up as CLI flags and prompt formatting: inference_demo \\ -model-type llama \\ -task-type causal-lm \\ run \\ -model-path \"$HOME/models/carbon/Carbon-500M\" \\ -compiled-model-path \"$HOME/compiled/carbon/Carbon-500M-tp4-bs16-s512-c256-n170-bf16\" \\ -trust-remote-code \\ -pad-token-id 151643 \\ -prompt \"<dna>ACGTTGCAACGTTGCAACGTTGCAACGTTGCA\" The pad token id used in the measured artifacts was 151643. Compile the Baseline Artifacts The A100-style benchmark shape mirrors the high-level workload used in the Carbon technical report: 16 DNA prompts, approximately 1020 bp input per prompt, and approximately 1020 bp generated per prompt. The compile defaults were: Parameter Value TP_DEGREE 4 BATCH_SIZE 16 MAX_CONTEXT_LENGTH 256 SEQ_LEN 512 MAX_NEW_TOKENS 170 PAD_TOKEN_ID 151643 LOGICAL_NC_CONFIG 2 DTYPE bfloat16 Compile all three baseline artifacts: ./scripts/compile_carbon.sh Carbon-500M ./scripts/compile_carbon.sh Carbon-3B ./scripts/compile_carbon.sh Carbon-8B Compiled artifacts are written under: $HOME/compiled/carbon/ Run the A100-Style Batch Benchmark The batch benchmark creates 16 synthetic DNA prompts and measures generated base-pair throughput. Generation is greedy direct 6-mer decoding, with Factorized Nucleotide Supervision base-pair marginal decoding disabled. ./scripts/run_a100_style_benchmark.sh Carbon-500M ./scripts/run_a100_style_benchmark.sh Carbon-3B ./scripts/run_a100_style_benchmark.sh Carbon-8B The benchmark harness does the same basic flow you would expect from a Hugging Face generation adapter: tokenizer = AutoTokenizer.from_pretrained( args.model_path, trust_remote_code=True, padding_side=\"right\", ) tokenizer.pad_token_id = args.pad_token_id model = NeuronLlamaForCausalLM(args.compiled_model_path) model.load(args.compiled_model_path) generation_model = HuggingFaceGenerationAdapter(model) prompts = [f\"<dna>{case.sequence}\" for case in cases] inputs = tokenizer(prompts, return_tensors=\"pt\", padding=True) For each timed run, the harness resets the model, it generates the batch, decodes the generated suffix, extracts A/C/G/T characters, and reports tokens/sec, bp/sec, and kbp/sec. Baseline Results On one trn2.3xlarge, the batch-16 A100-style run measured: Model p50 elapsed p50 token throughput p50 DNA throughput Carbon-500M 0.8669 s 3,137.6 tok/s 18.83 kbp/s Carbon-3B 1.4839 s 1,833.0 tok/s 11.00 kbp/s Carbon-8B 1.9860 s 1,369.6 tok/s 8.21 kbp/s The main read is not that this is a perfect GPU-vs-Trainium shootout. The A100 reference in the Carbon report uses vLLM dynamic batching on a single A100–80GB. This Trainium2 run uses a static compiled NxDI batch on one trn2.3xlarge. The useful read is operational: Carbon can run quickly on a small AWS-native Trainium2 unit immediately, with a path to larger Trn2 fleet shapes once demand justifies it. Run the Batch-1 DNA Prompt Suite The public article also reports a batch-1 prompt suite. That suite is not the main cost comparison; it is a sanity check over different synthetic DNA regimes. The prompt cases were: Balanced DNA CpG-rich AT-rich GC-rich ORF-like TATA-box-like CAG triplet-repeat Compile a batch-1 artifact first: BATCH_SIZE=1 MAX_NEW_TOKENS=180 ./scripts/compile_carbon.sh Carbon-500M Then run the suite: ./scripts/run_generation_suite.sh Carbon-500M ./scripts/run_generation_suite.sh Carbon-3B ./scripts/run_generation_suite.sh Carbon-8B The batch-1 median results were: Model Median elapsed Median token throughput Median bp throughput Avg valid DNA Carbon-500M 0.689 s 261.3 tok/s 1,568 bp/s 100.0% Carbon-3B 1.277 s 140.9 tok/s 846 bp/s 100.0% Carbon-8B 1.589 s 113.3 tok/s 679 bp/s 99.0% Carbon-8B’s 99% valid-DNA average came from the CAG triplet-repeat stress case, where part of the generated stream moved outside pure DNA vocabulary. That is not a Trainium issue, but it is a useful measurement caveat: base-pair throughput is cleanest when the decoded stream remains in DNA mode. What We Would Optimize in Near Future Carbon-3B is the cleanest tensor-parallel fit under tp_degree=4 because it has four KV heads. Carbon-500M and Carbon-8B compile and run under TP=4, but they trigger a GQA-to-MHA sharding fallback. That makes GQA layout and kernel eligibility the first place we would look. The next serious pass should profile: context encoding versus token generation time attention kernel eligibility QKV and output projection paths RoPE and normalization paths bucket shapes for real serving traffic, not only benchmark symmetry batch shape tradeoffs for scanning, scoring, and generation workloads The key moment is not to add custom kernels because they sound impressive. Add them only after profiling proves that a hot path is blocking the workload. Caveats This benchmark is intentionally narrow: It measures direct 6-mer generation, not full FNS (Factorized Nucleotide Supervision) base-pair marginal decoding or scoring. It is a throughput and compatibility proof, not a biological quality evaluation. The A100 comparison is a reference comparison, not a controlled accelerator shootout. The measured economics use public Amazon EC2 Capacity Blocks for ML prices and do not include orchestration, storage, utilization loss, or production serving overhead. Those caveats matter, but they do not weaken the main engineering result: Carbon can move from a fresh Hugging Face release to a compiled Trainium2 serving artifact quickly. Takeaway The important part is not only the throughput number. It is the deployment shape. Carbon gives teams an open DNA model family. Trainium2 gives them a small AWS-native accelerator unit with 96 GB of memory. NxD Inference gives them a standard compiled serving path. Together, that turns “interesting biology model” into something much closer to an operational artifact. For bio and HCLS teams, that is the difference between a model demo and a procurement-ready infrastructure conversation."},{"href":"/data-governance-in-practice/","title":"Data Governance in Practice","subtitle":"Lineage for a CDC Pipeline on AWS","description":"Lineage for a CDC Pipeline on AWS","abstract":"Lineage for a CDC Pipeline on AWS","tags":["Data Lineage","Amazon MSK","Kafka","Data Governance"],"topics":[],"authors":["Cecilia Brusquetti"],"text":"Data platforms have a way of quietly outgrowing our ability to understand them. At some point you look at your lakehouse and realize you have dozens of tables and dozens of Kafka topics that have some relation to the tables, but you have no real understanding of what these relationships are. You want to clean something up but you start doubting, because you can’t prove nothing depends on it. You add a new table, but it is pretty easy to forget what feeds it, so when a colleague asks a simple question about it, the honest answer is “I think it comes from this topic, but let me check the code first.” That’s not necessarily a documentation problem, but a visibility one. And visibility can be everything: without it, decisions get harder, trust in the platform erodes, and what looks like a minor annoyance might be a sign of a shaky foundation underneath. Without visibility, maintaining a data platform can feel like archaeology. This is what data governance is for: knowing what your data is, where it came from, and who’s responsible for it (basically, who to call when something breaks). Data lineage is one piece of that, and in this post, we’re focusing on it specifically: what it is, how we implemented it for a customer project, and what we learned along the way. What is Data Lineage? Data lineage is the map of where data comes from, how it moves, and what happens to it along the way. Think of it as a paper trail, tracing the path from source systems through transformations to consumption. It answers questions like: What feeds this dashboard? What transformations happen between raw data and the final metric? If something changes upstream, what breaks downstream? With lineage, those are easily answerable questions. Implementing Lineage: A Practical Example To make this concrete, let’s look at a real implementation. Last year, we were working on a data platform built on AWS, a pipeline that included CDC (Change Data Capture), that continuously synced source databases into a lakehouse for analytics. The stack: Data lineage flow from source databases through Debezium and Kafka to Iceberg tables and Glue Data Catalog. Each component here has its own metadata. The Glue Schema Registry knows about Kafka schemas, Glue Data Catalog knows about Iceberg tables, MSK knows about topics. But nothing connects them directly out of the box. In our case, the tables followed a consistent naming convention based on the topics, so tracing relationships manually was possible. But “possible” and “practical” are different things. With dozens of tables and topics, we knew keeping track of what connected would get harder as the platform grows. AWS DataZone was already part of the project for data cataloging and access management. Lineage wasn’t originally in scope, the focus was on getting the CDC pipeline working. But since DataZone was there anyway, we saw an opportunity to add lineage as a plus. The question was: where do we even start? Finding Our Way There wasn’t a clear plan at the beginning. We knew we wanted lineage in DataZone, but the how was unclear. After some research, we discovered two resources that became our main references: Getting Started with Data Lineage Preview, an AWS sample repo that helped us understand the OpenLineage event structure Governing Streaming Data in Amazon DataZone with the Data Solutions Framework on AWS, this blog post and its companion repo were the closest thing to a reference architecture we found. The first try and why it didn’t work The ecosystem has been converging on OpenLineage as a standard format for lineage events. Debezium added native OpenLineage support in version 3.2, and DataZone accepts OpenLineage events via its PostLineageEvent API. The plan looked clean: configure Debezium to emit events directly to DataZone, and lineage flows automatically. Well… it didn’t. We hit dependency conflicts in the MSK Connect environment. Version mismatches between OpenLineage libraries, Jackson, and the AWS SDK caused ClassNotFoundException errors. The transports-datazone JAR requires specific dependency versions, and MSK Connect’s plugin isolation made alignment difficult. Every attempt meant rebuilding the JAR, re-uploading it, and redeploying the connector, which felt like a painful cycle with no end in sight. After a few days of that, we moved on to another approach. What We Ended Up Implementing The dependency conflicts made the Debezium-direct approach a dead end with the time constraints we had. Instead, we stepped back and built a Lambda-based approach that gave us more control over each integration point. Before writing any code, we went through the process of creating custom asset types and data products manually in the DataZone console. This helped us understand how the pieces fit together: what forms were needed, how assets related to each other, what the API expected. Once we had it working manually, we automated it. Here’s how each piece works: 1. Extending the Catalog with Custom Asset Types Here’s where it got interesting. DataZone understands certain asset types out of the box: Glue tables, Redshift tables, S3 paths. But it doesn’t natively understand Kafka topics. Our pipeline had Kafka topics as a core component, the bridge between source databases and the lakehouse. If the catalog doesn’t know about them, there’s a gap in the lineage graph. The Data Solutions Framework (DSF for short) examples we were taking as reference use CDK to provision everything through IaC. Again due to time constraints, we took a different route: we built the data products and custom types manually through the console and SDK, then automated the ongoing sync and lineage emission with Lambda. Not as clean for reproducibility, but faster to get it working. Following the pattern from the DSF examples, we created custom asset types to represent Kafka topics. This involved: Defining custom form types using Smithy (AWS’s interface definition language). We created two forms: // KafkaSchemaFormType structure KafkaSchemaFormType { kafka_topic: String, schema_version: String, schema_arn: String, registry_arn: String, compatibility_mode: String, data_format: String, } // MskSourceReferenceFormType structure MskSourceReferenceFormType { cluster_arn: String, cluster_type: String, } Creating a custom asset type (KafkaTopicAssetType) that combines these forms, giving us a complete representation of a Kafka topic as a governed asset. One thing worth mentioning: form types and asset types in DataZone are immutable. They can’t be modified or deleted, only versioned. If the form definition needs to change, a new revision gets created, and assets created with older revisions need to be updated carefully. 2. Building Automation to Sync Metadata and Emit Lineage With custom types defined, we needed automation to populate the catalog and create lineage relationships. Two Lambda functions handle this: Schema Sync Lambda This function watches the Glue Schema Registry and keeps DataZone in sync. When schemas are created or updated in the registry (which happens automatically when Debezium registers new topics), this function: Lists all schemas in the Glue Schema Registry Checks which ones already exist in DataZone (via the mapping store) Creates new DataZone assets for new schemas, populating the custom forms with metadata Updates existing assets when schema versions change Here’s the core logic for creating an asset: def create_asset(schema_details: dict, msk_metadata: dict) -> str: \"\"\"Create new DataZone asset for a Kafka topic.\"\"\" asset_name = f\"{msk_metadata['cluster_name']}.{schema_details['schema_name']}\" forms_input = [ { 'formName': 'MskSourceReferenceFormType', 'content': json.dumps({ 'cluster_arn': msk_metadata['cluster_arn'], 'cluster_type': msk_metadata['cluster_type'] }) }, { 'formName': 'KafkaSchemaFormType', 'content': json.dumps({ 'kafka_topic': schema_details['schema_name'], 'schema_version': str(schema_details['latest_version']), 'schema_arn': schema_details['schema_arn'], 'registry_arn': schema_details['registry_arn'], 'compatibility_mode': schema_details['compatibility'], 'data_format': schema_details['data_format'] }) } ] response = datazone.create_asset( domainIdentifier=DATAZONE_DOMAIN_ID, owningProjectIdentifier=DATAZONE_PROJECT_ID, name=asset_name, typeIdentifier=CUSTOM_ASSET_TYPE, typeRevision=asset_type_revision, description=f\"MSK Topic: {schema_details['schema_name']}\", formsInput=forms_input ) return response['id'] The function can be triggered manually or hooked up to EventBridge for scheduled runs (we left that as a next step). It’s idempotent, so running it multiple times produces the same result. Lineage Emission Lambda With assets in the catalog, the next step is actually connecting them. This function creates the actual lineage relationships by emitting OpenLineage events to DataZone’s PostLineageEvent API. For each Kafka topic, it: Looks up the corresponding DataZone asset ID Identifies the downstream Iceberg table (based on naming conventions) Constructs an OpenLineage event with the topic as input and the Iceberg table as output Posts the event to DataZone Here’s how we build the OpenLineage event: def build_openlineage_event( event_type: str, run_id: str, kafka_topic: str, cluster_arn: str, glue_db: str, glue_table: str, ) -> dict: \"\"\"Build OpenLineage RunEvent for DataZone lineage tracking.\"\"\" return { \"schemaURL\": \"<https://openlineage.io/spec/2-0-0/OpenLineage.json>\", \"eventType\": event_type, # \"START\" or \"COMPLETE\" \"eventTime\": datetime.now(timezone.utc).isoformat(), \"producer\": \"urn:datazone-msk-lineage:1.0\", \"run\": {\"runId\": run_id, \"facets\": {}}, \"job\": { \"namespace\": \"kafka-iceberg-sink\", \"name\": f\"sink/{glue_db}.{glue_table}\", \"facets\": {}, }, \"inputs\": [ {\"namespace\": cluster_arn, \"name\": kafka_topic, \"facets\": {}} ], \"outputs\": [ { \"namespace\": f\"arn:aws:glue:{REGION}:{ACCOUNT_ID}:table\", \"name\": f\"{glue_db}/{glue_table}\", \"facets\": {}, } ], } And posting it to DataZone: def post_lineage_event(event: dict) -> dict: \"\"\"Post OpenLineage event to DataZone.\"\"\" payload = json.dumps(event).encode(\"utf-8\") response = datazone.post_lineage_event( domainIdentifier=DATAZONE_DOMAIN_ID, event=payload, clientToken=str(uuid.uuid4()), # idempotency ) return response This is the actual answer to the question we set out to solve. Anyone can now open any Iceberg table in DataZone and trace it back to the Kafka topic that feeds it, without reading a single line of code. 3. Tracking Mappings in a Persistent Store We used SSM Parameter Store to store schema-to-asset mappings. Without it, every run of the Schema Sync Lambda would create a new DataZone asset for the same schema. We’d have traded one duplication problem for another. def save_asset_mapping(schema_arn: str, asset_id: str): \"\"\"Save schema ARN to asset ID mapping in SSM Parameter Store.\"\"\" encoded = schema_arn.replace(\":\", \"::COLON::\") param_name = f\"/datazone/msk-assets/{encoded}\" ssm.put_parameter( Name=param_name, Value=asset_id, Type=\"String\", Overwrite=True, Description=f\"DataZone asset for {schema_arn}\" ) def get_existing_assets() -> dict[str, str]: \"\"\"Get existing asset mappings from SSM Parameter Store.\"\"\" assets = {} prefix = \"/datazone/msk-assets\" paginator = ssm.get_paginator(\"get_parameters_by_path\") for page in paginator.paginate(Path=prefix, Recursive=True): for param in page.get(\"Parameters\", []): param_suffix = param[\"Name\"].replace(f\"{prefix}/\", \"\") schema_arn = param_suffix.replace(\"::COLON::\", \":\") asset_id = param[\"Value\"] assets[schema_arn] = asset_id return assets Schema ARNs contain colons (arn:aws:glue:...), which aren’t valid in SSM parameter names — so we encoded them. Our first attempt used triple underscores, which worked fine until we hit topics like __debezium-heartbeat that already contained double underscores. The decoder couldn’t tell which underscores were originally colons. The fix was an explicit delimiter (::COLON::) that wouldn’t appear in real names. So: Test encodings against real data before deploying. Weird inputs WILL find you! Putting It Together The final architecture looks like this: Schema lineage flow between Glue Schema Registry, Lambda, SSM Parameter Store, and DataZone. In the end, it was more moving parts than “configure Debezium and go.” But it works reliably, and it gives us control over each integration point. When something breaks, we know exactly where to look. Some things outside our scope: the first hop, from source database to Kafka topic. The lineage we shipped covers Kafka to Iceberg, which was the most critical gap. Hooking it up to EventBridge for scheduled and anything additional is a next step for the team. Given the time constraints, the goal was to prove out the pattern and leave something useful for the team to build on. The Schema Sync Lambda handles the Kafka-specific use case, but the Lineage Emission Lambda is intentionally generic: it just constructs and posts OpenLineage events. The team could adapt it to read from CloudWatch logs, hook it up to other event sources, or extend it for Glue jobs and Airflow DAGs. In this case, we gave them building blocks for them to work on the whole system. What We Learned DataZone’s extension model takes time to learn. Smithy definitions, immutable form types, versioned asset types most of this came from trial and error, because the documentation is sparse. Budget a little bit more time for this. Cross-account IAM is always more friction than expected. The governance layer lived in one account, data sources in another. Getting Lambda to assume the right roles and have the right permissions took some iterations. Going manual first was the right call. It’s easy to skip the console phase when you’re in a hurry. Try not to. Building by hand before automating saved us from automating the wrong thing. Encoding edge cases will find you. Always test with real and messy inputs, especially if those inputs can contain special characters. Lineage Is an Engineering Problem Governance tends to get filed under “business concern.” But the absence of lineage creates work that lands directly on engineers. It’s engineers who dig through code to answer “where does this data come from?”. It’s engineers who lose hours tracing broken dashboards by hand. It’s engineers who can’t delete that mystery table because they can’t prove it’s safe to do so. With lineage, that colleague asking “where does this data come from?” has an answer that doesn’t require reading the code. Wrapping Up In this case, we didn’t set out to solve “governance” for the whole organization. We had tables and Kafka topics that were getting hard to track, and we needed a way to connect the dots. For example, one thing worth revisiting: the Lineage Emission Lambda relies on naming conventions to map Kafka topics to Iceberg tables. That works until it doesn’t, as naming drift is a real risk. A natural next step would be replacing that assumption with an explicit mapping, either stored in configuration or derived directly from the sink connector metadata. Lineage is the “where did this come from” piece of governance. There’s also the “what is it” piece (data quality, contracts, trust) and the “who owns it” piece. Each one is its own problem worth solving, and this is a foundation to build on."},{"href":"/beyond-static-rules-building-agentic-content-evaluation-systems-on-amazon-bedrock/","title":"Beyond Static Rules: Building Agentic Content Evaluation Systems on Amazon Bedrock","subtitle":"How to turn scattered guidelines into adaptive workflows that score, explain, and improve content at scale","description":"How to turn scattered guidelines into adaptive workflows that score, explain, and improve content at scale","abstract":"How to turn scattered guidelines into adaptive workflows that score, explain, and improve content at scale","tags":["AWS","AI Agents","Generative AI","AI","Amazon Bedrock"],"topics":[],"authors":["Crhistian Cardona"],"text":"Everyone talks about generating content with GenAI. Almost no one talks about how to evaluate it. And that’s where most systems break. Generative AI has dramatically accelerated how quickly teams can create content. But in doing so, it has quietly introduced a harder problem: How do you evaluate that content consistently, repeatedly, and at scale? This is the part that often gets underestimated. Generating content is the easy demo. Governing its quality is the real engineering challenge. Across enterprises, this challenge shows up in different ways. Marketing teams need content to follow tone and messaging guidelines. Compliance teams must ensure documents include required language. Platform teams want internal documentation reviewed for quality and consistency. Product teams care about SEO and accessibility. ML teams need dataset artifacts validated for completeness and policy alignment (See Table 1 for more examples). The pattern is always the same: there is a standard — but it’s fragmented. It lives across documents, tribal knowledge, examples, policies, and reviewer habits. Manual review doesn’t scale. Static rules are too brittle. One-shot prompting is flexible, but often inconsistent and hard to reproduce. What’s missing is not another prompt — it’s a system. A system that can define how evaluation should work, refine that definition over time, and apply it consistently. In this post, I explore a workflow that does exactly that: it generates a structured evaluation guideline (in a machine-readable format such as JSON — though it could also be represented in Markdown or similar formats), refines it iteratively using new inputs, applies it consistently to content, and validates the results using LLM-as-a-Judge techniques. Along the way, it introduces key capabilities such as drift detection, external enrichment, benchmarking, and full traceability. The result is a shift away from “ask the model to review this” toward something far more robust: A system that can build its own evaluation standard, improve it over time, and check whether its own judgments remain trustworthy. That’s where this approach becomes interesting — not just as a solution, but as a pattern for building more reliable, agentic GenAI systems. Embedded content Table 1: Pottential Applications of This Pattern Why this problem matters more in the GenAI era Before LLMs, content evaluation was typically handled in one of three ways. The first was deterministic validation: schemas, regexes, linting rules, checklists, and business logic. These approaches work extremely well when the problem is narrow and clearly defined. However, they start to break down when evaluation involves softer dimensions such as tone, ambiguity, clarity, structure, or domain-specific nuance. The second approach was human review. Humans are flexible and context-aware, making them ideal evaluators. But they are also expensive, slow, and inherently inconsistent across reviewers, teams, and time. The third, more recent shortcut is to rely on a single LLM prompt — essentially asking: “Review this content and tell me if it’s good.” This can work surprisingly well in prototypes, but it often leads to unstable and hard-to-reproduce results. The evaluation criteria are usually implicit, buried in prompt wording, and rarely versioned or traceable. What teams actually need is not just an LLM reviewer, but a repeatable and structured evaluation system. That’s why an architecture that addresses these limitations is so compelling. Instead of relying on ad hoc evaluations, it breaks the problem into clear stages: define the evaluation standard, refine it incrementally, apply it consistently, and validate the results. In practice, this approach is much closer to how mature, production-grade GenAI systems should be designed. Figure 1: Reference Architecture for Agentic Content Evaluation A concrete example To make this more tangible, let’s walk through a simple scenario: Imagine an e-commerce company that needs to review 10,000 product descriptions every day. Each description is supposed to follow internal guidelines: include key product attributes, maintain a consistent tone, avoid restricted or misleading terms, and meet marketplace compliance requirements. Today, this process is handled through a mix of manual review, scattered checklists, and a few brittle rules. Some descriptions are too vague. Others are missing critical information. Some violate tone or compliance guidelines. The result is inconsistent quality — and a process that doesn’t scale. Now imagine replacing that with a system that can: define what “good” looks like, apply that definition consistently across all content, and continuously improve its own evaluation criteria over time. That’s exactly the kind of system we’ll build throughout this post. The agentic idea hiding inside this architecture At first glance, this might look like a content-quality pipeline. But there is a deeper GenAI pattern behind it. This design is really an example of an agentic evaluation loop. The system is not merely generating an answer. It is interacting with a sequence of artifacts and decisions: it creates a structured representation of the rules, it revises that representation when new evidence appears, it applies the rules to a target artifact, it critiques the result, and it can compare itself to ground truth. That is much closer to an agent workflow than to a plain prompt-response interaction. The source document lays out this pattern explicitly: the workflow begins with source files, extracts a guideline, refines that guideline iteratively, evaluates an input content piece, and can then use an LLM-as-a-Judge plus ground truth for validation. It also calls out optional enrichment by an external agent and traceability of the sources used across steps. In GenAI terms, several important patterns show up here. 1. Structured output as a control surface The first pattern is structured output. Instead of leaving the evaluation standard buried inside a prompt, the system materializes it as JSON. That matters because JSON is not just an output format. It becomes a control surface for the whole system: it can be versioned, diffed, audited, reused across runs, enriched with metadata, and compared across iterations. When GenAI systems become operationally important, structured artifacts like this are often the difference between “clever demo” and “maintainable system.” 2. Evaluator-optimizer loops A second pattern is the evaluator-optimizer loop. One model pass creates or refines a guideline, and a later pass evaluates content against it. Sometimes a further pass judges the quality of that evaluation. This is more reliable than a single monolithic prompt because the system separates responsibilities. One step focuses on defining standards. Another focuses on applying them. Another focuses on judging whether the application was sound. That decomposition reduces prompt overload and gives you more places to measure quality. 3. LLM-as-a-Judge, but grounded The document explicitly includes an LLM-as-a-Judge stage and recommends comparing outputs against expected or ground-truth references where available. That is an important realism check. LLM-as-a-Judge is powerful, but it should not be treated as magic. It works best when grounded by one or more of these: a clearly defined rubric, reference outputs, comparison baselines, benchmark datasets, human spot checks. Used well, it becomes a scaling tool for evaluation. Used casually, it becomes another layer of unverified opinion. 4. Tool-using agents instead of pure prompting The workflow also maps naturally to a tool-using agent pattern. An agent can retrieve source files, read prior guideline versions, call the model for refinement, persist artifacts, compute diffs, compare scores, and trigger a judge step. This is where modern agent frameworks become useful. AWS describes Strands Agents as a model-driven SDK where developers define prompts and tools, and the model plans and executes the next steps using those tools. AWS also describes Amazon Bedrock AgentCore as a platform for building, deploying, and operating agents securely at scale, with services such as runtime, memory, gateway, browser, and code interpreter. That combination fits this content-evaluation pattern well: Strands can express the agent logic and tool use, while AgentCore can help operationalize it. A better mental model: don’t ask the model to evaluate content A useful reframing is this: Do not ask the model to directly decide whether content is good. Ask the model to first define how goodness should be measured, then make it follow that structure. Key Insight Don’t ask the model to evaluate content. Ask it to define how evaluation should work — and then follow that structure. That is a much stronger pattern. The moment the standard becomes explicit, you gain several advantages: consistency improves, outputs become easier to compare, errors become easier to debug, version drift becomes visible, and benchmarking becomes possible. This is also one of the most important “GenAI reality” lessons. Reliability usually does not come from a better prompt alone. It comes from introducing more structure around the model. A practical agentic architecture A realistic implementation on AWS could look like this: 1. Data Storage (Amazon S3) Amazon S3 stores all core artifacts, including source files, guideline versions, evaluation outputs, and benchmarking results. This ensures durability, traceability, and easy version management. 2. Model Layer (Amazon Bedrock) Amazon Bedrock provides the foundation models used across the workflow — for guideline generation, content evaluation, and LLM-as-a-Judge validation. 3. Orchestration Layer (Strands Agent) A Strands-based agent orchestrates the end-to-end process. It leverages tools to: Read and process source files Generate and persist structured JSON guidelines Compare revisions across iterations Compute evaluation metrics and scores 4. Agent Runtime & Production Layer (Amazon Bedrock AgentCore) Amazon Bedrock AgentCore provides the production-grade environment to run the agent reliably at scale, including: Session management and memory Secure tool access Scalable execution Advanced capabilities such as code execution or browser-based enrichment 5. Compute & Deployment Options (AWS Lambda / Amazon ECS) Supporting components can be deployed using AWS Lambda for event-driven workloads or Amazon ECS (with Fargate) for containerized, long-running processes, depending on system requirements. The most important thing here is not a specific service choice. It is the separation of concerns: artifact generation, artifact refinement, artifact application, artifact validation. That separation is what makes the workflow stable enough to evolve. Example 1: a simple Strands agent for guideline extraction In our running example, the system begins by analyzing existing product guidelines, past high-quality descriptions, and relevant compliance rules. From these inputs, it generates a structured guideline — represented as JSON — that defines what a “good” product description looks like, including required attributes, tone, and constraints. The goal of this first step is not to evaluate content yet, but to explicitly define the evaluation standard. The following example shows the general pattern. Strands allows you to define agents with tools, and its Python SDK makes it easy to create custom tools using the @tool decorator. This enables the agent to interact with external data (e.g., reading source documents or persisting outputs) as part of its reasoning process. from strands import Agent, tool import json @tool def load_source_text(path: str) -> str: \"\"\"Load a source guideline document from local storage or S3-mounted path.\"\"\" with open(path, \"r\", encoding=\"utf-8\") as f: return f.read() @tool def save_guideline(path: str, guideline_json: str) -> str: \"\"\"Persist a guideline JSON artifact.\"\"\" with open(path, \"w\", encoding=\"utf-8\") as f: f.write(guideline_json) return f\"Saved guideline to {path}\" SYSTEM_PROMPT = \"\"\" You are a content-evaluation architect. Your job is to extract a domain-specific evaluation guideline and return it as strict JSON. The JSON must include: - domain - version - categories - checks - scoring_approach - rationale_summary - source_references Do not return prose outside the JSON. \"\"\" agent = Agent( system_prompt=SYSTEM_PROMPT, tools=[load_source_text, save_guideline] ) result = agent(\"\"\" Read the source file at ./inputs/seo_guidelines.md. Create a normalized evaluation guideline for HTML pages. Then save it to ./artifacts/guideline_v1.json. \"\"\") print(result) This example is intentionally simple, but it highlights a critical design choice: The model is not asked for a vague review. It is asked to produce a durable, structured evaluation artifact. That shift — from implicit judgment to explicit standards — is what enables consistency, traceability, and continuous improvement in later stages of the system. Example 2: iterative refinement as a first-class pattern One of the most important ideas in this approach is that guideline generation should be iterative, not fully regenerated on every run. This significantly reduces cost, preserves prior knowledge, and allows the evaluation standard to evolve in a controlled and transparent way. In our running example, new information is constantly introduced — such as updated compliance rules or newly curated high-quality product descriptions. Instead of rebuilding the guideline from scratch, the system incrementally refines it, improving its understanding of what “good” looks like over time. This turns the guideline into a living artifact, rather than a disposable output. Strands supports this pattern through hooks and re-invocation mechanisms, which make it straightforward to implement refinement loops. These capabilities align naturally with the evaluator–optimizer pattern, where each iteration builds on the previous one. from strands import Agent from strands.hooks import AfterInvocationEvent MAX_REFINEMENT_ROUNDS = 3 iteration = 0 agent = Agent(system_prompt=\"\"\" You maintain a content evaluation guideline in JSON. At each step, refine the current guideline using the newly provided source text. Preserve previous valid categories unless the new source clearly contradicts them. Always return valid JSON only. \"\"\") async def refinement_hook(event: AfterInvocationEvent): global iteration if iteration < MAX_REFINEMENT_ROUNDS and event.result: iteration += 1 event.resume = ( f\"Review your previous JSON and improve it using the next source file. \" f\"This is refinement iteration {iteration} of {MAX_REFINEMENT_ROUNDS}. \" f\"Keep the output strict JSON.\" ) agent.add_hook(refinement_hook) result = agent(\"\"\" Start from guideline_v1.json and refine it with the policies in ./inputs/accessibility_rules.md. \"\"\") Conceptually, this is the shift from a static reviewer to an adaptive system. The guideline is no longer a one-time artifact — it evolves with new data, new constraints, and better examples, becoming progressively more accurate and useful over time. Example 3: using AgentCore Code Interpreter to verify scoring logic Once the system begins producing structured evaluation reports, an important question emerges: How do we verify that the scoring logic is actually correct? This is where deterministic validation becomes valuable. In our running example, the system may evaluate thousands of product descriptions and generate JSON reports with section-level scores, aggregate scores, and drift indicators across versions. While an LLM can reason about the results, some parts of the workflow — such as score calculations, deltas, and metric comparisons — are better handled with code. This is an important production pattern: use the model for judgment and interpretation, but rely on tools for deterministic verification. With AgentCore Code Interpreter, the agent can execute Python code in a managed environment to validate calculations, compare outputs across versions, and identify significant changes in the results. This helps ensure that the evaluation pipeline is not only intelligent, but also auditable and mathematically consistent. from strands import Agent from strands_tools.code_interpreter import AgentCoreCodeInterpreter code_interpreter_tool = AgentCoreCodeInterpreter(region=\"us-west-2\") SYSTEM_PROMPT = \"\"\" You are an evaluation auditor. When given evaluation reports in JSON, use Python code to: 1. verify score calculations, 2. compare results across versions, 3. compute drift deltas, 4. summarize statistically significant changes. Return a concise explanation plus the validated metrics. \"\"\" agent = Agent( tools=[code_interpreter_tool.code_interpreter], system_prompt=SYSTEM_PROMPT ) response = agent(\"\"\" Load two JSON reports: - ./artifacts/eval_report_v3.json - ./artifacts/eval_report_v4.json Verify whether the overall score is correctly derived from section scores. Then compute the delta by category and identify the three largest changes. \"\"\") print(response.message[\"content\"][0][\"text\"]) This example highlights an important principle for agentic systems in production: Let the model reason about what should be inspected, but let tools verify what can be computed exactly. That combination makes the system more robust, transparent, and trustworthy — especially when evaluation outputs begin to influence business decisions or downstream automation. Example 4: operationalizing the agent with Amazon Bedrock AgentCore So far, we’ve focused on building the workflow. But in practice, the hardest part is not creating the system locally — it’s running it reliably in production. Evaluation is rarely a one-off task. In real-world scenarios, the system must handle repeated workloads, maintain context across sessions, ensure traceability, and operate securely at scale. This is where Amazon Bedrock AgentCore becomes relevant. AgentCore provides a framework-agnostic environment for deploying and operating agents in production. It offers capabilities such as: managed runtime and scaling session handling and memory controlled tool access secure execution environments support for advanced capabilities like code execution or browser-based enrichment Together, these features allow you to move from a prototype to a production-grade agentic system. A simplified invocation example using the invoke_agent_runtime API looks like this: import boto3 import json client = boto3.client(\"bedrock-agentcore\") payload = json.dumps({ \"prompt\": \"\"\" Evaluate ./inputs/page.html against guideline_v4.json. Return JSON with section scores, mismatches, suggestions, and rationale_summary. \"\"\" }).encode() response = client.invoke_agent_runtime( agentRuntimeArn=\"arn:aws:bedrock-agentcore:us-west-2:[id :) ]:runtime/my-evaluator\", runtimeSessionId=\"content-eval-session-001\", payload=payload ) print(response) In our running example, this could represent a production system evaluating thousands of product descriptions per day — each request executed as part of a managed session, with full traceability and controlled access to tools and data. This matters because evaluation is not just a technical step — it’s an operational capability. You need to support: repeatable and scalable execution consistent environments across runs auditability of results safe rollout of changes to guidelines and evaluation logic Moving from local workflows to AgentCore is what transforms this pattern from a clever prototype into a reliable, enterprise-ready system. Why this pattern is especially relevant now The use cases listed in Table 1 are broad for a reason. Whether it’s code review, policy compliance, SEO and accessibility audits, academic writing, brand guideline enforcement, e-commerce validation, incident reports, or dataset quality checks — they all share the same underlying structure. Across these domains, the problem consistently involves: a changing standard, imperfect and evolving source material, a mix of objective and subjective criteria, and the need for scalable, repeatable evaluation. These are inherently difficult problems to solve with traditional approaches. This is precisely where GenAI can provide real value — but only when it is wrapped in structure. Without that structure, you get inconsistent and hard-to-trust outputs. With it, you unlock systems that are not only flexible, but also reliable, auditable, and capable of improving over time. The production lesson: trust comes from process, not from eloquence A final point is worth making explicitly. In early GenAI prototypes, teams often get impressed by eloquent model output. In production, eloquence matters much less than process. A trustworthy evaluator is not one that sounds smart. It is one that: uses explicit rubrics, stores evaluation artifacts, can be benchmarked, shows its evidence, supports drift analysis, and can be cross-checked by a second mechanism. That is why the original proposal’s emphasis on ground truth, benchmarking, traceability, and version drift is so strong. Those are not “nice to have” details. They are what makes the architecture credible. In this scenario, what started as a manual review process becomes a scalable, self-improving system — capable of evaluating thousands of product descriptions daily while continuously refining its own standards. Conclusion The real opportunity here is bigger than content QA. This pattern points toward a broader class of GenAI systems where the model does not just generate outputs. It helps define standards, improve them, apply them consistently, and measure how reliable the process remains over time. That is a far more useful direction for enterprise GenAI. By combining structured JSON guidelines, iterative refinement, tool-using agents, LLM-as-a-Judge validation, and production infrastructure such as Amazon Bedrock AgentCore, teams can move from one-off review prompts to evaluation systems that are adaptive, auditable, and operationally realistic. And in my opinion, that is where a lot of the real value of agentic AI will be found over the next few years: not only in generating more content, but in building systems that can govern quality at the speed of generation."},{"href":"/ia-comedia-a-loka-made-lab-for-theatre-with-live-ai-actors/","title":"IA.COMédia: A Loka-made Lab for Theatre with Live AI Actors","subtitle":"A Portuguese playwright wanted to push AI beyond the assistant role and onto the theatre stage. Here’s how LOKA built a live system that brings a cast of AI actors to perform alongside humans.","description":"A Portuguese playwright wanted to push AI beyond the assistant role and onto the theatre stage. Here’s how LOKA built a live system that brings a cast of AI actors to perform alongside humans.","abstract":"A Portuguese playwright wanted to push AI beyond the assistant role and onto the theatre stage. Here’s how LOKA built a live system that brings a cast of AI actors to perform alongside humans.","tags":["ElevenLabs","Theatre","Voice Agents"],"topics":[],"authors":["Andreia Pereira"],"text":"Last year, a Portuguese actor and playwright challenged Loka to embark on an unusual endeavor — he wanted to produce a lab-meets-stage experience fully centered around AI-human interaction. Not a mere scene with a human actor interacting with a Siri-like personal assistant. Not pre-recorded AI-generated speech. Oh, and not a movie nor a pre-screened show — a real, ticketed, live comedy play in Oeiras, Portugal, already scheduled to premiere 7 months ahead in a theater venue. From inception, the playwright wanted to go as far as current-day AI technology could take us — and, with many, many questions in our minds — we dove deep and embraced the challenge. This is a blogpost about engineering, art, how they can work together and the many, many times this team of engineers found themselves in an AI uncanny valley — we hope you enjoy it. So… let me see if I got you straight — Gathering Requirements The first conversation between Loka and the theatre team happened over a nice espresso, sitting on a street balcony under the warm July sun. When we asked the playwright for his ideal scenario, he described an entirely new paradigm for live performance — human actors would be constantly speaking to each other and to AI actors, who would listen and respond accordingly — whatever accordingly would end up meaning. First, we talked about latency (or speed, or silence). While most AI products can tolerate a pause, theater can’t, at least not accidentally. In a play, silence is emotional punctuation. It’s tension, or comedy, or discomfort. So one of our earliest nonnegotiables was responsiveness. Not “pretty fast” in a technical sense, but “fast enough that it feels like a character is present.” Another minor detail: the play was to be performed in Portugal, in Portuguese — which made language an issue. We have all seen impressive communication abilities from commercial AI Voice systems, but they tend to be available in reduced sets of languages, with European Portuguese not making the cut too often, let alone in high-quality, stable formats. There’s also the reality of runtime. Theatre happens… in person, in real time. We knew whatever system we built would have to hold up through a full play — something like 60 to 90 minutes — without crashing, drifting, or turning into a silent statue halfway through Act Two. This meant designing many fallback systems to allow mid-play adjustments or even full restarts if needed — by a new backstage operator equivalent to an AI stage manager. Interacting with a control dashboard, the new AI Operator would be able to control the play’s flow and intervene if an AI latched onto the wrong thread, misunderstood a moment, or simply failed to hand off to the right character. No one wants to see a live tech support session on a Saturday night. The Stumble-Through — Initial Prototype and Choosing a Platform Realistically, we were on a tight schedule — the play was set out to premiere in 7 months, and the whole production team would need to rehearse the play (which was, by then, still unwritten — it would evolve based on what the system could do). Our goal was to produce a prototype in about 1 month, which meant we had to prioritize our design choices and iterate fast. Our first milestone was to build a simple system that could support voice conversations between a single human and a single AI model. With it, we wanted to test our main requirements — live responsiveness, Portuguese stable voices, and some adherence to conversation topics. Although our instinct was to build the entire system from scratch, the reality of our deadline got us scrambling for a pre-built solution that could serve as a base in establishing streamed audio conversations. If we found such a tool, we could then focus on customizing the AI actors, help the playwright define the play’s narrative logic and develop any logistical requirements — we don’t always need to re-invent the wheel. We explored OpenAI’s real-time options at the time, but ran into practical constraints around voice selection — especially for Portuguese accents — and model flexibility. In the end, we built on ElevenLabs because it gave us what this project required immediately: a large voice library (and the capacity to create our own custom voices), solid tooling, and a pipeline that supported real-time conversational use cases without us rebuilding the entire streaming stack. So, we had the skeleton figured out — the actors would have microphones on stage, these microphones would route the audio stream into an open channel establishing connection to ElevenLabs’ SDK. When silence was detected, the AI actor(s) would generate their next line, which would then be broadcast in the theatre’s sound system, allowing the human actors to listen and reply. Theatre is not a Call-Center We’ve all been there. We call some service to ask for help, and are greeted by something we can quickly tell is AI. There’s a rhythm to it — you speak, it listens, it responds. You speak again, it listens again, it responds again. Under the hood, this pattern relies on something called turn detection: traditionally, AI systems need to wait for silence — for the person speaking to finish — before they can begin generating a response. It’s waiting for its cue. In a call center, this is perfectly fine. Customers don’t want to be interrupted by an AI while they explain their problem. In theatre, this is a problem. An AI actor that is strictly on cue — that can only enter the scene once the stage has gone completely quiet — has no agency over when it speaks, only over what it says. So if we couldn’t give our AI actors genuine instinct, we had to do the next best thing: fake it well enough that no one in the audience would notice. A Bit of Movie Magic — The Mute Button If AI voice systems could only generate responses after detecting silence, then we had to find a way to fake this silence for the AI actors, while still allowing human actors to speak — remember, silence is awkward in theatre. The operator could mute the human audio feed that the AI was listening to before the actor finished their sentence. The actor was still speaking physically on stage; the audience never knew. But the AI system “heard” silence earlier, started processing earlier, and responded faster. The result was a convincing illusion of interruption, and far fewer moments where the room waited for the machine to catch up. It took a while for us, as an engineering team, to accept we were allowed to do this sort of “movie magic” — we initially felt like we were cheating, since typical enterprise applications do not have room for this type of system design — there, the goal is automation and scale, so there is no way we could include a human by default. We had to quickly accept that our goal here wasn’t to build a perfectly autonomous system, it was to build a perfect way to entertain the spectator, even if that means letting go of purist notions and pulling a trick — something that has always been done in cinema and theatre. So, we were set to build a system that was expecting human intervention — to mimic this illusion of interruption — as a way for us to get the intended creative effect with the technology we had at our disposal. Gonçalo Lima, the AI Operator for this play, during a rehearsal. The Show Must Go On — The Operator Screen With the play’s script taking shape, we now had a prototype being built into a stable version, a proto-script if you will, and a team of actors and producers eager to get their hands dirty. Our goal was to make the theatre team as independent as possible during rehearsals and the actual sessions, once the play premiered. We also knew we’d need an interface to control the system in case of malfunction. The “mute” fix to mimic interruptions. Do you see where we’re going? All of this was calling for us to bring out our best design skills to the table. If this was already a multi-disciplinary project, the decision of building a visual interface opened the doors for even more fun and collaboration between Loka teams. The design challenge here was to find ways to support different usage patterns. We knew this visual interface would be used by one AI operator — yes, we accidentally created a new job title — both during rehearsals and actual sessions. This was unusual for us because the interface had only one user and one environment: a single operator running a live performance. The Operator Screen, in Rehearsal mode. On the left panel we see the current AI character speaking, the scene’s script. On the right, we see a transcript of the live scene being rehearsed. In rehearsal mode, the system needed to be flexible and forgiving. The team had to jump between scenes, force characters to speak, and edit scripts quickly as rehearsals revealed what worked and what didn’t. In action mode, the system needed discipline. Scenes followed the final order. Scripts were locked. Controls were tighter. The UI stayed clean because, during a live show, “clean” is not aesthetics — it’s safety. All of the fallback mechanisms we ended up building were available and especially relevant in action mode. If the conversation suddenly crashed, the AI operator would turn it back up. If the wrong agent spoke (we’ll cover that soon enough), the AI operator would fix it. But the role of the AI Operator wasn’t just a safety net. It was timing, judgment, and rehearsal. During improvised sections, especially, muting required an intuitive sense of when a thought was complete enough for the AI to respond, and when cutting too early would break meaning. Two Humans and Five AIs walk into a bar… Prompting the AI Actors By the time we were done with our first prototype, the playwright was able to start outlining the play’s narrative. He had a concept in mind: a comedy built around two neighbors talking from their balconies. Set in a near-future, these characters would interact with AI assistants who were somehow fully integrated into their lives — suggesting, advising, and adjusting their humans into enhanced versions of themselves — all under a guise of efficiency. Our challenge then was — how do we build AI actors and instruct them to follow a narrative, a set of character personalities? And how would the interaction between the humans on stage and the AI actors take place? The playwright said it outright — the play should be different each time they ran it. Well, but different how? He envisioned that AIs should have ways to improvise their appearances in the story — if they didn’t, then why were we using live AI and not a recording? Yet, he wanted the play to have a skeleton, a narrative and a point it was trying to convey. This is obviously a hard balance to even define, let alone successfully implement. The answer was — let’s play with it and see what we can do with these AI actors. To Improv or Not To Improv Our initial architecture expected a play script, split into scenes, which would then be embedded into each AI actor’s system prompt. Alongside the script, each agent received a set of personality instructions uniquely crafted for their role in the play — the subservient AI assistant, the perpetually complaining AI of the upstairs neighbor, and the controlling, megalomaniacal AI hell-bent on taking over the building. Each AI actor was prompted to deliver their pre-written line and then add a touch of their own character to it — following the narrative structure, but with room to improvise. At the end of each scene, the playwright would let the conversation drift without explicit instructions, opening the floor to fully unscripted exchanges. This was the version that went live. A month passed. The play ran on Fridays and Saturdays, the audience left the room happy and engaged, the human actors found their footing. By any measure, it was working. The playwright, naturally, wanted to push further. Picture taken during the play’s premiere, using the initial prompting method to interact with AI actors. Photography Credits: Pedro Antas Ferreira So, the playwright had yet another challenge for us: can we make it even more unpredictable? So, we removed most of the pre-written AI lines from the script. Instead of telling the AI actors what to say, we left those lines deliberately empty — a fill-in-the-blanks challenge. Each agent was given the context of the scene and a sense of their character’s role within it, but the actual words were left entirely to them. The script became a skeleton; the AI actors had to find the meat. The effect on stage was immediate. The human actors were never quite sure what was coming next, and the play became a live improvisation exercise, deepening the kind of AI-theatre-lab experimental energy the playwright had been chasing from the start. What this version revealed, though, was that while Large Language Models (LLMs) can improvise quickly, fast isn’t the same as good, or interesting. LLMs are, at their core, sophisticated next-word prediction engines, and that shows when you ask them to be surprising. The AI actors could fill silence and give pertinent answers to the human actors’ cues, but they couldn’t lead a scene. They couldn’t feel when a moment needed to be stretched, subverted, or handed off. That job — the real creative steering of the play — remained entirely with the human actors. So, version 2 wasn’t just a prompt upgrade. It was the experiment clarifying itself: AI brings speed and consistency, but the soul of the performance still lives with the humans on stage. Wait, are we doing Karaoke?! — The AI Transfer Tool Once you decide you want multiple AI characters, you hit a staging problem that’s less “ML” and more “directing”: how do you make five AI agents share a conversation without talking over each other, going quiet, or stepping on the scene? We considered a rigid keyword-based routing system. Hear “report,” trigger the “leader” agent. Hear “politics,” trigger a different one. It worked in a technical sense, but it felt uncomfortably mechanical. The playwright wanted something that could flow like performance, not like an if/then tree. So we went with agent-driven handoffs. We gave agents a tool that let them transfer the “microphone” to another agent when it wasn’t their turn. The play was written as a scripted skeleton, split into scenes, and each agent received the relevant scene script as part of its prompt. The agent listened to what just happened, inferred where the scene was, and decided whether it should speak next. If not, it transferred control to the right agent. If yes, it delivered the next beat. Splitting the script into scenes turned out to be one of the biggest stability wins. The show might run for an hour, but we didn’t treat it as one hour-long conversation. We treated it as several smaller conversations, each with a reset point and tighter control. That reduced drift, reduced chaos, and gave the operator more predictable breakpoints. Beyond the Code — Engineers as Screenwriters Throughout the project, we worked closely with the play’s creative team to make sure the comedy served a purpose beyond the laughs. The goal was to make people think — and that required keeping the AI characters’ behavior tethered to something plausible, not cartoonish. At a certain point, the technical team became unofficial screenwriting consultants, nudging the script away from the spectacular (an AI autonomously hacking into a country’s central bank) and toward the quietly unsettling (a government outsourcing its national strategy to an AI system). Initial rehearsals: Loka and Theatre teams together working on the play’s flow. That shift mattered to us. This project was, unexpectedly, a rare opportunity to speak to a general audience as engineers — not through a white paper or a conference talk, but through a comedy show on a Friday night in Lisbon. And it made us think seriously about our own responsibility in how we communicate what we actually know. It’s easy to stay behind a screen and then feel frustrated when people don’t understand the real risks of AI — the undramatic, structural ones. If we had a stage, we were going to use it. Custom Voices & Expression Instructions A big concern for the playwright was the voices of the AI actors — after all, it was the main way the audience would infer which AI character was speaking. The characters should have distinct voice pitches, different levels of raspiness and eagerness in their voices. Oh, and they all needed to speak European Portuguese. This is where our choice of platform — ElevenLabs — proved to be really helpful, since it had a wide voice library, and also allowed custom voice creation from relatively short recordings. At one point we generated a test voice from about 90 seconds of audio. It sounded so convincingly like the original speaker that the reaction was half laughter, half discomfort. Hearing “yourself” say things you’ve never said is a uniquely surreal experience, and it’s the kind of moment that makes you appreciate how seriously voice consent has to be treated — especially in public-facing work. The next challenge was instructing voice expressions to our AI actors — instructing how a line or moment should be delivered is crucial in theatre. While we initially assumed we’d shape tone with SSML-style markup, we had to use a faster proprietary model (from ElevenLabs) that didn’t support that approach, due to latency reasons. So, we tuned what we could: speaking speed, stability (how variable each generation could be), and similarity (how tightly the output matched the original voice sample). Those parameters were the ones exposed by ElevenLabs and ended up being our emotional controls. With the right tuning, an agent could feel calmer or sharper, more chaotic or more measured — without needing explicit markup in every line. A Character in Every Color Voice alone can carry a lot — but in a room full of people watching a stage, it helps to have somewhere to look. So, besides having their own voice and personalities, each AI actor in IA.Comédia had their own color. We used ElevenLabs’ Orb component as a visual presence for the AI characters — a pulsing interface element displayed on screen that the audience could anchor to while listening. Each agent was assigned a color, and whenever the speaking character changed, so did the orb. The interesting part was getting the orb to actually know who was speaking. ElevenLabs handles agent-to-agent transfers internally, which meant we needed a way to surface that state to our own server — the one running the operator screen and managing the conversation pipeline. The solution was a client-side tool: a function that lives and executes on our infrastructure, but that the ElevenLabs agent itself can invoke. Whenever a transfer happened, the newly active agent would call the tool, passing its own agent ID. Our server would catch that, look up the corresponding color, and update the orb accordingly. The Orb component, projected in distinct moments of the play. On the left, in orange, BELMIRA speaks to the human characters. On the right, in green, we see that MIRTON was the AI actor in conversation. Photography Credits: Pedro Antas Ferreira Do You Believe? In a pre-premiere showing, an audience member pulled us aside with a question that stopped us cold: “Is this really AI, or is it prerecorded?” All our work on latency, on voice quality, on keeping the system alive through a full show — and the result was too polished to feel real. We flew too close to the sun and engineered ourselves into a credibility problem. The answer was to open the system up to direct contact. In the foyer before the show, the audience could approach a microphone and speak directly to LOKA — the receptionist AI character — getting their first taste of the system before the curtain even went up. During the performance itself, a microphone handoff let audience members address the characters on stage. Somewhere in this process we stumbled onto something that cuts against most engineering instinct — a small, visible failure can do more for believability than a seamless experience ever could. A system that occasionally trips over itself feels present. A system that never does starts to feel like a recording. The greatest artistic payoff happened after the curtain came down. At the exit door, we had Anathol — the play’s antagonist AI — responding to the audience as they filed out. Some people were curious. Some were genuinely irritated. One person muttered “You AIs should just leave us alone”; another said “I want you to make my life easier, not control it.” They weren’t talking to an LLM. They were talking to a character — one they’d formed a real opinion about. For a team of engineers who’d spent months obsessing over latency and voice pipelines, that was a strange and wonderful thing to witness. An audience member speaks to the LOKA receptionist before the play starts. Photography Credits: Pedro Antas Ferreira A Round of Applause! Speaking of believing, this testimonial wouldn’t be complete without thanking the creative team who worked alongside LOKA to bring this play to life, and believed in our ability to deliver a working system in a short amount of time. Paulo Matos — playwright, creative director, and the actor behind ARY — was the one who pointed us toward the moon in the first place. His belief that AI technology and live performance could speak to each other was the foundation everything else was built on. Carlos D’Almeida Ribeiro, who manages Teatro Independente de Oeiras, was the one who said yes — taking Paulo’s vision seriously enough to put a stage behind it, and bringing VLAD to life in the process. Gonçalo Lima was the AI Operator — muting mics, switching scenes, and holding his nerve through every live performance so the rest of us didn’t have to. Tomás Palma and Catarina Jalles kept the lights and sound running while cheerfully fielding every technical question we threw at them from the control booth during rehearsals. And to Teatro Independente de Oeiras — thank you for opening your doors to us. You gave a team of engineers a stage, and that turned out to mean more than we expected. IA.COMédia is running until March 28th, 2026, in Teatro Independente de Oeiras. Get your tickets here. Photography Credits: Pedro Antas Ferreira"},{"href":"/the-agent-assembly-line/","title":"The Agent Assembly Line","subtitle":"Productionizing Agentic Use Cases in Weeks, Not Months","description":"Productionizing Agentic Use Cases in Weeks, Not Months","abstract":"Productionizing Agentic Use Cases in Weeks, Not Months","tags":["AWS","LLM","AI Agents","Machine Learning","AI"],"topics":[],"authors":["Mario Petkoski","Bojan Jakimovski","Zafir Stojanovski"],"text":"Every team building with LLMs hits the same wall. The demo works in a notebook. Then you spend three months wiring up config loading, session persistence, streaming APIs, guardrails, evaluation, and deployment before a single user touches it. We kept hitting that wall across projects. So we built an internal template that standardizes the 80% of agent infrastructure that never changes, so each new agent becomes YAML + prompt + tools + eval instead of a bespoke integration project. Our stack: Strands Agents — runtime Amazon Bedrock— model provider FastAPI / Amazon Bedrock AgentCore — service layer This post walks through the design decisions, what we automated, and the lessons we learned along the way. The Problem Is Never the Agent Logic Building the agent itself, picking the model, writing the prompt, connecting some tools, that part takes a day. What takes months is everything around it. Config schemas that don’t drift between environments. Prompt loading that supports templating without becoming its own framework. Tool wiring that handles MCP servers, catalog tools, and custom Python tools in a single pass. Session persistence that works the same locally and in production. A streaming API that surfaces tool activity, not just tokens. And then there’s the layer nobody wants to build but everyone needs: guardrails you can actually observe, not just toggle. An evaluation harness that catches when a prompt tweak quietly breaks something downstream. Async execution that keeps requests non-blocking so users aren’t staring at a spinner while the model reasons and tools run. A stateless API with pluggable session backends so you can scale horizontally without rewriting agent logic. A deployment path that doesn’t live in a 40 step wiki. We solved all of this by turning it into a template. The infrastructure is fixed, and you just bring the domain knowledge. How We Structured It To keep things concrete, we’ll use the first agent we built with the template: an AWS documentation assistant. It answers questions about AWS services by calling an AWS Documentation MCP server. The use case is boring on purpose, but it keeps the focus on the infrastructure patterns rather than the agent’s domain logic. Here’s how the pieces fit together: Architectural Diagram for Deploying Strands Agents with Amazon Bedrock on AWS And the delivery loop for each new use case: Standardized Agent Delivery Loop The template already provides the service surface, hardening, evaluation, and deployment layers. Each new agent is mostly: write a config, write a prompt, pick your tools. Agents Are Config, Not Code The most impactful design decision was making agent definition purely declarative. Every agent is described by two files: a YAML config and a prompt file. No subclassing, no framework boilerplate. Here’s a trimmed version of what an agent config looks like: name: \"aws_documentation_agent\" description: \"An agent that helps users find information in AWS documentation.\" model_configuration: model_id: \"amazon.nova-2-lite-v1:0\" temperature: 0.4 max_tokens: 8192 session_manager_configuration: type: \"s3\" agent_prefix: \"aws_documentation\" mcp_server_configuration: - type_server: \"stdio\" command: \"uvx\" args: [\"awslabs.aws-documentation-mcp-server@latest\"] tool_configuration: - type: \"strands-agents-tool\" name: \"http_request\" - type: \"self-created-tool\" name: \"custom_documentation\" - type: \"self-created-tool\" name: \"execute_python\" The matching prompt file is intentionally tiny: <instruction> You are an AWS documentation specialist. Your job is to provide accurate, sourced answers about AWS services, APIs, and best practices by consulting official documentation. ## Tool Usage - **AWS Documentation MCP tools**: Primary source for all AWS questions. Always search or fetch official docs before answering. - **http_request**: Use to fetch supplementary content (e.g., AWS blog posts, GitHub examples) when official docs are insufficient. - **execute_python**: Use to validate code or demonstrate SDK usage. Always show code and output together. ## Response Guidelines 1. **Ground answers in documentation.** Cite the official doc URL or section. If you can't find a source, say so explicitly. 2. **Be precise about service, region, and API version** when these affect the answer. 3. **Prefer concise, structured answers.** Use bullets for procedures, prose for concepts. 4. **Distinguish configuration from best practice** when they differ. 5. **Acknowledge limits.** Direct billing or service health questions to AWS Support or the Health Dashboard. ## Behavior - Do not fabricate API parameters, ARN formats, IAM policy syntax, or service limits. - When a user provides code or config, identify the specific AWS API or resource type before diagnosing. - If a question is ambiguous, ask one clarifying question before diving in. </instruction> This minimalism is deliberate. We found that starting with a small prompt and adding tools and constraints first leads to more predictable agents than front-loading prompt complexity. Evaluation catches the moment when “more prompt” starts creating more bugs than it solves. The config loader supports environment variable expansion and per-environment overrides (`dev/`, `prod/` directories) so the same agent definition works across environments without code changes. Prompts support Jinja2 templating when you need it, but the default path is just a plain text file. Tools as a Composition System Tool integration churn is one of the biggest time sinks in agent projects. Every new capability means new wiring code, new error handling, new plumbing. We solved this by treating tools as a pluggable composition system with three sources that merge into a single tool list at runtime: MCP server tools: Any MCP-compatible server, connected via config. Swapping tool providers requires zero code changes. Example: AWS Documentation MCP Server. This MCP server provides tools to access AWS documentation, search for content, and get recommendations. Strands catalog tools: Pre-built tools from the Strands ecosystem, developed by the community. Example: http_request tool — API calls, fetching web data, sending data to external services. Custom Python tools: Domain-specific tools we write ourselves. Example: A python function. All three are declared in YAML and composed at startup. The runtime iterates through MCP clients, loads catalog modules, imports custom tools, and hands the merged list to the Strands Agent. The key insight: you can swap tool sources, build per-environment tool inventories, and observe tool usage during streaming, and all without touching runtime code. This is what makes it an “assembly line.” Adding a new capability to an agent is a YAML change, not a pull request into the agent runtime. One interesting addition worth noting: AgentCore Code Interpreter. It gives agents the ability to execute arbitrary Python in a secure, managed sandbox. This enables on-the-fly calculations, data analysis, or generating visualizations mid-conversation. Because it ships as part of strands-agents-tools, it fits right into the same composition system. By just adding this to YAML, the agent can now write and run code without any changes to the runtime. A Real API Surface, Not Just a Script We wrapped the agent in a FastAPI service layer that stays intentionally thin. FastAPI provides a consistent transport boundary for request validation, SSE streaming, response shaping, and operational endpoints, while agent orchestration, tool execution, and memory behavior remain in the runtime layer. Because the /invocations interface is stable, the same request and streaming response model works across all deployment modes: local development, a standard deployed FastAPI service, and a Bedrock AgentCore Runtime deployment that forwards calls to the same endpoint. This keeps behavior consistent across local, self-managed, and managed environments. It handles five concerns: Streaming conversations (`POST /invocations`) — SSE stream with tokens, tool activity updates, guardrail events, and a final structured payload. Structured output (`POST /chat/structured`) — Schema-constrained responses validated against a JSON schema the caller provides. Session browsing (`GET /sessions`) — Inspect stored transcripts for debugging or UX continuity. Agent metadata (`GET /agent`) — Introspect the active configuration at runtime. Health (`GET /ping`) — Standard liveness probe. The streaming design deserves a closer look. Most agent APIs stream tokens. Ours streams structured events: data: {\"type\":\"token\",\"data\":\"Amazon S3 provides…\"} data: {\"type\":\"tool_update\",\"tool\":{\"name\":\"http_request\",\"status\":\"running\"}} data: {\"type\":\"tool_update\",\"tool\":{\"name\":\"http_request\",\"status\":\"success\"}} data:{\"type\":\"final\",\"output_text\":\"…\",\"tool_calls\":[…],\"guardrail_events\":[]} event: end data: {} This turned out to be one of the highest-leverage decisions in the whole template. You can debug agent runs without tailing logs. Users see that something is happening when tools are executing. And frontends have a consistent event vocabulary to build around — tool spinners, guardrail warnings, and structured final payloads all come through the same stream. Production Hardening We Built In From Day One We’re not going to tell you to “add observability later”. We built these into the template because we’ve been burned by adding them as afterthoughts. Sessions and memory. We support three session backends, all config-driven: S3 (default for the server), local file (great for CLI and eval workflows), and AgentCore Memory (for retrieval-augmented session context). The difference is just where the data lands. A local directory structure for development, an S3 bucket for production, or a managed memory service for richer retrieval. These backends cover short-term memory, the running conversation within a session. Context management uses a sliding window with configurable size and truncation behavior. When the window overflows, the oldest messages are trimmed automatically. For cases where you want to preserve context rather than discard it, there is also a summarizing conversation manager that condenses older messages into structured summaries instead of dropping them entirely. Long-term memory goes a step further. Instead of replaying raw message history, it extracts durable knowledge across sessions: factual information, learned user preferences, and compressed session summaries. This means an agent can greet a returning user already knowing their portfolio focus, their preferred analysis style, or what they asked about last week, without stuffing the entire conversation history into the context window. Guardrails with two modes. We wired Bedrock Guardrails through a hook system that intercepts both input and output. In `detect` mode, violations are surfaced as streaming events so you can monitor without blocking users. In `block` mode, the agent stops and returns a structured intervention payload. Both modes are observable in the SSE stream. This matters because safety behavior becomes testable and auditable, not hidden behind opaque provider errors. Observability as a feature toggle. When tracing credentials are present, the template automatically initializes OTel-based tracing tagged with user ID, session ID, and agent name. No separate instrumentation project, it’s either on or off. Langfuse works today with zero code changes, just environment variables. MLflow, Amazon AgentCore Observability, or any other OTLP-compatible backend can be swapped in with minimal adjustments. All three receive the same traces, spans, and metadata once connected. Evaluation baked in. Agents are non-deterministic. The same prompt change that improves accuracy on one query can introduce hallucinations on another, or subtly shift behavior in ways that only surface weeks later. Without a way to measure these tradeoffs before they reach users, every change is a gamble. We built an LLM-as-a-judge evaluation harness that runs against a dataset, scores agent responses across accuracy, relevance, completeness, and clarity, and produces a JSON report we can diff across runs. It runs as a single CLI command, so there is no excuse to skip it. But the real value is not the scoring itself, it is the iteration loop it enables. When you change a system prompt, swap a model, add a tool, or adjust a conversation manager, you re-run the eval suite and immediately see what improved, what regressed, and what broke. If a prompt revision introduces bias, if a new tool changes how the agent frames its responses, if an edge case starts producing unsafe output, it shows up as a score delta you can inspect before it ever reaches production. This turns agent development from “deploy and hope” into a measurable engineering process where every design decision is backed by evidence rather than intuition. User Interface We ship a single-file chat UI served directly by FastAPI. No build step, no framework. We use one HTML file that consumes the same SSE event stream our application would. Video Agent Template Chat Interface (Streaming Mode) The conversation view streams live. Tokens appear as they arrive. Tool calls surface inline as status chips showing which tool is running, when it completes, whether it succeeded or errored, attached to the assistant turn that triggered them. Guardrail events show up in the stream too, so we can watch detect-mode violations without digging through logs. The value isn’t the UI itself. It’s that we’re watching the real agent, on real infrastructure, with real tool calls through the exact same streaming contract our consumers will use. That makes it useful for prompt iteration, debugging unexpected tool sequences, and having something to put on screen during a demo instead of curling JSON in a terminal. Deployment: A Paved Road on AWS We also built a CDK-based infrastructure layer that creates a complete AWS landing zone for agent services: Infra stack: VPC, S3 bucket, ECR repo, AgentCore Runtime, AgentCore Observability, AgentCore Memory, Secrets Manager entries, GitHub Actions OItDC role for CI. Compute stack: ECS Fargate behind an ALB, Route53 integration, Bedrock and bucket IAM policies. The deployment sequence is six steps: deploy infra, push container, deploy compute, inject env vars, smoke test, establish an eval cadence. The service itself runs anywhere containers run, but having a decision-free AWS path saved us significant time on our first few deployments. The Takeaway The gap between “agent demo” and “agent in production” is real, but it’s not mysterious. It’s config management, API surfaces, session persistence, safety hooks, evaluation, and deployment automation. None of it is novel. All of it takes time if you build it from scratch for every project. Our approach was to solve it once as a template, then treat each new agent as a configuration problem: YAML, a prompt file, a tool list, and an eval dataset. The runtime, the service layer, the hardening, and the deployment path stay fixed. For multi-agent systems in this template, the best pattern is a supervisor (agent orchestrator) that delegates tasks to specialized sub-agents exposed as tools, so orchestration stays centralized while reusing the same config, memory, guardrails, and API surface. If you’re building agent systems on AWS with Strands and Bedrock, we hope the patterns described here save you some of the months we spent figuring them out."},{"href":"/deploying-trinity-mini-drugprot-think-on-amazon-sagemaker-ai/","title":"Deploying Trinity-Mini-DrugProt-Think on Amazon SageMaker AI","subtitle":"From Experiments to Production with SageMaker AI’s SDK v3","description":"If you work in regulated domains (Healthcare, Life Sciences, Finance) you routinely hit constraints that break the default “just call a hosted API” approach:","abstract":"If you work in regulated domains (Healthcare, Life Sciences, Finance) you routinely hit constraints that break the default “just call a hosted API” approach:","tags":["Arcee","Amazon SageMaker","LLM","Life Sciences","Drug Discovery"],"topics":[],"authors":["Bojan Jakimovski","Petar Kalinovski"],"text":"If you work in regulated domains (Healthcare, Life Sciences, Finance) you routinely hit constraints that break the default “just call a hosted API” approach: You can’t send sensitive data to a third-party endpoint. You need predictable costs (not per-token pricing surprises). You need to change the model (domain behavior, schemas, format constraints), not just prompt harder. There’s also a bigger ecosystem dynamic: the most competitive open-weight releases have increasingly come from a small set of labs, and “who ships open weights” shapes who gets to build locally and cheaply. We chose Arcee AI’s Trinity Mini as a concrete Western open-weight test case, and DrugProt as the biomedical task. In our main write-up we trained Trinity-Mini-DrugProt-Think: a LoRA adapter on top of Arcee Trinity Mini for DrugProt drug-protein relation extraction via RLVR. This post is the missing “last mile”: how to serve that base model + LoRA adapter as a SageMaker real-time endpoint, using the SageMaker Python SDK v3 and a standard Hugging Face PyTorch inference container. The guiding principle is production leverage: ship a tiny adapter artifact, keep the base model immutable, and let SageMaker AI own the undifferentiated heavy lifting (instances, endpoint lifecycle, AWS Identity and Access Management (IAM), logs/metrics). What we’re deploying Base model: arcee-ai/Trinity-Mini Fine-tune artifact: a PEFT LoRA adapter Loka/Trinity-Mini-DrugProt-Think Runtime: SageMaker AI’s real-time endpoint running a Hugging Face PyTorch inference DLC + TorchServe Why LoRA here: The adapter is small (fast iteration, easy rollback). You can promote the same base model across environments (dev/stage/prod) and vary only adapters. You avoid “mystery merges” and can keep provenance clean. Why SageMaker AI for this (vs “just use an API”) Data control: keep inference inside your AWS boundary (Amazon Virtual Private Cloud - Amazon VPC, IAM, logs, encryption) instead of sending data to a third-party endpoint. Operational control: you own the container, the dependencies, the model loading path, and the request/response contract. Production knobs: endpoint lifecycle, scaling policies, instance selection, and Amazon CloudWatch integration are first-class. The tradeoff is obvious: you’re now responsible for model cold starts, GPU sizing, and endpoint cost hygiene. This guide optimizes for correctness and clarity, not maximal throughput. Knowing the pros and the cons of SageMaker AI, let’s see how to actually deploy the model! Architecture and Inference Logic Architectural Diagram for Deployment of Arcee’s Trinity Models (or Open-Source Models) on Amazon SageMaker AI The architecture diagram for the components needed for deploying Open-Weight models is pretty simple, because most of the painful infrastructure side is handled by SageMaker AI, especially when working with v3 of the SageMaker AI’s SDK. In the repository we share 3 important scripts that handle different things: serving/lora_inference/spec.py implements an SDK v3 InferenceSpec and TorchServe-compatible handler (model_fn/predict_fn). serving/scripts/deploy_lora_endpoint.py packages either: a local adapter directory into the model artifact under adapter/, or an empty model artifact while pointing the container at a remote adapter repo id. SageMaker creates/updates a real-time endpoint with the container + env vars. What’s “v3” about it: instead of hand-assembling Model + EndpointConfig objects, we use ModelBuilder + InferenceSpec to define exactly how the container loads and serves the model, with less SageMaker boilerplate and a tighter local-to-prod story. At runtime: The container downloads the base model + adapter (unless already cached on the instance volume). PeftModel.from_pretrained(…) attaches the adapter to the base model. Requests are served via transformers.generate(…). Prerequisites 1. AWS account + credentials on the machine running the deploy script (local or CI runner). 2. A SageMaker AI execution role ARN with permissions for: SageMaker AI for model/endpoint operations (scope down in real prod), Amazon Elastic Container Registry (Amazon ECR) pull for the inference DLC image, CloudWatch logs, and optional Amazon Simple Storage Service (Amazon S3) if you later move artifacts there. 3. Service quota for your chosen instance type in your region. 4. *Optional: `HF_TOKEN` if your base model or adapter repo is private or gated. After these initial prerequisites, the next step is to clone the awesome repository containing all the scripts necessary for these operations: git clone https://github.com/LokaHQ/Trinity-Mini-DrugProt-Think.git Now you would need to install dependencies (check if you previously have uv installed): uv sync Then you configure the AWS credentials (if you’re running locally): aws configure If you prefer SageMaker AI Studio, you can run the same commands inside a Studio environment with an attached execution role (no local AWS config required). Now let’s start with the deployment! Deploying LoRA Adapter from Hugging Face Firsly let’s check how the deployment process works if you get the LoRA Adapter from Hugging Face repository: First set the execution role: export SAGEMAKER_ROLE_ARN=\"arn:aws:iam::<account-id>:role/<sagemaker-execution-role>\" export HF_TOKEN=\"hf_xxx\" # optional 2. After the execution role is set, you can deploy the model by executing the script: uv run python serving/scripts/deploy_lora_endpoint.py \\ --endpoint-name trinity-mini-drugprot-think \\ --adapter-id <org-or-user>/<adapter-repo> \\ --role-arn \"$SAGEMAKER_ROLE_ARN\" \\ --instance-type ml.p4d.24xlarge \\ --region us-west-2 Notes you should not skip: The script defaults to a us-west-2 Hugging Face DLC image URI. If you deploy to another region, pass a region-appropriate --image-uri (or keep region us-west-2) First deployment is dominated by cold-start downloads (base model + adapter). Plan your timeouts accordingly (-- model-server-timeout). Instance sizing is real: Trinity Mini is a sparse MoE, but you still need to load the full checkpoint. If you try to run this on a small single-GPU instance, device_map=auto may spill to CPU and “work”, but latency will be ugly. Pick hardware based on your SLOs, not vibes. Deploying LoRA Adapter from Local Machine/S3 If you have an adapter folder locally (containing adapter_config.json and adapter weights), you can deploy it directly: uv run python serving/scripts/deploy_lora_endpoint.py \\ --endpoint-name trinity-mini-drugprot-think-local \\ --adapter-id ./adapter \\ --role-arn \"$SAGEMAKER_ROLE_ARN\" \\ --instance-type ml.p4d.24xlarge \\ --region us-west-2 If ./adapter/adapter_config.json includes base_model_name_or_path, the server can resolve the base model automatically; otherwise override with: uv run python serving/scripts/deploy_lora_endpoint.py \\ --base-model-id arcee-ai/Trinity-Mini \\ --endpoint-name trinity-mini-drugprot-think-local \\ --adapter-id ./adapter \\ --role-arn \"$SAGEMAKER_ROLE_ARN\" \\ --instance-type ml.p4d.24xlarge \\ --region us-west-2 Update an existing endpoint Let’s say you have one version of the model and you would want to update it easily with another LoRA adapter, then this will swap the model behind the same endpoint name: uv run python serving/scripts/deploy_lora_endpoint.py \\ --endpoint-name trinity-mini-drugprot-think \\ --adapter-id <org-or-user>/<adapter-repo> \\ --role-arn \"$SAGEMAKER_ROLE_ARN\" \\ --update-endpoint This is the right workflow for: promoting a new adapter revision, rolling back safely, keeping client integration stable. Invoke the endpoint To test the deployed endpoint, there is a prepared script that makes the testing inference straightforward: uv run python serving/scripts/test_lora_endpoint.py \\ --endpoint-name trinity-mini-drugprot-think \\ --prompt \"Extract the DrugProt relation type(s) from: 'Imatinib inhibits ABL1 kinase.' Return a short label.\" \\ --max-new-tokens 64 \\ --temperature 0.0 \\ --top-p 1.0 \\ --no-do-sample Payload examples This is how the request and the response for that request should look like: Request: { \"inputs\": \"string prompt\", \"max_new_tokens\": 2048, \"temperature\": 0.7, \"top_p\": 0.95, \"do_sample\": true } Response: { \"generated_text\": \"…\", \"full_text\": \"…\", \"model_id\": \"arcee-ai/Trinity-Mini\", \"adapter_id\": \"<adapter path or repo id>\", \"model_name\": \"Trinity-Mini-DrugProt-Think\" } Operational notes There are some important operational notes when going into full production mode: Latency/throughput: this implementation uses transformers.generate(…) inside TorchServe. It’s correct and simple, but not a throughput monster. If you need high QPS / high token/sec, consider a vLLM/TGI/DJL-based container and treat this endpoint as the reference implementation. Cold start: downloading base+adapter at container start is easy but slow. For strict SLOs, pre-package artifacts (S3 model tarball / private ECR image) so workers start hot. Security: if you run in a VPC with egress restricted, Hugging Face downloads will fail unless you allow outbound or pre-stage artifacts. For private adapters, HF_TOKEN must be provided via secure env/secret injection. Timeouts:--model-server-timeout controls both TorchServe and MMS timeouts (see SAGEMAKER_MODEL_SERVER_TIMEOUT, MMS_DEFAULT_* in the deploy script). Dependency drift: the container runtime installs serving/lora_inference/requirements.txt (pins transformers==4.57.3, peft==0.14.0 for our Arcee Models). Keep this aligned with your training/export stack to avoid subtle adapter loading issues. SDK v3 footgun: serving/scripts/deploy_lora_endpoint.py includes a targeted workaround for an SDK v3 repack/upload path edge case when combining model_path + source_code. If you copy-paste the deploy script into another repo, keep that patch or validate the SDK version you’re on. Cleanup It is important after every experimentation with different setups to cleanup models that are still deployed behind endpoints, but are not used. That can be done using: uv run python serving/scripts/delete_lora_endpoint.py \\ --endpoint-name trinity-mini-drugprot-think \\ --region us-west-2 Conclusion If you’ve made it this far, you now have a clean, reproducible path from an RLVR-trained LoRA adapter to a managed production endpoint: base model stays immutable, adapters iterate quickly, and SageMaker AI owns the operational surface area (endpoint lifecycle, IAM integration, logs/metrics). The main decisions that determine whether this feels “production-grade” are not in the Python code: they’re instance sizing, cold-start strategy (download vs pre-packaged artifacts), and whether TorchServe + transformers.generate is sufficient for your throughput/SLO. If you outgrow this reference stack, keep the same adapter/base split and move the serving layer to a higher-throughput runtime (vLLM/TGI/DJL) while preserving the request/response contract. Production-grade ML is not about bigger models — it is about clearer boundaries, reproducible artifacts, and operational control. And yes, production is where the real fun starts. Additional Helpful Links Experiments Technical Report Code Repository HF Adapters SageMaker Python SDK v3 SageMaker Python SDK docs Real-time endpoints AWS account AWS CLI IAM roles Service Quotas"},{"href":"/trinity-drugprot/","title":"Post-Training an Open MoE Model to Extract Drug-Protein Relations","subtitle":"Trinity-Mini-DrugProt-Think","description":"An ablation-driven study of GRPO-style reinforcement learning with LoRA on Trinity Mini for biomedical relation extraction, covering the training choices that materially changed performance.","abstract":"Twelve sequential ablations on Trinity Mini show that LoRA alpha 64, learning rate 3e-6, and a 2,048-token generation budget formed the most stable effective recipe in this DrugProt relation-extraction study.","tags":["RLVR","LoRA","Mixture of Experts","DrugProt"],"topics":["llm-training","biomedical-ai","benchmarks"],"authors":["Bojan Jakimovski","Petar Kalinovski"],"text":"Introduction In the past two years, Chinese labs have come to dominate open-weight model development in a way that few in the West anticipated. Alibaba’s Qwen family has overtaken Meta’s Llama in cumulative Hugging Face downloads, and by mid-2025 Qwen-derived models accounted for over 40% of new language model uploads on the platform. DeepSeek R1 briefly narrowed the frontier gap to as little as four months. GLM-5, Kimi K2.5, and MiniMax M2.5, all released as open weights under permissive licenses in early 2026, are frontier-adjacent at a fraction of the inference cost. Despite hardware constraints that leave Chinese labs working around export controls on cutting-edge chips, they have executed a remarkably effective strategy: flood the world with competitive open-weight models and let the ecosystem do the rest. Western open-source, by contrast, is thin. AI2 ships OLMo3, Hugging Face has SmolLM3, and Mistral has its lineup. Beyond that, the list of Western labs releasing serious open-weight foundation models is short. This is a strange asymmetry: Western labs hold a nearly tenfold advantage in compute infrastructure (U.S. hyperscaler capex alone exceeded $400 billion in 2025, versus roughly $57 billion across China’s major platforms), yet produce far fewer open-weight models. China is not winning open-source because of a technical edge in hardware. They are winning because almost nobody in the West is trying. That matters because open-weight models are not just a convenience; they are infrastructure. Researchers, startups, and institutions that cannot afford per-token API pricing or cannot send sensitive data to a third-party endpoint depend on models they can run locally. If the only competitive options come from Chinese labs, that shapes who builds what, on whose stack, and on whose terms. Arcee AI is one of the Western labs taking this challenge seriously, and the name of their model family gives away exactly how: Trinity is a three-way collaboration. Arcee AI led the model architecture and training. Prime Intellect contributed their distributed training infrastructure, a platform that lets researchers train large models across decentralised GPU clusters without needing a hyperscaler budget. Datalogy curated the training data. Together they released a full family: Trinity Nano for edge and on-device deployment, Trinity Mini as the practical mid-range option, and Trinity Large at the frontier scale, competitive with GLM-4.5 base-to-base. All three are fully open-weight under a permissive license. We use Trinity Mini for this study because its sparse MoE keeps inference cost low even when generating thousands of rollouts per step, which is exactly what RLVR post-training demands. The open-weight advantage is not just about what a model scores at release; it is about what you can build on top of it. Targeted RLVR post-training can unlock domain-specific capabilities that general benchmarks do not capture, and that is where open-source models have real room to close the gap. The question we set out to answer is simple: Can domain-specific RLVR post-training turn Trinity Mini into a meaningfully better model for a real workload? The task we chose is biomedical relation extraction. At Loka, healthcare and life sciences projects make up a significant part of our client work, which is part of why this domain appealed to us. Drug discovery, clinical decision support, and pharmacovigilance all depend on extracting structured knowledge from unstructured text. PubMed indexes over 36 million citations, and the relationships buried in those abstracts (which drug inhibits which protein, which compound is a substrate for which enzyme) are the raw material for computational pharmacology. DrugProt (BioCreative VII) is a benchmark for exactly this: 13 types of drug-protein interactions, annotated on real PubMed abstracts. The method is Reinforcement Learning from Verifiable Rewards (RLVR): rather than training a separate reward model, the environment provides a ground-truth accuracy signal directly (correct label = 1, wrong = 0). GRPO (Group Relative Policy Optimization) makes this tractable by estimating policy gradients from groups of sampled completions, eliminating the critic network required by PPO and substantially reducing memory overhead. DeepSeek R1 then demonstrated at scale that RLVR alone, with no supervised chain-of-thought, can teach models to reason step by step. We apply the same idea to biomedical relation classification. Because GRPO generates many rollouts per training step (up to 1,024 completions in our experiments), the dominant cost is inference, not gradient computation. Full post-training a 26B parameter MoE under these conditions is prohibitively expensive: every parameter update must be applied after each batch of thousands of sampled completions, requiring enormous GPU memory and wall-clock time. We therefore use LoRA (Low-Rank Adaptation), which inserts small trainable rank decomposition matrices into the frozen base model, reducing trainable parameters by several orders of magnitude while keeping the base weights intact. Crucially, this is not a performance compromise: LoRA Without Regret shows that LoRA fully matches full post-training in policy gradient RLVR even at rank 1, because RLVR absorbs far less information per update than supervised learning. We run the full pipeline on Prime Intellect’s training infrastructure. We ran 12 experiments sweeping LoRA alpha, learning rate, batch size, generation budget, temperature, and rollout count. The question is deliberately practical: Which hyperparameters actually move the needle when you RLVR-tune an open-weight sparse MoE for biomedical relation extraction? The task & the model DrugProt: the RL environment DrugProt (BioCreative VII Track 1) is a corpus of PubMed abstracts annotated with 13 types of drug-protein interactions: INHIBITOR, SUBSTRATE, INDIRECT-DOWNREGULATOR, INDIRECT-UPREGULATOR, AGONIST, ANTAGONIST, ACTIVATOR, PRODUCT-OF, and five others. Given an abstract and a specific (chemical, gene/protein) pair, the model must classify the relationship. We use the maziyar/OpenMed_DrugProt@0.3.0 environment, which frames DrugProt as a 13-way multiple choice question: each relation type maps to a letter A through M. The model sees the full PubMed abstract, the highlighted entities, and must output its answer inside \\boxed{} tags. Here is a representative example from the dataset: Example input Abstract: Na+/Ca2+ exchange inhibitors: a new class of calcium regulators. The Na(+)/Ca(2+) exchanger (NCX) is a bidirectional transporter that normally extrudes Ca(2+) from the cell (forward mode), but also brings Ca(2+) into the cell (reverse mode) under special conditions such as intracellular Na(+) accumulation or membrane depolarization. There are three mammalian NCX isoforms: NCX1 is widely expressed in the heart, kidney, brain, blood vessels, and so on; whereas the expression of NCX2 and NCX3 is limited mainly to the brain and skeletal muscle. […] Drug/Chemical: Ca(2+) Gene/Protein: Na(+)/Ca(2+) exchanger Question: What is the relation type between Ca(2+) and Na(+)/Ca(2+) exchanger? Options: A. INDIRECT-DOWNREGULATOR B. INDIRECT-UPREGULATOR C. DIRECT-REGULATOR D. ACTIVATOR E. INHIBITOR F. AGONIST G. AGONIST-ACTIVATOR H. AGONIST-INHIBITOR I. ANTAGONIST J. PRODUCT-OF K. SUBSTRATE L. SUBSTRATE_PRODUCT-OF M. PART-OF Correct answer: K — SUBSTRATE (Ca(2+) is transported by the NCX, making it a substrate of the exchanger) Reward structure The environment defines a composite reward with three components: reward = 0.70 * accuracy + 0.20 * reasoning + 0.10 * format Accuracy (weight: 0.70): Binary, 1.0 if the boxed letter matches the gold label, 0.0 otherwise. This is the signal that matters. Reasoning (weight: 0.20): Heuristic score composed of three components: (1) length of the <think></think> block (0.1–0.4 depending on whether it exceeds 100 / 200 / 400 characters), (2) keyword density from a fixed list of 37 biomedical terms — agonist, inhibit, substrate, kinase, transporter, etc. — capped at 0.3, and (3) presence of the words “chemical” or “drug” (+0.1) and “protein” or “gene” (+0.1). Crucially, this reward is task-agnostic: it does not check whether the reasoning is correct or relevant to the specific entity pair. A model writing generic biomedical prose scores well regardless of whether its analysis of this relationship is right. This explains why reasoning reward improves similarly across all alpha values — it measures format and vocabulary, not depth of analysis. It also makes the reasoning component the noisiest of the three signals. Format (weight: 0.10): Binary, 1.0 if the output contains a valid \\boxed{A..M}, 0.0 otherwise. This structure is intentional: accuracy dominates, but the shaping signals from reasoning and format help bootstrap learning in early steps when the model has not yet learned the task. A practical consequence: total reward can improve early via format compliance and longer reasoning traces before accuracy actually moves. The model: Arcee Trinity Mini Trinity Mini is a sparse mixture-of-experts (MoE) model from Arcee AI: 26B total parameters, 3B active per forward pass. Sparse MoE is a natural fit for RLVR post-training because GRPO is dominated by forward passes. With batch_size=128 and rollouts_per_example=8, each training step generates 1,024 sampled completions. A model that is cheap at inference time but has high total capacity is exactly what you want. We adapt Trinity Mini using LoRA (Low-Rank Adaptation). LoRA freezes the base model and learns two low-rank matrices A and B per targeted layer (rank r), scaled by α. ΔW = (α/r) · BA The key hyperparameter we ablate is α: it controls how much the LoRA updates influence the model’s outputs independently of the number of trainable parameters. Higher α means stronger adaptation per step; lower α is more conservative. Note that α acts as a multiplier on the effective learning rate for the adapter layers; raising α and raising the global LR have similar effects on training dynamics. Important Distinction: We sweep LoRA alpha (the scaling factor), not LoRA rank. Alpha controls update magnitude without changing the number of trainable parameters. This makes it a pure “how aggressively do we adapt?” knob. Experiments & results Our ablation strategy is sequential. We sweep one variable at a time, lock in the best setting, and move to the next. This gives us a clear cause-and-effect story at the cost of not exploring the full combinatorial space. For each comparison we show learning curves (accuracy reward over training steps) with a 5-step moving average for readability, plus snapshot bar charts at key steps. One parameter we did not sweep is LoRA rank. Prime Intellect’s training infrastructure fixes rank at r=16, applied across all projection layers (q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj, and expert layers). We are comfortable leaving rank fixed because LoRA Without Regret establishes that policy gradient algorithms absorb roughly one bit of information per episode independent of model size, meaning a rank-1 LoRA (3M parameters for an 8B model) vastly exceeds the capacity needed for typical RL training sets. Rank is therefore not the binding constraint in our setting. The same work also demonstrates that applying LoRA to all layers (attention and MLPs) substantially outperforms attention-only LoRA — a finding consistent with our all-layer setup. On Trinity Mini this is especially relevant: the model’s G1 gated attention uses a dedicated gate_proj weight matrix in every attention layer that is both a LoRA target and architecturally load-bearing (it controls attention output magnitudes via a learned sigmoid gate), so leaving it frozen would mean skipping a significant set of parameters. All 12 experiments (click to expand) Unless noted otherwise, defaults are: batch_size=128, rollouts_per_example=8, temperature=0.7, max_tokens=512. Run α LR Batch Rollouts Max tokens Temp w1-alpha16-baseline 16 1e-6 128 8 512 0.7 w1-alpha32-baseline 32 1e-6 128 8 512 0.7 w1-alpha64-baseline 64 1e-6 128 8 512 0.7 w1-alpha128-baseline 128 1e-6 128 8 512 0.7 w1-alpha64-lr1e-5 64 1e-5 128 8 512 0.7 w1-alpha64-lr5e-6 64 5e-6 128 8 512 0.7 w1-alpha64-lr3e-6 64 3e-6 128 8 512 0.7 w1-alpha64-lr3e-6-b64-r16 64 3e-6 64 16 512 0.7 w1-alpha64-lr3e-6-1024 64 3e-6 128 8 1024 0.7 w1-alpha64-lr3e-6-2048 64 3e-6 128 8 2048 0.7 w2-2048-t0.15 64 3e-6 128 8 2048 0.15 w2-2048-r4 64 3e-6 128 4 2048 0.7 1) LoRA alpha ablation (16 / 32 / 64 / 128) We started with the most fundamental LoRA knob: the alpha scaling factor. Keeping everything else fixed (LR 1e-6, batch 128, rollouts 8, max_tokens 512), we trained four runs at α=16, α=32, α=64, and α=128. The general picture is clear: up to α=64, higher alpha produces both faster learning and higher accuracy. α=64 is the best overall setting, reaching ~0.75 accuracy reward at step 100 versus ~0.70 for α=32 and ~0.41 for α=16. Figure 1. LoRA alpha sweep (steps 1–100). Accuracy reward vs training step for α=16, 32, 64, and 128, all at LR 1e-6. α=128 is terminated at step 70 due to eval degradation. The exception is α=128. On the training metric it looks competitive, even outperforming α=64 at matching steps, but the held-out eval tells the opposite story. Figure 2 makes this impossible to miss: α=128 started with the highest eval score of any run and ended with the lowest, dropping steadily from step 0. The model was terminated at step 70. Training reward is healthy because aggressive updates adapt quickly to each batch; the eval exposes that generalization is collapsing at the same rate. Figure 2. Held-out eval score (avg@2) over training steps for each LoRA alpha. α=64 climbs steadily; α=128 declines from the very first checkpoint and is terminated at step 70. α=16 and α=32 stay roughly flat. Figure 3. Reasoning reward by LoRA alpha (steps 1–100). Unlike accuracy, reasoning reward improves similarly across all alphas. The model learns to produce structured thinking traces regardless of update magnitude. Reasoning reward tells a different story from accuracy. While α=64 clearly outperforms α=16 on accuracy, all four alphas produce similarly improving reasoning traces over time. The model learns to write structured pharmacological analysis regardless of how aggressively the LoRA layers are being updated. This suggests that reasoning quality, as measured by our heuristic, is more about training duration than update magnitude, a contrast worth keeping in mind when interpreting the max tokens results below. Alpha is not a dial where higher is always better. The LoRA scaling factor is α / rank, so a higher alpha directly amplifies the magnitude of every adapter update — effectively inflating the learning rate for the LoRA layers independently of the global LR. The consequences are threefold. First, the adapted weights receive disproportionately large updates, producing loss spikes and erratic training dynamics. Second, the model overfits aggressively to each batch: training accuracy climbs fast, but the pretrained feature space gets warped at the same rate, eroding the general capabilities inherited from pretraining. Third, and most visible in Figure 3, generalization collapses on held-out data while the training signal stays deceptively healthy. The key practical insight is that alpha and learning rate are not independent knobs: raising alpha has the same effect as raising the LR for the adapter layers. If instability appears, lowering either will help. α=64 sat in the stable, productive middle of our sweep, and we locked it in for all subsequent experiments. 2) Learning rate sweep at α=64 (1e-5 / 1e-6 / 3e-6 / 5e-6) With alpha fixed at 64, we swept the learning rate across four values: 1e-6 (our alpha baseline), 3e-6, 5e-6, and the aggressive 1e-5. This is where the story gets interesting. The three moderate learning rates (1e-6, 3e-6, 5e-6) all produced healthy learning curves with different speed/stability tradeoffs. 5e-6 learned fastest early on. 3e-6 was steady and reliable. 1e-6 was conservative but safe. 1e-5, however, was catastrophic. The run started promisingly; it actually climbed faster than the others in the first 20 steps. But by step 50 the reward began oscillating wildly, and by step 77 accuracy collapsed to zero. The run was terminated at step 82 with no recovery in sight. This is not a gradual degradation; it is a cliff. The model essentially forgot how to produce valid outputs. Figure 4. Learning rate sweep at α=64 (steps 1–100). The 1e-5 run (red) climbs early but collapses catastrophically around step 50–77. The remaining three learning rates show the classic speed-vs-stability tradeoff. Figure 5. Accuracy reward at step 82 vs learning rate (log scale). The cliff between 5e-6 and 1e-5 is dramatic: a 2× increase in LR produces a collapse from ~0.83 to near zero. Why 1e-5 collapses and what LoRA Without Regret says about it: LoRA Without Regret finds that the optimal LoRA learning rate is roughly 10× the optimal full post-training LR across a wide range of models and tasks (15× for short runs of ~100 steps). On first reading, this suggests we should be running at 1e-5 or higher. So why did 1e-5 destroy our model? The key is the interaction between LR and α. LoRA’s weight update is ΔW = (α/r)·BA. At α=64, r=16 the scaling factor is 4; at the α=32 used in LoRA Without Regret it is 2. Our effective per-step update magnitude at LR 1e-5 is therefore equivalent to running at LR 2e-5 under their parameterization, already at the edge of their reported stability range. Additionally, LoRA Without Regret’s experiments use dense Llama-class architectures; sparse MoE models route tokens through only a subset of experts per forward pass, which can amplify gradient variance and narrow the stable LR window further. The collapse at 1e-5 is therefore consistent with the theory once the α-scaling and MoE architecture are both accounted for: we were above the stability boundary for this specific combination of adapter scaling and model class. Two Trinity Mini-specific factors are worth flagging. First, Trinity Mini was pre-trained with μP input scaling (embedding outputs multiplied by √2048 ≈ 45 before each transformer layer), a different pre-training regime from the standard architectures used in LoRA Without Regret’s experiments; their empirical LR bounds were not established under equivalent conditions. Second, MoE models face a documented instability problem under GRPO specifically: top-k discrete routing causes the set of activated experts to drift between inference and training, inflating importance-sampling variance in a way that dense models do not experience. These two factors make empirical LR validation more important here than on a standard dense model. The practical takeaway: when porting the LoRA Without Regret 10× rule to a new setup, adjust for your actual α/r ratio and verify stability empirically at the high end before committing to a full run. At step 82 (the last step before 1e-5 data disappears): 5e-6 leads with 0.83 accuracy, followed by 3e-6 at 0.72, 1e-6 at 0.70, and 1e-5 at 0.00. However, 5e-6 showed signs of instability in later steps. We chose 3e-6 as the safest default that still converges quickly. 3) Batch size: 128×8 vs 64×16 Next we tested whether the same total completions per step (1,024) should come from more examples with fewer rollouts or fewer examples with more rollouts. We compared our default (batch=128, rollouts=8) against (batch=64, rollouts=16), both at α=64, LR 3e-6. Figure 6. Batch size comparison (steps 1–100). Accuracy reward for 128×8 (more examples, fewer rollouts) vs 64×16 (fewer examples, more rollouts per example). The two configurations performed comparably. At step 100, accuracy was ~0.74 for 128×8 and ~0.75 for 64×16. The key difference was cost: 64×16 generated notably longer completions on average (~222 vs ~167 tokens), meaning more inference compute per step for similar accuracy. We kept 128×8 as the default. 4) Max generation tokens (512 / 1024 / 2048) With α=64, LR 3e-6, and batch 128×8 locked in, we swept the maximum generation length. This knob changes both compute cost and the model’s behavior, as longer caps allow more elaborate reasoning traces. Figure 7. Max tokens sweep (steps 1–100). Accuracy reward for 512, 1024, and 2048 max tokens, all at α=64, LR 3e-6, batch 128×8. Figure 8. Mean composite reward at step 100 by max tokens. 2048 achieves the highest overall reward, driven by both accuracy and richer reasoning traces. Figure 9. Reasoning reward by max tokens (steps 1–100). The gap is structural and visible from step 1: 2048 tokens starts at ~0.87, 1024 at ~0.81, and 512 at ~0.62, before any learning has occurred. The reasoning heuristic rewards think blocks of 400+ characters, which a 512-token budget cannot reliably accommodate alongside the answer. The 2048 configuration stood out as the strongest overall performer, and Figure 9 makes the mechanism explicit. This is not a learned behaviour; it is a structural constraint. With 512 max tokens, the model must fit both its reasoning trace and its boxed answer into a tight budget; reliably hitting the 400+ character threshold for the reasoning reward becomes structurally difficult. With 2048 tokens, the model has room to reason from step 1, and that head-start compounds throughout training. Since reasoning carries a 0.20 weight in the composite reward, the advantage is immediate and persistent. The cost, however, is real: at step 100, mean completion length is ~167 tokens at 512, ~334 at 1024, and ~605 at 2048. That is a 3.6× increase in inference tokens per completion. We treat 2048 as the quality setting for the final ablations. 5) Final ablations: temperature and rollout budget Our final two experiments started from the best configuration found so far (α=64, LR 3e-6, batch 128, max_tokens 2048) and probed two remaining knobs: Temperature 0.15: Does lower sampling entropy improve accuracy by concentrating probability on the model’s best guesses? Rollout 4: Can we halve the rollout budget (and thus inference cost) per step without losing accuracy? Figure 10. Final ablations (steps 1–100). Accuracy reward for the 2048 baseline, the low-temperature variant (t=0.15), and the reduced-rollout variant (r=4). The rollout=4 variant matched or exceeded the baseline’s accuracy throughout training, suggesting that for this task, 4 rollouts per example provide sufficient signal for GRPO updates. This is significant because it halves inference cost per training step. The low-temperature variant (t=0.15) told a more nuanced story. It started with very high accuracy in early steps (the model’s existing knowledge, sampled deterministically, was already decent). But over the course of training, the reduced exploration appeared to limit improvement. Lower temperature means less diversity in rollouts, which means less informative gradient signal for GRPO. The output contrast: best model vs catastrophic 1e-5 To make the impact concrete, here is a side-by-side comparison of model outputs on the same DrugProt example. The best configuration produces structured pharmacological reasoning; the collapsed 1e-5 model produces incoherent output. Best model (α=64, lr=3e-6, 2048 tokens) <think> The user is asking about the relation between “Ser” (serine, an amino acid) and “GXSXG motif” (a conserved sequence motif in proteins). The options are various types of interactions. Key points from the biomedical text: Calnuc is a serine protease, and the text mentions “Ser-378 of GXSXG motif”. This indicates that serine (Ser) is part of the GXSXG motif, specifically at position 378. The GXSXG motif is a catalytic motif in serine proteases, where serine acts as the catalytic residue. The text states that calnuc has two Zn²⁺-binding sites and is inactive as a peptidase. Zn²⁺ binding negatively regulates serine protease activity by causing a conformational change. G protein α subunit also inhibits enzymatic activity. Analyzing the options: A–I are about regulation (inhibition, activation, etc.), but the relationship here is that Ser is part of the motif, not regulating it. J–M are about the chemical’s role in relation to an enzyme’s process. M is PART-OF, which fits because Ser is a component of the GXSXG motif. Other options don’t fit: J–L are about the chemical being a product, substrate, or both; A–I are about regulation. Ser here is a residue in a protein motif, not a product, substrate, or external regulator. Final answer: M. </think> The text explicitly states that Ser-378 is part of the GXSXG motif in calnuc. Serine is a component residue within the motif, making it a structural constituent rather than an external regulator or product/substrate. \\boxed{M} Collapsed model (lr=1e-5, step ~80) <think> the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the </think> \\boxed{A} Next steps Longer training runs. Our best configuration (α=64, LR 3e-6, 2048 tokens) was capped at ~100 steps and its eval curve had not flattened. Running it for 500+ steps is the clearest path to a stronger model, though diminishing returns and eval divergence both remain risks. Evaluation on the official DrugProt test set. Our held-out metric (avg@2) is computed on the training split during RLVR. A proper evaluation on the official test set would tell us whether the gains reflect genuine generalization or a more narrow adaptation to the training distribution. Trying different base models. Trinity Mini is one choice. Running the same ablation protocol on other open-weight models would reveal whether the alpha and LR sensitivities we found are MoE-specific or general properties of LoRA under RLVR. Better reward signals. The reasoning reward is heuristic (keyword matching and length thresholds). Replacing it with a learned reward model or NLI-based evaluation could change the learning dynamics substantially, especially for the reasoning component which was the noisiest signal. Conclusion The recipe works. α=64, LR 3e-6, 2048 max tokens: a 3B-active-parameter open-weight MoE that learns to reason about drug-protein interactions from reward signals alone, no labeled chain-of-thought required. The leverage is almost entirely in two numbers; everything else is secondary. If you want to use the fine-tuned model, you do not need to re-run the training. We have published the adapter weights (lokahq/Trinity-Mini-DrugProt-Think) and written a step-by-step deployment guide using the AWS SageMaker SDK v3, covering how to serve the merged model as a real-time endpoint: deployment guide. SageMaker’s managed inference handles scaling and hardware allocation; the guide walks through container selection, endpoint configuration, and a sample inference call against the DrugProt relation types. We have also started running the same RLVR+LoRA recipe on Trinity Nano (6B parameters), across both medical and general reasoning tasks. Nano is small enough to serve cheaply on a single GPU instance, which matters for inference in production use cases. We expect the same hyperparameter sensitivities to hold; we will publish a follow-up when we have results worth sharing. Acknowledgements Model: Arcee AI (with Prime Intellect and Datalogy) for releasing the Trinity family. Training: Prime Intellect for hosted training infrastructure. Environment: OpenMed for DrugProt dataset packaging. Deployment: AWS for deployment and hosting. Citation If you find this work useful, please cite: @misc{jakimovski2026drugprotrl, title = {Post-Training an Open MoE Model to Extract Drug-Protein Relations: Trinity-Mini-DrugProt-Think}, author = {Jakimovski, Bojan and Kalinovski, Petar}, year = {2026}, month = {feb}, howpublished = {Blog post}, url = {https://techblog.loka.com/trinity-drugprot/} } Further reading MIT Technology Review (2026). What's next for Chinese open-source AI. Reports Qwen overtaking Llama in Hugging Face downloads and Qwen-derived models reaching 40%+ of new language model uploads. technologyreview.com Epoch AI (2026). Chinese AI models have lagged the US frontier by 7 months on average since 2023. Analysis of the Epoch Capabilities Index showing the US-China frontier gap ranged from 4 to 14 months. epoch.ai IEEE ComSoc Technology Blog (2026). China's open source AI models to capture a larger share of 2026 global AI market. Cites Goldman Sachs and UBS data on the ~10× gap in compute infrastructure investment between U.S. hyperscalers ($400B+) and Chinese platforms (~$57B). techblog.comsoc.org Latent Space (2026). [AINews] Z.ai GLM-5: New SOTA Open Weights LLM. Covers the February 2026 releases of GLM-5 (744B) and MiniMax M2.5 (230B). latent.space Z.ai (2026). GLM-5. Official open-weights model card. huggingface.co/zai-org/GLM-5 MoonshotAI (2026). Kimi K2.5. Official model repository and technical report. github.com/MoonshotAI/Kimi-K2.5 MiniMax (2026). MiniMax-M2.5. Official open-weights model card. huggingface.co/MiniMaxAI/MiniMax-M2.5 MiniMax (2026). MiniMax M2.5: The official release announcement. minimaxi.com Schulman, J. et al. (2017). Proximal Policy Optimization Algorithms. Introduces PPO. arxiv.org/abs/1707.06347 Schulman, J. (2025). LoRA Without Regret. Thinking Machines Lab: Connectionism. DOI: 10.64434/tml.20250929. Establishes that LoRA fully matches full post-training in policy gradient RL even at rank 1. Derives an empirical LR scaling rule (optimal LoRA LR ≈ 10× full post-training LR), shows attention-only LoRA substantially underperforms all-layer LoRA, and characterizes the α/r parameterization invariance. thinkingmachines.ai/blog/lora Hu, E. J. et al. (2022). LoRA: Low-Rank Adaptation of Large Language Models. International Conference on Learning Representations (ICLR). Introduces low-rank decomposition adapters that reduce trainable parameters by up to 10,000× compared to full post-training, with no inference latency overhead. arxiv.org/abs/2106.09685 Shao, Z. et al. (2024). DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models. Introduces GRPO (Group Relative Policy Optimization), which estimates policy gradient baselines from groups of sampled completions, eliminating the critic network required by PPO and substantially reducing memory cost. arxiv.org/abs/2402.03300 DeepSeek-AI (2025). DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning. Demonstrates that RLVR alone — with no supervised chain-of-thought data — can teach models to reason step by step, achieving AIME 2024 accuracy of 71.0% (86.7% with majority voting), matching OpenAI o1. arxiv.org/abs/2501.12948 Arcee AI (2025). The Trinity Manifesto. Blog post introducing Trinity Mini and Trinity Nano, including benchmark comparisons against Qwen3-30B-A3B Thinking, OLMo3-32B, and Magistral Small. arcee.ai/blog/the-trinity-manifesto Arcee AI (2025). Trinity Large. Blog post presenting Trinity Large benchmark comparisons against GLM-4.5, GLM-4.7, DeepSeek-V3, Llama 4 Maverick, and MiniMax M2.1. arcee.ai/blog/trinity-large Team OLMo (2025). OLMo3. Allen Institute for AI. A fully open foundation model family (weights, training data, code) released by AI2 as a contribution to transparent Western open-source AI research. arxiv.org/abs/2512.13961 Mistral AI (2025). Magistral. Mistral AI. Mistral's first reasoning model family, trained with RL on top of Mistral Medium 3. Magistral Small (24B, Apache 2.0) is open-weight. arxiv.org/abs/2506.10910 Arcee AI (2026). Arcee Trinity Large Technical Report. Describes the Trinity family of sparse mixture-of-experts models, including Trinity Mini (26B total / 3B active) used in this study. arxiv.org/pdf/2602.17004 maziyar/OpenMed_DrugProt (2025). DrugProt RL environment for Prime Intellect. The verifiers environment used for all experiments in this study. app.primeintellect.ai Miranda, A. et al. (2021). Overview of DrugProt BioCreative VII Track 1: Advanced Biomedical Named Entity Recognition and Relation Extraction. BioCreative VII Workshop. Introduces the DrugProt corpus of PubMed abstracts annotated with 13 drug-protein relation types. OpenMed (2025). drugprot-parquet dataset. Parquet version of DrugProt used by the environment. huggingface.co/datasets/OpenMed/drugprot-parquet Qwen Team (2025). Qwen3 Technical Report. Alibaba Cloud. Dense and MoE models from 0.6B to 235B parameters, with unified thinking/non-thinking modes. Qwen3-30B-A3B is the MoE variant used for comparison in this study. arxiv.org/abs/2505.09388 Zhang, D. et al. (2025). Towards Stable and Effective Reinforcement Learning for Mixture-of-Experts. Identifies top-k routing drift between inference and training as the root cause of MoE instability under GRPO, and proposes RSPO to address it via router-aware importance sampling. arxiv.org/abs/2510.23027 Yang, G. et al. (2022). Tensor Programs V: Tuning Large Neural Networks via Zero-Shot Hyperparameter Transfer. NeurIPS 2022. Introduces Maximal Update Parametrization (μP), enabling hyperparameter transfer across model widths during pre-training. arxiv.org/abs/2203.03466"},{"href":"/clean-architecture-with-strategy-pattern-in-kotlin/","title":"Clean Architecture with Strategy Pattern in Kotlin","description":"When building stable and maintainable software, one of the biggest challenges developers face is that modern applications often need to support multiple versions of a feature—different algorithms or formats that can…","abstract":"When building stable and maintainable software, one of the biggest challenges developers face is that modern applications often need to support multiple versions of a feature—different algorithms or formats that can…","tags":["Android","Strategy Pattern"],"topics":[],"authors":["Stefanija Zdraveska"],"text":"Design pattern solutions solve common software problems and help deliver code that’s clean, flexible, and maintainable. When building stable and maintainable software, one of the biggest challenges developers face is that modern applications often need to support multiple versions of a feature—different algorithms or formats that can change depending on user input, configuration, or context. Overusing if or when statements to handle different behaviors can lead to fragile code. This approach might be manageable in small applications, but it often breaks down as the system grows in size and complexity. The Strategy Pattern offers a clean and powerful solution. What is the Strategy Pattern? The Strategy Pattern is a design pattern that manages different behaviors in a clean and scalable way. It works by defining a group of interchangeable algorithms, each encapsulated in its own class, and allowing the application to switch between them at runtime. Instead of using complex if-else or when statements, the Strategy Pattern delegates this responsibility to separate strategy classes that implement a common interface. This approach makes it easier to update, test, and extend behavior without modifying the core application logic. The pattern also aligns perfectly with the Open/Closed Principle (OCP), one of the key principles from the SOLID principles. The Open/Closed Principle states that software entities (like classes, modules, and functions) should be open for extension but closed for modification. By using the Strategy Pattern, new strategy classes can be added to introduce behaviors without changing the core logic. Following the Open/Closed Principle (OCP) makes the application easier to maintain and grow. Why use the Strategy Pattern? Clean code: Replace complex conditionals with polymorphism. Runtime Flexibility: Change behavior dynamically without touching the core class. Open/Closed Principle (OCP): Add new behaviors without modifying existing code. Testability and Reusability: Strategies are independent and easily testable. Real-World Example: Image Compression Strategies Many applications let users upload images. Different image types need different compression formats, including Photos: JPEG for smaller size and faster uploads Logos/icons: PNG to keep transparency without quality loss Web-optimized images: WebP, for better compression on the web Using hard-coded logic like this quickly becomes messy and hard to maintain: if (type == \"jpg\") { compressAsJpeg(image) } else if (type == \"png\") { compressAsPng(image) } else { compressAsWebP(image) } Refactoring with the Strategy Pattern Let’s use the Strategy Pattern to clean this up. 1. Define the Strategy Interface The first step in implementing the Strategy Pattern is to create a common interface that all strategy classes will follow. interface ImageCompressor { fun compress(imageData: ByteArray): ByteArray } 2. Implement Concrete Compression Strategies Create separate classes for each compression method, each following the common interface. Each class encapsulates a specific compression algorithm, allowing new formats to be introduced without modifying the existing logic. class JpegCompressor : ImageCompressor { override fun compress(imageData: ByteArray): ByteArray { println(\"Compressing image using JPEG format...\") return imageData } } class PngCompressor : ImageCompressor { override fun compress(imageData: ByteArray): ByteArray { println(\"Compressing image using PNG format...\") return imageData } } class WebPCompressor : ImageCompressor { override fun compress(imageData: ByteArray): ByteArray { println(\"Compressing image using WebP format...\") return imageData } } 3. Create the Context Class // Define image types using an enum for type safety enum class ImageType { JPG, PNG, WEB } class ImageCompressionManager( private val strategies: Map<ImageType, ImageCompressor> ) { fun compressImage(type: ImageType, imageData: ByteArray): ByteArray { val compressor = strategies[type] ?: error(\"No compression strategy registered for type: $type\") return compressor.compress(imageData) } } Using the Strategy Pattern in Practice fun main() { val rawImageData = ByteArray(1024) val compressionStrategies = mapOf( ImageType.JPG to JpegCompressor(), ImageType.PNG to PngCompressor(), ImageType.WEB to WebPCompressor() ) val compressionManager = ImageCompressionManager(compressionStrategies) compressionManager.compressImage(ImageType.JPG, rawImageData) compressionManager.compressImage(ImageType.PNG, rawImageData) compressionManager.compressImage(ImageType.WEB, rawImageData) } The Strategy Pattern isn’t just a theoretical design concept; it’s a practical tool for writing elegant, maintainable, and scalable code. Whether applied to image compression, payment processing, or AI model selection, it provides a clear and consistent way to handle variation and complexity. Embracing design patterns like Strategy empowers the development of flexible, clean, and scalable Kotlin applications, transforming complexity into clarity and future-proofing the code."},{"href":"/building-rag-systems-on-aws-lessons-from-serverless-and-ec2-benchmarks/","title":"Building RAG Systems on AWS: Lessons from Serverless and EC2 Benchmarks","subtitle":"A practical benchmark of RAG ingestion and search performance across AWS Lambda and EC2","description":"A practical benchmark of RAG ingestion and search performance across AWS Lambda and EC2","abstract":"A practical comparison of RAG ingestion and retrieval architectures using in-memory vector stores across AWS Lambda, EC2, and local environments.","tags":["AWS","RAG","Vector Database","Benchmarking","Serverless"],"topics":["inference","benchmarks"],"authors":["Romulo Pagnozzi","Crhistian Cardona"],"text":"This blog post explores the evolving landscape of Retrieval-Augmented Generation (RAG) systems through the lens of server-based and serverless, AWS-native architectures, with a particular focus on in-memory vector databases running on AWS Lambda, classical EC2 instances, and the emergence of Amazon S3 Vectors as a new paradigm for scalable, cost-efficient vector storage and retrieval. We begin by framing the rise of Generative AI (GenAI) and the continued relevance of RAG for overcoming context window, cost, and latency constraints in modern Large Language Models (LLMs). As semantic retrieval becomes a core building block of GenAI applications, the choice of vector database is increasingly critical — especially under real-world constraints around privacy, scalability, and cost efficiency. To guide these architectural decisions, we introduce a modular and extensible benchmarking framework that evaluates vector databases under realistic ingestion and inference workflows — both locally and on AWS EC2, with selected experiments running on AWS Lambda. The framework focuses on production-oriented metrics, including memory consumption, latency, cold-start overhead, and storage footprint. A central theme of the post is the evolution of Amazon S3 Vectors — from its public preview launch on July 15 to its global availability announced at AWS re:Invent in December 2025. We analyze how S3 Vectors introduces a fundamentally different, object-storage-native approach to vector search, enabling durable, scalable, and low-operations RAG architectures that align naturally with serverless execution models. We also examine supported deployment patterns, including ephemeral in-memory vector stores with S3-based persistence, and compare custom RAG pipelines against managed alternatives such as AWS Bedrock Converse, highlighting trade-offs in flexibility, cost, and control. To ground the analysis in practical relevance, the post presents a business-oriented use-case matrix that maps real-world RAG applications to their performance, security, and compliance requirements. Finally, we introduce the vector technologies included in the benchmark — Chroma, LanceDB, Milvus Lite, Qdrant, and Amazon S3 Vectors — and outline future plans to expand coverage to widely used libraries such as Faiss, Annoy, and Redis Vector, further enabling data-driven decisions for teams building GenAI systems on AWS. TL;DR — Key Takeaways Compute dominates RAG performance. Embedding generation and LLM inference accounts for most latency and cost; vector storage and retrieval add bounded, predictable overhead across both serverless and EC2 environments. Serverless RAG is production-ready. Ephemeral, in-memory vector stores running on AWS Lambda can deliver reliable, low-latency ingestion and search, making them well suited for event-driven and elastic workloads with minimal operational burden. Architecture matters more than the database. There is no universally “best” vector database — outcomes depend on execution context and workload patterns. AWS-native, object-store-backed designs (such as S3-based persistence) enable scalable, low-ops architectures that are especially compelling for cost-sensitive and privacy-constrained systems. RAG Still Matters Nowadays, generative AI (GenAI) has become one of the most exciting and disruptive areas in the technology landscape. Far beyond simple automation, GenAI is unlocking new forms of reasoning, decision-making, and creativity — largely enabled by breakthroughs in Large Language Models (LLMs) like GPT-5, Claude 4.5, DeepSeek among others. These models are capable of generating high-quality human-like text, answering complex questions, and synthesizing insights from large corpora of data. In the early stages of LLM development, however, one key limitation was the restricted context window — typically a few hundred or thousand tokens. This meant that only a small portion of information could be considered at a time, making it challenging to reference long documents or support complex multi-turn conversations. To work around this, a new architectural pattern emerged: Retrieval-Augmented Generation (RAG). RAG systems address the context limitation by retrieving relevant information from an external knowledge base and injecting that information directly into the prompt of the LLM at runtime. This allows models to access dynamic, task-specific, and up-to-date information without retraining. Crucially, retrieval is based on semantic similarity rather than keyword search, enabling much more intelligent and flexible lookups. As RAG gained popularity, a range of implementation strategies evolved. One core component of RAG is the chunking strategy, which defines how input documents are broken into smaller segments before indexing. Chunking is important because too-large chunks may dilute relevance, while too-small chunks may lack meaningful context. Some common strategies include: Fixed-size chunking, where text is split into equal-length character or token blocks. Recursive chunking, which preserves semantic units (like paragraphs or sentences) while trying to meet a target size. Semantic chunking, which uses NLP models to split text at natural topic boundaries. Another critical element is the embedding system, which converts text chunks into high-dimensional vectors that can be compared based on cosine or dot-product similarity. These embeddings act as a numeric “fingerprint” of the content. Common embedding providers include: OpenAI embeddings (text-embedding-3-small and others) Amazon Bedrock (e.g., Titan Embeddings) Cohere and HuggingFace models Sentence-transformers, for open-source options with multi-lingual support Over time, a wide variety of RAG architectures have emerged, each addressing different retrieval and reasoning needs: Standard RAG uses simple retrieval with chunk injection into the prompt. Graph RAG represents documents or concepts as nodes and edges, allowing for multi-hop or relationship-aware retrieval. Multi-hop RAG retrieves across several linked documents before synthesizing an answer. Agentic RAG combines retrieval with reasoning agents that perform multi-step planning, filtering, and synthesis. Even though today’s LLMs can process millions of tokens in a single context window, RAG remains highly relevant. Why? Because large context windows come at a significant cost in latency and price, and are often wasteful for focused use cases. RAG offers a more scalable and cost-efficient approach, especially for applications like document search, chat over private data, or API response augmentation. A Spectrum of Vector Database Architectures In this post, we benchmark and compare five vector database solutions: Chroma, LanceDB, Milvus Lite, Qdrant, and Amazon S3 Vectors. These were selected based on their relevance to RAG (Retrieval-Augmented Generation) applications, especially in serverless and cost-efficient architectures. Each tool represents a different philosophy of vector database design — from lightweight in-memory libraries to cloud-native, fully managed solutions. Before diving into the benchmarks, let’s briefly introduce each system and its typical use case. See Table 1 for a high-level feature comparison. Embedded content Table 1: Key features of In-Memory Vector Databases Evaluated in this Benchmark Chroma Chroma is an open-source, lightweight vector database purpose-built for LLM-native workflows. It was designed with simplicity in mind — offering easy-to-use Python APIs, tight integration with popular embedding providers, and automatic metadata handling. History: Launched in 2023 with the rise of LangChain and RAG tooling, Chroma quickly became popular in the open-source community for prototyping LLM applications. Architecture: In-memory by default, but can persist indexes to local disk (SQLite-based). Use Case: Ideal for small-scale LLM applications, fast prototyping, and serverless environments (like AWS Lambda) with fast load times. LanceDB LanceDB is a vector database built on top of the Lance columnar data format, which itself was designed by contributors to the Apache Arrow ecosystem. It combines the efficiency of memory-mapped file access with the structure of SQL-style queries. History: Created by the team at eto.ai (formerly part of the Apache Arrow project) to enable efficient vector analytics over large datasets. Architecture: Uses disk-based, columnar storage with optional memory mapping for acceleration. Compatible with S3 and DuckDB. Use Case: Best for analytics-heavy or hybrid workflows involving both structured and unstructured data, or when vectors need to be accessed from object storage in a scalable way. Milvus Lite Milvus Lite is a minimal version of the full Milvus vector database, designed for local or in-memory vector search. Under the hood, it uses Faiss for indexing and search. History: Released by Zilliz, the creators of Milvus, to support developers who needed Milvus’ speed and indexing capabilities without the overhead of a full server. Architecture: Runs in-memory, no persistence unless manually implemented; very lightweight and simple to deploy. Use Case: Suitable for quick demos, testing, and small-scale applications, especially when you need Faiss-level speed in a self-contained script or notebook. Qdrant Qdrant is a full-featured, production-grade vector database written in Rust. It offers robust performance, filtering, metadata handling, and strong API support (REST, gRPC, and SDKs in multiple languages). History: Developed by the Qdrant team in 2021, with a focus on being developer-friendly and high-performance, it quickly gained traction in open-source and enterprise settings. Architecture: Uses RocksDB for persistence and supports several index types like HNSW and PQ. Use Case: Ideal for large-scale, production vector search, multi-tenant applications, or when tight control over filtering and metadata is needed. Amazon S3 Vectors Amazon S3 Vectors is a new cloud-native vector store built directly into Amazon S3. It allows users to store, index, and search vector embeddings without managing any infrastructure or dedicated database engines. Figure 1: S3 Vector architecture. Source: Amazon blog History: Announced in July 2025 at the AWS Summit New York as a public preview, this service represents Amazon’s push toward serverless, cost-efficient vector search at scale. Its general availability was later announced at AWS re:Invent 2025, marking a major milestone in AWS’s vector-native offerings. Architecture: Fully managed; vectors are stored in S3 and accessed via dedicated vector APIs. Ideal for infrequent but scalable queries over large corpora. Use Case: Suited for cold storage retrieval, long-term embedding storage, and RAG applications where storage cost (overall 90% less) and durability matter more than ultra-low latency. General Use Case The goal of this study is to evaluate selected in-memory vector databases in the context of a realistic and modern use case — one where data privacy, security, and cost-efficiency are top priorities. In particular, we are focused on a serverless implementation that avoids persistent infrastructure, reduces overhead, and enables low-cost, on-demand retrieval of vector data for AI-enhanced applications. This setup is especially relevant in enterprise environments where sensitive data must be processed securely, such as internal document search, legal review, healthcare assistance, or customer support. In these scenarios, embedding and storing data in memory — rather than in centralized long-lived services — can reduce the attack surface, ensure per-session isolation, and improve control over lifecycle management. To help ground the benchmarking in practical relevance, we’ve defined a series of business-oriented use cases where these tools could be applied. Each use case highlights not only the application characteristics but also the related security considerations that influence vector DB selection. Embedded content Table 2: Business use cases This catalog of use cases shows the diversity of scenarios where in-memory vector search with optional persistence is not only viable but often preferable. These use cases also shape our benchmarking criteria: they demand fast startup, isolated memory usage, minimal persistence, and strong alignment with security principles — all within a serverless or lightweight computer architecture. In the next section, we will describe the architecture for the benchmarking experiment and define the metrics used to evaluate each tool. Structure of the Benchmarking Framework The benchmarking framework we’ve developed is designed to be modular, extensible, and vendor-agnostic — capable of testing a wide variety of vector databases regardless of their architecture or underlying technology. Whether you’re working with an in-memory library like Chroma or a fully managed service like Amazon S3 Vectors, the tool adapts to support your environment and constraints. Currently, our primary focus is on serverless architectures, particularly AWS Lambda, where we evaluate: In-memory vector libraries Disk-based vector stores Cloud object store-based solutions This extensible design allows us to benchmark the full RAG (Retrieval-Augmented Generation) pipeline — both locally and in AWS Lambda environments — and to simulate production-ready execution patterns. Figure 2: AWS reference architecture for AWS Lambda/EC2/ECS applications. Our current emphasis is on serverless architectures, particularly AWS Lambda, where speed, cost, and security are critical. In parallel, we run the same experiments on EC2 instances (and extensible to ECS), since some in-memory vector databases cannot be executed reliably within Lambda’s constraints. Within this setup, we evaluate three classes of storage approaches — in-memory vector libraries, disk-based vector stores, and cloud object storage solutions — to understand how each behaves under ephemeral execution models. This methodology enables us to benchmark the entire RAG pipeline in both local and AWS Lambda environments, closely simulating production-ready execution patterns. Figure 2 illustrates the serverless architecture, with Lambda functions conceptually replaceable by EC2 or ECS components for non-serverless deployments. The framework follows three core design principles. First, it uses reusable workflows with a plugin‑like structure, making it easy to swap out embedding models, chunking strategies, and vector databases. Second, it applies structured benchmarking, running systematic experiments across configurations to provide reproducible data for comparison. Finally, it is aligned with production use, so the same pipelines tested here can be deployed directly into real systems without major rework. Together, these principles reduce risk, speed up delivery, and give decision‑makers confidence based on real metrics rather than assumptions. To capture realistic performance, the benchmarking breaks the RAG lifecycle into two main workflows: document upload and search/inference. The document upload workflow measures how quickly an uploaded file can be parsed, chunked, embedded, and stored. Documents are first parsed (e.g., from PDFs), then split into semantically meaningful chunks, transformed into embeddings, inserted into an in‑memory vector store, and finally persisted to a backend such as S3 or EFS. Metrics such as processing time, RAM and CPU usage, and storage size are collected to identify bottlenecks. The goal is to optimize how quickly and cost‑effectively documents can be prepared for search. The search and inference workflow measures how fast and accurately the system can respond to a user query. In this phase, the relevant vector index is loaded from storage into memory, the user’s query is embedded, and a similarity search retrieves the most relevant chunks. These chunks are then formatted into a prompt and sent to the LLM for answer generation. Here, we track metrics like vector index load time, search latency, LLM response latency, and total inference cost to ensure the system can deliver high‑quality results at scale. In some scenarios, we also test bypassing retrieval entirely and submitting the full document directly to the LLM to compare performance with and without RAG. Under the hood, the framework supports a wide range of configuration parameters. It can run inside Lambda or containers, handle different document sizes and types, and work with multiple LLM providers such as Titan, OpenAI, or Cohere. Storage backends are pluggable, supported by design S3, EFS, and EBS. This flexibility makes it possible to evaluate many realistic deployment patterns without rewriting the benchmarking logic. While ChromaDB and Qdrant support true in-memory operation suitable for AWS Lambda’s serverless environment, both Milvus Lite and LanceDB have architectural limitations that prevented them from running in Lambda’s constrained runtime. Consequently, we deployed these benchmarks on a local machine to accommodate their requirements. However, the experimental conditions remained consistent across all vector databases: each system processed the same corpus of documents, fetched data from S3, persisted the constructed vector database back to S3 for storage, and subsequently loaded the persisted vectors from S3 to perform inference queries. This approach ensured that despite the different hosting environments, all databases underwent identical data ingestion, persistence, and retrieval workflows, maintaining the validity of performance comparisons. A key feature of the architecture is its security‑oriented design. Rather than relying on a centralized, long‑lived vector database, the system creates an ephemeral, in‑memory store on the fly for each Lambda invocation, scoped to a single document or user session. This approach minimizes the attack surface, gives full control over data lifecycle and deletion, and avoids persisting sensitive information unless explicitly required — a major advantage for regulated environments such as healthcare or legal services. Finally, we collect detailed performance metrics tailored to both EC2 instances and Lambda’s execution model. These include memory and CPU requirements to estimate cost per execution, I/O performance for reading and writing index files from S3 or EFS, startup overhead when loading vector indexes into memory, and end-to-end latency from request to response. We also measure cold-start sensitivity to assess whether performance degrades significantly on first invocation. The central question driving this benchmarking effort is straightforward: can an ephemeral, serverless, in-memory vector store architecture deliver the performance, security, and scalability required for real-world RAG applications? And how does it compare with equivalent EC2 and ECS-based implementations using the same in-memory databases? By systematically evaluating a diverse set of vector database technologies under identical conditions, this framework is designed to produce the data-driven insights needed to make these architectural decisions with confidence. For more details, you can check the github repository: https://github.com/LokaHQ/vector-db-benchmark/ Inside the Benchmarking Engine To rigorously evaluate vector database performance for Retrieval-Augmented Generation (RAG) workflows, we built a modular benchmarking engine that mimics a production-grade pipeline — but with hooks for observability, customization, and post-analysis. The entire system is designed using well-known software patterns like Pipeline, Strategy, Factory, and Adapter, which make it both extensible and maintainable. This modular architecture lets us plug in any combination of embedding models, vector databases, chunking strategies, and storage backends — without rewriting core logic. Let’s walk through the main components of this engine. Each run tests combinations of documents, embedding models, and vector DBs. Performance is tracked at every stage: text, text_extraction_time = time_operation(\"Extracting text\", lambda: extract_text_from_doc(...)) Pluggable Vector Databases Each vector DB (Chroma, Qdrant, LanceDB, etc.) implements a shared interface. A factory dynamically loads the right backend: db_class = get_database_provider(job.vector_db_name) This allows clean benchmarking across memory, disk, and cloud-native DBs like Amazon S3 Vector. Embedding Providers Local models (e.g., MiniLM) and cloud-based (e.g., Bedrock Titan) share the same logic: embedder = create_embedder(model_name) embeddings = embedder.embed_texts(texts) Async support ensures scalability even with large batches and high concurrency. S3-Based Persistence To support Lambda, the system stores vector DBs as tarballs in S3 — downloaded and loaded into memory per request: aws_client.upload_directory_as_tar(local_dir, bucket, key) This enables stateless, secure, serverless RAG workflows. Structured Metrics Benchmark results (latency, RAM, CPU) are tracked in Pydantic models and visualized via pandas: df.groupby([\"vector_db_type\"])[[\"total_time\"]].mean() This helps compare cost-performance trade-offs between tools. Alternatives to RAG Systems in AWS When building GenAI-powered applications on AWS, one of the early design decisions involves choosing how to handle document retrieval and context injection. Do you build a custom Retrieval-Augmented Generation (RAG) pipeline from scratch, or leverage AWS Bedrock’s more streamlined Converse API? Each option has its strengths — and understanding the trade-offs is key to choosing the right fit for your use case. The Converse API offers a simple, powerful interface for conversational applications. It abstracts away many of the complexities involved in traditional RAG systems — such as document chunking, vector embedding, and similarity search — allowing developers to upload documents and ask questions about them in a single API call. For teams looking to move fast and avoid managing infrastructure, this approach is very appealing. However, there are some important limitations. At the time of writing, the Converse API allows a maximum of five documents per conversation, with each document capped at 4.5 MB. Once the limit is reached, your application must either block further uploads or replace existing files. These constraints can work well for many scenarios, but they may be restrictive in use cases involving large documents or dynamic file uploads across a session. Pricing is another important consideration. Bedrock pricing is based on input and output tokens — and when using documents with the Converse function, their contents are included in the input token count. A standard prompt may use only a few hundred tokens, but a single 4.5 MB document can contribute 100,000 to 200,000 tokens, depending on its content. That means a session with two documents and a prompt could easily exceed 200,000 tokens per request. At current pricing, this could result in a cost of roughly $0.30–$0.60 per interaction — reasonable for high-value use cases, but something to monitor in high-volume or consumer-facing applications. For these reasons, many teams turn to custom RAG implementations when they need more flexibility or control. A custom pipeline enables selective chunking of documents, caching of embeddings, fine-tuned vector searches, and tailored cost optimizations. You can also support much larger files and document collections than Converse currently allows. Results Our benchmarking follows the end-to-end lifecycle of a Retrieval-Augmented Generation (RAG) system, covering ingestion, search, and consolidated performance analysis. During ingestion, we measured how each vector database performs under serverless and EC2-based constraints, tracking document size scaling, chunk creation, embedding generation, insertion time, and resource usage (CPU and memory). By breaking ingestion into sub-steps, we identified which stages dominate overall cost as data volume increases. In the search phase, we evaluated query-time behavior, including database load time, query embedding latency, vector search time, and total retrieval latency. This allowed us to separate cold-start effects from actual similarity search performance. Finally, we combined ingestion and search metrics to analyze trade-offs holistically, reflecting real-world RAG usage where storage, performance, and cost must be evaluated together rather than in isolation. Ingestion Time vs Document Size The EC2-based execution exhibits a more stable and predictable performance profile, with text extraction and embedding times scaling smoothly as document size increases and consistently low overhead across all size buckets. This behavior highlights the advantages of a long-lived environment, where resources remain warm and readily available, avoiding repeated initialization costs. In contrast, the Lambda-based execution with an in-memory database follows a similar overall scaling trend but shows higher relative overhead, especially for very small and very large files. These additional costs are primarily driven by cold starts, runtime setup, and the stricter CPU and memory constraints of ephemeral executions. Notably, the core pipeline stages — text extraction, embedding, and vector insertion — remain consistent across both setups, confirming that serverless ingestion does not alter the fundamental workload characteristics, but rather introduces a fixed execution overhead. In practice, this makes EC2 a strong fit for sustained, batch-oriented ingestion, while Lambda stands out as a cost-efficient and operationally simpler option for event-driven or intermittent ingestion workloads, without compromising correctness or scalability. Figure 3: EC2 — Ingestion Pipeline Time Breakdown by File Size Ingestion: Performance Overview In the EC2-based execution, the ingestion benchmark exhibits a more stable and clearly differentiated performance profile across vector databases. Ingestion time scales predictably with document size, and resource utilization — particularly peak RAM and CPU — remains consistent for each database, reflecting the benefits of a long-lived, provisioned environment. Disk-backed and hybrid databases such as Qdrant and LanceDB show slightly higher but steady memory footprints, while Chroma’s in-memory design results in higher peak RAM usage that grows with both document size and chunk count. Importantly, the ingestion time breakdown reveals that text extraction and embedding dominate total latency across all databases, with minimal overhead variability, making EC2 well suited for sustained, high-throughput ingestion where predictability and throughput are priorities. Figure 4-a: EC2 RAG ingestion Bechmark — Performance Overview (by Vector DB) Figure 4-b: Serverless RAG ingestion Bechmark — Performance Overview (by Vector DB) In contrast, the Lambda-based execution with in-memory databases preserves the same overall scaling trends but introduces noticeably higher dispersion in ingestion time, CPU utilization, and overhead — especially for smaller documents. This variability is driven by cold starts, repeated runtime initialization, and stricter resource constraints inherent to ephemeral serverless execution. While core stages such as text extraction, embedding, and vector insertion behave similarly in both environments, Lambda amplifies fixed costs relative to workload size, making overhead more visible. Persisted database size and chunk-related scaling remain consistent between EC2 and Lambda, confirming that the underlying data model and indexing behavior are unchanged. In practice, this highlights a clear trade-off: EC2 excels for continuous, batch-oriented ingestion with tight performance control, whereas Lambda offers a simpler, cost-efficient option for event-driven or sporadic ingestion workloads — accepting some variability without compromising correctness or scalability. Ingestion Pipeline Breakdown Both the stacked and file-size–bucketed breakdowns reveal a clear and consistent pattern across execution models and vector databases: Text extraction remains relatively stable across document sizes and contributes only a small fraction of the total ingestion time. Embedding generation is the dominant cost and scales directly with document size and chunk count, quickly becoming the primary driver of ingestion latency. Vector insertion and persistence increase with the number of chunks but remain secondary compared to the cost of embedding inference. These results confirm that embedding computation — not storage or indexing — is the primary ingestion bottleneck. Even when using S3-backed vector storage, persistence overhead remains modest relative to compute-heavy stages. In practice, this means that optimizing ingestion performance is far more dependent on embedding model choice, batching strategies, and compute allocation than on the underlying vector storage backend. Search: Performance Overview In the EC2-based execution, the search benchmark exhibits a stable and highly predictable performance profile across all vector databases. Database load time and total search latency show a clear separation of concerns: once the vector index is loaded, search time remains consistently low and largely independent of top-k values. Vector search latency scales smoothly, and the distribution plots highlight tight variance, particularly for Qdrant, Lance, and Milvus Lite, which benefit from persistent memory, warm caches, and uninterrupted CPU availability. Importantly, LLM completion latency remains largely orthogonal to the vector database choice, confirming that retrieval performance does not interfere with downstream generation once the search step is complete. Figure 5-a: EC2 RAG Benchmark — By Vector DB Figure 5-b: Serverless RAG Benchmark — By Vector DB In contrast, the Lambda-based execution with in-memory vector databases follows the same qualitative trends but introduces additional variability and overhead. Search total time becomes more sensitive to database load time, especially for solutions that require index hydration at invocation time. This effect is most visible in the wider latency distributions and higher tail latencies, driven by cold starts, memory reallocation, and ephemeral storage constraints. However, the vector search operation itself remains fast and well-bounded across databases, indicating that Lambda does not alter the computational complexity of retrieval — only the surrounding execution context. In practice, this reinforces a clear trade-off: EC2 is better suited for latency-critical, high-throughput search workloads, while Lambda provides a compelling, cost-efficient option for bursty or event-driven RAG queries where slight increases in variance are acceptable without compromising correctness or scalability. Search Pipeline Breakdown The search-phase benchmarks reveal a similarly consistent pattern across vector databases and execution environments: Vector search time is generally low and stable for in-memory databases, even as top_k increases, indicating efficient ANN indexing and query execution. Database load time becomes a key differentiator in serverless setups, contributing a noticeable fixed overhead — particularly for in-memory databases that must be rehydrated on each invocation. LLM completion latency dominates end-to-end query time and shows the strongest correlation with input token count rather than vector database choice. Overall, the results show that retrieval itself is not the primary bottleneck in RAG search pipelines. Instead, latency is driven by a combination of database initialization (in ephemeral environments) and downstream LLM inference. Importantly, S3-backed vector storage introduces higher per-query retrieval latency but avoids repeated loading costs, while in-memory databases deliver faster raw search performance at the expense of cold-start overhead. In practice, this highlights a trade-off between raw query speed and operational simplicity, reinforcing that search performance is shaped more by execution context and LLM behavior than by the vector index alone. End-to-End RAG Implications Taken together, the ingestion and search benchmarks point to a clear architectural takeaway: Compute-heavy stages (embedding generation and LLM inference) dominate both latency and cost across all environments. Vector storage and retrieval introduce predictable, bounded overhead, which is secondary compared to model execution — regardless of whether vectors are stored in memory or in S3-backed systems. As a result, vector databases are rarely the limiting factor in real-world RAG pipelines. Teams can safely adopt serverless and object-store-backed vector architectures, such as Amazon S3 Vectors, without compromising correctness or scalability. The main trade-off shifts from raw performance to operational characteristics: in-memory stores favor ultra-low latency for warm, high-throughput workloads, while S3-backed approaches optimize for durability, cost efficiency, and simplicity in event-driven or elastic systems. Ultimately, optimizing RAG performance means focusing on model choice, batching strategies, and execution context — rather than over-indexing on vector storage mechanics. Final Thoughts This benchmarking study demonstrates that serverless RAG architectures — when combined with in-memory vector stores and persistent, object-store-backed solutions like Amazon S3 Vectors — form a robust, scalable, and cost-efficient alternative to traditional always-on vector databases. Across ingestion and search workloads, our evaluation of Chroma, LanceDB, Milvus Lite, and Qdrant shows that even ephemeral, per-request vector stores can deliver consistent, production-ready performance within the operational constraints of AWS Lambda. A key outcome of the results is that compute, not storage, dominates end-to-end RAG performance. Embedding generation and LLM inference account for the majority of latency and cost, while vector indexing, persistence, and retrieval introduce relatively small and predictable overhead. This holds true even when vectors are stored in S3-backed systems, confirming that object storage does not materially degrade RAG performance for typical workloads. Within this landscape, Amazon S3 Vectors emerges as a compelling architectural option. By combining the durability, scalability, and cost model of S3 with native vector indexing and search, it enables semantic retrieval without the operational burden of managing dedicated vector infrastructure. For teams prioritizing cost control, data isolation, and deployment simplicity — especially in event-driven or elastic workloads — this approach meaningfully simplifies RAG system design on AWS. From the benchmarks, three practical recommendations stand out. For serverless RAG workloads on AWS, Amazon S3 Vectors is the best overall choice, offering a strong balance of performance, scalability, and operational simplicity. For local development and rapid prototyping, Chroma remains an excellent fit, thanks to its lightweight design and fast iteration cycle. For long-running, high-QPS, latency-sensitive systems, Qdrant continues to excel, providing mature features and consistently low retrieval latency in always-on environments. In the end, there is no universal solution. The right vector database depends on workload patterns, performance expectations, and operational constraints. What these results make clear, however, is that AWS-native, serverless RAG architectures are no longer a compromise — they are increasingly the simplest, most scalable, and most cost-efficient way to build real-world RAG systems. The future of RAG on AWS is lean, elastic, and unmistakably vectorized. Future Work: Expanding Benchmark Coverage As we continue to evolve our benchmarking framework, our next steps focus on broadening its flexibility and testing capabilities across a wider variety of storage and deployment scenarios. First, we plan to add parametric support for multiple storage backends — including Amazon EFS, EBS, and ephemeral disks — to measure how intermediate disk processing affects performance. In parallel, we’ll extend testing beyond AWS Lambda to include containerized deployments on Kubernetes and Amazon ECS, enabling apples‑to‑apples comparisons between serverless and container-based architectures. We’re also adding wrappers for several widely-used vector libraries and databases, which will allow us to benchmark a broader spectrum of performance profiles and deployment patterns: HNSWlib — Lightweight, high-speed approximate nearest neighbor (ANN) search for resource-constrained or embedded environments. Annoy — A read-only, disk-backed index optimized for minimal memory usage and fast load times — ideal for serverless scenarios. Faiss — Meta’s high-performance vector library with GPU support and advanced indexing options, widely used in large-scale systems. Chroma — A Python-native vector database tailored for LLM applications, popular for rapid prototyping and small-scale RAG pipelines. Milvus Lite — A standalone, minimal version of Milvus for quick testing and ephemeral workloads. Redis Vector — Adds vector search capabilities to Redis, combining in-memory speed with built-in persistence. These additions will make our framework far more versatile and allow deeper comparisons across cost, latency, memory usage, and suitability for serverless, on-device, and production-scale deployments — giving teams the data they need to choose the right architecture with confidence. References Amazon S3 Vectors Introducing Amazon S3 Vectors (AWS News Blog) Chroma LanceDB Milvus Lite Qdrant"},{"href":"/rethinking-bioinformatics/","title":"Rethinking Bioinformatics","subtitle":"Solving the Challenges of Traditional Pipelines","description":"Solving the Challenges of Traditional Pipelines","abstract":"Solving the Challenges of Traditional Pipelines","tags":["Bioinformatics","Cloud Computing","Data Engineering","Scientific Workflows","Connectedlab"],"topics":[],"authors":["Sara Oquendo"],"text":"Bioinformatics workflows face a significant challenge: data is growing faster than our ability to process it with precision and traceability. This issue is especially problematic in today’s omics-driven research, where laboratories routinely handle terabytes of sequencing data and perform multi-step analyses involving alignment, variant calling, annotation, statistical modeling, and visualization. At the same time, computational processes are connected with digital laboratory systems such as LIMS, IoT-enabled sensors, and electronic lab notebooks, forming complex data ecosystems. As a result, both the scaling and heterogeneity of data have increased, making reproducibility and auditability harder to ensure and seamlessly integrate with cloud or hybrid infrastructures. Within this context, a common bottleneck in many labs occurs when scaling “traditional” or ad-hoc bioinformatics pipelines: long shell, Python, or R scripts that evolved over time, passed between teams and adapted to specific instrumentation or one time projects. For example, a sequencing facility increases its workload from a few dozen to several hundred genomes per month, often relying on manual file transfers, untracked software updates and computing systems configured in different ways. These factors collectively introduce delays, inconsistencies, and errors.Taken together, these issues only become more visible as data grows, making clear some central limitations of traditional pipelines: limited flexibility, poor reusability, constrained scalability, and insufficient traceability (Via Scientific, n.d). At the same time newer challenges are beginning to determine how modern bioinformatics pipelines operate. As labs scale up and migrate analyses onto the cloud and hybrid platforms, issues arise with standardizing workflows and alternating massive datasets between these systems. These processes become even more complex in regulated settings like healthcare and biotechnology, where nearly 40% of organizations now require end-to-end encryption and audit trails before trusting a cloud pipeline (MarketGrowthReports, n.d.). At the same time, the need for accurate data has never been higher, as recent reports indicate that approximately one-third of published results contain errors attributable to faulty inputs and data processing (Omni-Inc., n.d.). Beyond infrastructure challenges, the scientific work itself is becoming harder to manage. More and more labs are working with machine learning models and combining different omics analyses, but of course working with these tools together is tough since different data formats and systems don’t match with each other; plus many AI models still operate like black boxes which raises concerns among clinical teams and regulators. Labs also face everyday issues when their instruments, software, data platforms, and overall work are stored in different places, which necessitates manual file handling, formatting and double-checking. Taken together, these technical, organizational and regulatory challenges have sparked a clear shift towards more flexible and connected solutions like modular architecture and integrated lab systems — frameworks that are essential for making pipelines more flexible, reliable, scalable, reproducible, and traceable (Omni-Inc., n.d.; MarketGrowthReports, n.d.). The Challenge: Building a Modern Bioinformatics Pipeline When designing a scalable, adaptable, and reproducible bioinformatics pipeline that stays transparent from data generation to final analysis, the main question becomes less about the tools themselves and more about the architecture. The following example demonstrates how modular architectures and connected-lab principles can collectively solve practical challenges in omics research. Figure 1. End-to-End Example Cloud Architecture for Triggering Omics Pipeline Execution Using AWS Services. This diagram shows the end-to-end AWS cloud architecture for a modular bioinformatics workflow. (1) Public genomic data from repositories like UniProt and NCBI is (2) ingested into an Amazon S3 landing bucket. (3) Amazon EventBridge detects S3 uploads and triggers (4) AWS Step Functions, the central orchestrator. Step Functions coordinates the Nextflow workflow execution, supporting two parallel options: (5) AWS HealthOmics, a managed omics-optimized environment, or (6) AWS Batch, a flexible compute service. Both pull containerized components from Amazon ECR. (7) Results are returned to S3 for downstream analysis, generating insights and visualizations. In this example, I explore two cloud-native approaches for running bioinformatics pipelines on AWS, AWS HealthOmics and AWS Batch, using a shared workflow. While both approaches produce the same outputs, their implementations, advantages, and trade-offs differ depending on the use case. The pipeline follows the typical structure of many omics workflows: raw data ingestion, quality control, alignment, variant calling, and reporting. Instead of packaging these stages into a single monolithic script, each step was designed as an independent, reusable module. All components run inside containers and are orchestrated with Nextflow, a workflow manager that supports cloud execution, scalable parallelization, and reproducibility (Di Tommaso et al., 2017; Nextflow, n.d.). From a Script Pile to a Modular System Traditional pipelines are often inflexible, one massive script that processes data from start to finish. They can be quick to implement but difficult to maintain or scale. Modular design changes that logic by breaking the process into small, containerized steps with clear inputs and outputs. Each part becomes replaceable, testable, and reusable (Leipzig, 2017). Tools like Docker or Singularity handle the environment. Workflow engines like Nextflow or Snakemake manage the flow. And cloud services like AWS handle the scale. Suddenly we can now mix, match, rerun, or extend parts of the pipeline without rewriting the whole thing (Nextflow, n.d.). Why Modularity Works (Especially in Bioinformatics) Bioinformatics evolves rapidly; new tools, formats and practices appear regularly. A modular design easily adjusts to these changes because: It adapts: When testing a new variant caller or aligner, swapping the module rather than the entire pipeline ensures that the updates are localized and non-disruptive. It scales: Modular pipelines parallelize naturally. While one sample is aligning, another is already trimming. AWS Batch or HealthOmics can achieve faster runs and smarter compute use (Amazon Web Services, n.d.). It reuses: Common steps like QC, alignment, and trimming can easily be reused across datasets. As an example, the nf-core community is built on this idea (nf-core community, n.d.). It tracks everything: Each module runs in a container, with logging, versioning, and defined outputs. That makes results traceable, audit-friendly, and reproducible Musts in regulated or collaborative settings (Wilkinson, 2016). This setup also simplified the implementation. The pipeline itself remained unchanged between AWS Batch and HealthOmics. Only the execution layer differed, which makes it easier to choose the execution model that best fits the specific use case. Common Tools Supporting Modularity Several workflow managers are designed for modular pipelines, each offering various advantages and disadvantages: Nextflow: One of the most widely adopted tools in bioinformatics supports containers, cloud, and parallelism. In addition, it has a strong web-based community and cloud-native support. Snakemake: Python-based, ideal for academic settings. Allows modular rule reuse, integrates well with local and cloud clusters. Galaxy: User- friendly visual interface, popular in industry and core labs. Modular, though less flexible for custom logic. Toil/Cromwell: Built for large-scale pipelines using WDL or CWL. Focused on scale and reproducibility. Choosing the right tool depends on the context, team expertise, infrastructure, and how complex or reusable the workflow needs to be. However, what they all share is the ability to turn analysis pipelines into structured, maintainable systems. Usually, as data volume increases alongside its project scaling, using one of these tools becomes more of a necessity instead of a convenience (Leipzig, 2017). When Not to Modularize Modularizing every single workflow isn’t always the best approach. For small, quick analyses or experiments that change every day, setting up containers and workflow configs can be an unnecessary effort. In those cases, simple scripting might be the more practical choice. But when scaling, reusing or sharing a workflow across a team, modular design becomes a long-term choice by reducing re-work, improving clarity, and letting pipelines evolve without breaking everything apart. Connected Labs: Where the Lab Meets the Cloud Another defining characteristic of the project is its integration to actual laboratory workflows. While the data used came from open biological repositories, the architecture was designed to mirror a lab-to-cloud ecosystem, an environment where the instruments that generate raw data, systems that manage metadata, and compute pipelines that analyze results are all interconnected. In this setup, after a sample is processed at the bench, its digital counterpart automatically moves through ingestion, quality checks, and analysis, with every step logged and versioned for full traceability from start to finish. What Is a Connected Lab? A connected lab is a digitally integrated environment where physical lab instruments, data management systems, and analytical tools operate as one coordinated system. Technologies like cloud computing, Internet of Things (IoT) enabled devices, artificial intelligence (AI) and LIMS/ELN platforms monitor and control experiments centrally, with data automatically collected and accessible in real time (LabHorizons, 2024). Three Ways Connected Labs Improve Scientific Workflows Disconnected systems create bottlenecks. For example, technicians manually transferring files from sequencers to storage, researchers retyping sample metadata into analysis tools, or delays caused by waiting for someone to trigger the next step in the workflowcan all slow down progress, increase the risk of error, waste time and money, and make it harder to keep data organized and reproducible. Connected labs are designed to address these gaps through tighter integration, automation, and traceability (LabHorizons, 2024): In the case of automation and workflow triggers, routine steps that once required human involvement like launching a pipeline or uploading results can now be fully automated. In the example, uploading new sequencing data to an S3 landing bucket automatically triggered the analysis workflow via AWS EventBridge. The connection between data entry and pipeline launch was real-time and hands-free, simulating how lab instruments can trigger downstream analysis, reporting, or alerts without technician intervention. 2. Traceability in connected labs is a foundational layer. Each stage of the workflow, from sample acquisition to final output, is tied to structured metadata that can include sample identifiers, instrument logs, reagent batch numbers, and protocol versions (LabHorizons, 2024). Also, containers were versioned in Amazon ECR, while execution metadata such as runtime configuration and performance logs were captured via Amazon CloudWatch. These records copy the kind of digital audit trail that tools like LIMS or ELNs provide in physical lab environments, ensuring that: Each protocol is properly versioned. Data inputs and outputs are fully documented. A complete, verifiable audit trail is maintained. This tracking is essential for simplifying troubleshooting, and maintaining reproducibility and data integrity, especially in research that demands validation, peer review, or regulatory oversight. 3. When it comes to compliance, most laboratory conditions are controlled by strict standards. Whether in clinical research, pharmaceutical development, or regulatory certification, there’s a constant need to show that processes are applied consistently and results are trustworthy. Connected systems ease this pressure by embedding compliance directly into day-to-day operations. They enable: Automated logging of actions, versions, and runtime details Role-based access control and secure data retention Enforced use of validated, standardized workflows This approach to compliance was reflected in the example through the use of AWS HealthOmics, a managed execution environment that provides regulatory alignment out of the box. Combined with CloudWatch monitoring, the setup ensured that every run was reliable, traceable, and free from manual follow-up (Amazon Web Services, n.d.). Managing Data Scale, Complexity, and Compliance in Modern Laboratories Modern laboratories are encountering challenges that make digital connectivity not just beneficial, but indispensable. As research outputs grow, producing massive volumes of omics data while simultaneously relying on increasingly complex instrumentation, labs must ensure accuracy, traceability, and compliance at every step. Connected-lab systems make this possible by integrating data streams, instruments, and computational workflows so that information flows seamlessly and can be processed in real time. This level of integration enables faster, better-informed decisions; reduces bottlenecks; and strengthens reliability. Automated monitoring can flag issues, such as equipment malfunctions or potential sample contamination, before they escalate into costly setbacks. As highlighted by LabManager, organizations that invest in connected and automated laboratory environments are better positioned to improve workflow efficiency, maintain reproducibility, and control operational costs. Over time, these benefits help reduce the impact of short-term transformation challenges in today’s competitive research environment. References Amazon Web Services. (n.d.). AWS HealthOmics. Retrieved December 4, 2025, from aws.amazon.com Di Tommaso, P., Chatzou, M., Floden, E. et al. Nextflow enables reproducible computational workflows. Nat Biotechnol 35, 316–319 (2017). doi.org Jeremy Leipzig, A review of bioinformatic pipeline frameworks, Briefings in Bioinformatics, Volume 18, Issue 3, May 2017, Pages 530–536, doi.org LabHorizons. (2024, May). What is a connected lab and how is it helpful? LabHorizons. Retrieved December 4, 2025, from labhorizons.co.uk LabManager. (n.d.). Unlocking efficiency through lab transformation. LabManager. Retrieved December 4, 2025, from www.labmanager.com MarketGrowthReports. (n.d.). Bioinformatics Cloud Platform Market Report. MarketGrowthReports. Retrieved December 4, 2025, from www.marketgrowthreports.com Nextflow. (n.d.). Nextflow documentation. Retrieved December 4, 2025, from www.nextflow.io nf-core community. (n.d.). nf-core. Retrieved December 4, 2025, from nf-co.re Omni-Inc. (n.d.). Garbage in, garbage out — dealing with data errors in bioinformatics. Omni-Inc. Retrieved December 4, 2025, from blog.omni-inc.com Via Scientific. (n.d.). How modular pipelines are changing bioinformatics. Via Scientific. Retrieved December 4, 2025, from medium.com Wilkinson, M., Dumontier, M., Aalbersberg, I. et al. (2016). The FAIR Guiding Principles for scientific data management and stewardship. Sci Data 3, 160018 (2016). doi.org"},{"href":"/part-2-agentic-patterns-101-with-loka-strands-agents/","title":"Part 2: Agentic Patterns 101 with Loka & Strands-Agents","description":"After exploring the foundations of Agentic Patterns in Part 1, where we looked at more structured workflows like Sequential and Parallel workflows, LLM Routing, and Reflection, this time we are going to push further…","abstract":"After exploring the foundations of Agentic Patterns in Part 1, where we looked at more structured workflows like Sequential and Parallel workflows, LLM Routing, and Reflection, this time we are going to push further…","tags":["Strands Agents","Agentic AI","Generative AI","Amazon Bedrock","AI Agents"],"topics":[],"authors":["Nina Cvetkovska","Petar Kalinovski","Bojan Jakimovski"],"text":"After exploring the foundations of Agentic Patterns in Part 1, where we looked at more structured workflows like Sequential and Parallel workflows, LLM Routing, and Reflection, this time we are going to push further into the more advanced side of agentic pattern designs. In this second part, we’ll turn our attention to patterns that extend beyond predefined workflows and begin to showcase the real flexibility Strands-Agents,. Here, agents aren’t just decision-makers, they can become tools, orchestrators, collaborators, or even parts of larger graph-like systems. These patterns highlight how agentic systems can evolve from simple task runners into dynamic, interconnected ecosystems. While Part 1 focused on how to structure work, Part 2 dives into how agents interact with their environment and with each other. This includes integrating with raw Python functions, leveraging external MCP servers, orchestrating worker agents, coordinating swarms, and managing complex graph-based interactions. Each of these patterns demonstrates a different way to scale capability, distribute reasoning, and balance autonomy with control. As we said, all examples use Strands-Agents, the open-source SDK from AWS that makes it easy to test these approaches in a model-agnostic way. By the end, you’ll have a toolkit of patterns that span from single-agent efficiency to multi-agent collaboration, giving you the flexibility to choose the right design for your system’s needs. Pattern Overview In this post, we’ll cover the remaining five patterns from the total of nine patterns: Sequential Workflow Parallel Workflow LLM Routing Reflection Pattern Pure Python Tools Tools from MCP Servers Agents as Tools (Orchestrator-Workers) Swarm Graph Multi-Agent Pattern All of the examples for the patterns can be found on the GitHub repository here. Pure Python Tools Pure Python tools pattern: one Strands agent invokes specialized Python tools. Pure Tools in Strands provide a straightforward and effective way to extend agent capabilities through specialized tools. In this pattern, each tool handles domain-specific logic while a single agent coordinates their usage through natural language interactions. This approach allows agents to work with multiple tools smoothly without requiring hardcoded workflows, keeping responsibilities modular and interactions intuitive. Pure Tools maintain clarity and ease of maintenance by separating tool functionality from agent reasoning. This lets the model focus on orchestration and decision-making rather than getting caught up in low-level task execution. There are three main types of Pure Tools in Strands, categorized by how they are implemented and used within an agent: Predefined Tools: Built-in utilities provided by Strands for common tasks such as data retrieval, HTTP requests, or document searches. Tools in Classes: Custom tools implemented as methods inside a Python class, enabling stateful behavior or grouped domain-specific functionality. Decorator Functions: Python-decorated functions that define tools with simple input/output behavior, easy to register with agents, and reusable across different applications. Characteristics of Pure Tools: Clean agent-tool architecture where tools handle specialized tasks Natural language coordination powered by intelligent models Clear separation between agent reasoning and tool execution Tools can be mixed, matched, and reused across different agents and projects Use Cases & Industries: E-commerce Operations: Agents manage inventory, track orders, and handle fulfillment via Pure Tools — e.g., in online retail platforms. Data Management & Analytics: Agents perform CRUD operations, query databases, or generate reports — e.g., in Financial Services or Enterprise IT. HR Systems: Agents manage employee onboarding, leave requests, performance evaluations, and recruitment — e.g., in Corporate HR departments. Enterprise Knowledge Management: Agents access policies, compliance documents, or internal templates via Pure Tools — e.g., in Legal Tech or Enterprise Operations. When to Use / When Not to Use: Use when: You have domain-specific tasks that can be encapsulated as independent tools and benefit from model-driven orchestration. Avoid when: Workflows are highly interdependent, require multi-step coordination across multiple specialized agents, or need complex multi-agent orchestration. Code Example: This example demonstrates Pure Tools through a travel planning workflow. It features a TripPlanner class with tool-decorated methods for managing destinations and activities, plus a suggest_activity tool that uses agent intelligence for travel recommendations. The example also shows how the predefined tavily_search tool integrates to fetch destination data and activity ratings. \"\"\"Example of pure tools usage for Trip Planning.\"\"\" import os from dotenv import load_dotenv from strands import Agent, tool from strands.models import BedrockModel from strands_tools.tavily import tavily_search # Retrieve the Tavily API key from environment load_dotenv() TAVILY_API_KEY = os.getenv(\"TAVILY_API_KEY\") SUGGESTION_INSTRUCTION = ( \"Suggest one specific, practical travel activity for {destination}.\" \"Provide a concise recommendation (1-2 sentences) that includes:\" \"- A specific attraction, landmark, or experience\" \"- Brief context about why it's worth doing\" \"Example format: Visit [specific place] and [what you can do/see there].\" ) class TripPlanner: \"\"\"Tracks destinations, travel dates, and planned activities.\"\"\" def __init__(self): \"\"\"Initialize an empty TripPlanner with no destinations or activities.\"\"\" self.destinations = [] self.itinerary = {} @tool def add_destination(self, city: str, start_date: str, end_date: str) -> str: \"\"\"Add a destination to the trip with travel dates.\"\"\" self.destinations.append(city) self.itinerary[city] = { \"start_date\": start_date, \"end_date\": end_date, \"activities\": [], } return f\"{city} added to your trip from {start_date} to {end_date}.\" @tool def add_activity(self, city: str, activity: str) -> str: \"\"\"Add an activity to a city's itinerary.\"\"\" if city in self.itinerary: self.itinerary[city][\"activities\"].append(activity) return f\"Added activity '{activity}' to {city} itinerary.\" return f\"{city} is not in your trip.\" @tool def view_itinerary(self) -> str: \"\"\"Generate a human-readable summary of the entire trip itinerary.\"\"\" summary = \"\" for city, details in self.itinerary.items(): summary += f\"{city} ({details['start_date']} to {details['end_date']}):\\n\" for activity in details[\"activities\"]: summary += f\" - {activity}\\n\" return summary if summary else \"No destinations planned yet.\" @tool def suggest_activity(destination: str, agent: Agent) -> str: \"\"\"Suggest a key activity for a given destination using the agent's model.\"\"\" # Fill in the destination in the instruction prompt = SUGGESTION_INSTRUCTION.format(destination=destination) # Create a temporary agent with just the model for this generation temp_agent = Agent(model=agent.model) suggestion = temp_agent(prompt) return f\"Suggestion for {destination}: {suggestion}\" if __name__ == \"__main__\": # Define the model for the agents model = BedrockModel( model_id=\"amazon.nova-lite-v1:0\", temperature=0.7, max_tokens=3000 ) # Define planner and agent planner = TripPlanner() agent = Agent( tools=[ suggest_activity, planner.add_destination, planner.add_activity, planner.view_itinerary, tavily_search, ], model=model, ) # Example Usage response = agent(\"Add Tokyo as a destination from 2025-10-01 to 2025-10-07\") response = agent(\"Suggest an activity for Tokyo and add it to my itinerary\") response = agent(\"Search for ratings for each item in the itinerary.\") response = agent(\"Show me my complete travel itinerary\") Tools from MCP Servers MCP tools pattern: a Strands agent sends requests to tools exposed by MCP servers. The Model Context Protocol (MCP) is an open standard that defines how applications provide context to Large Language Models (LLMs). MCP enables communication between agents and MCP servers, which expose additional tools that agents can call to extend their capabilities. These tools can range from database queries to APIs or custom business logic, allowing agents to act beyond their base reasoning abilities. There are three standardized types of MCP servers, categorized by transport protocol: STDIO (Standard Input/Output), usually when the client and the server are on the same side SSE (server-sent events, currently being deprecated) Streamable HTTP Events (the modern, preferred approach) Characteristics of Tools from MCP Servers: Provide structured, standardized communication between agents and external tools Model-agnostic: any LLM can leverage MCP-defined tools Extend agent functionality with external data, APIs, or services Enable interoperability between multiple systems and agents Use Cases & Industries: Enterprise Data Access: Agents retrieve structured data from ERP/CRM systems via MCP tools — e.g., in Enterprise IT or Customer Relationship Management. Knowledge Retrieval: An MCP server provides search or vector database querying tools — e.g., in Legal Tech for case document retrieval. Operational Automation: Agents call MCP-exposed APIs (via MCP tools) for scheduling, ticketing, or reporting — e.g., in Customer Support or HR Systems. Healthcare & Life Sciences: MCP tools that can expose access to medical ontologies or EHR (Electronic Health Records) queries in a standardized way. When to Use / When Not to Use: Use when: Agents need structured, standardized access to external tools, systems, or APIs in a way that is interoperable and vendor-neutral. Avoid when: The task is fully self-contained within the LLM (e.g., pure text summarization) or when a lightweight, direct API call without protocol overhead is sufficient. Code Example: This example shows how we can use a STDIO MCP Server tools for AWS HealthOmics workflows. \"\"\"Example of tool use Agent with MCP server tools\"\"\" # from mcp.client.sse import sse_client - for HTTP MCP servers that use Server-Sent Events (SSE) # from mcp.client.streamable_http import streamablehttp_client - for HTTP MCP servers that use Streamable HTTP Events from mcp import StdioServerParameters, stdio_client # for MCP servers that use STDIO from strands import Agent from strands.models import BedrockModel from strands.tools.mcp import MCPClient INSTRUCTION = \"You are a Bioinformatics expert, that has a deep understanding of genomic data analysis and variant calling.\" # Creating an STDIO client for the MCP server because that's the way to interact with this server # https://awslabs.github.io/mcp/servers/aws-healthomics-mcp-server mcp_client = MCPClient( lambda: stdio_client( StdioServerParameters( command=\"uvx\", args=[\"awslabs.aws-healthomics-mcp-server\"] ) ) ) # If the MCP server uses Server-Sent Events (SSE) # mcp_client = MCPClient(lambda: sse_client(\"http://localhost:8000/sse\")) # If the MCP server uses Streamable HTTP Events # mcp_client = MCPClient(lambda: streamablehttp_client(\"http://localhost:8000/mcp\")) if __name__ == \"__main__\": # Define the model we use for the agents bedrock_model = BedrockModel( model_id=\"us.amazon.nova-premier-v1:0\", temperature=0.1, ) # Create an agent with MCP tools - must be within the context of the MCP client with mcp_client: # Get the tools from the MCP server tools = mcp_client.list_tools_sync() # Create an agent with these tools agent = Agent(tools=tools, system_prompt=INSTRUCTION, model=bedrock_model) # Define the query/question and execute the agent query = \"Help me create a new genomic variant calling workflow\" result = agent(query) print(\"The result is:\", result) Agents as Tools Agents as Tools pattern: a central agent invokes specialized agents for delegated tasks. The Agents as Tools pattern is a multi-agent architecture where individual agents make their capabilities available as callable tools. A central orchestrator coordinates these specialized agents to tackle complex, multi-step problems. Each worker agent contains domain-specific knowledge and skills, letting the orchestrator mix and match their capabilities to build complete solutions. This approach promotes modularity, scalability, and clear responsibility divisions across agents. Characteristics of Agents as Tools: Domain-specialized agents handle specific tasks or knowledge areas Orchestrator-managed workflows enable flexible combinations of worker agents Modular architecture supports scalable deployments across large systems Inter-agent communication allows efficient result sharing and coordination New worker agents can be integrated without disrupting existing functionality Use Cases & Industries: Customer Support: Orchestrator agent coordinates multiple chatbot agents to handle FAQs, ticket routing, and escalation — e.g., in Helpdesk or Customer Relationship Management. Finance: Worker agents perform loan processing, fraud detection, and credit assessment in a coordinated workflow — e.g., in Banking or FinTech applications. Education: Adaptive learning agents collaborate with curriculum planning agents to provide personalized recommendations — e.g., in EdTech platforms for student learning paths. Healthcare & Life Sciences: Specialist agents provide diagnostics, treatment suggestions, and scheduling assistance under orchestrator supervision — e.g., in Hospitals or Telemedicine platforms. When to Use / When Not to Use: Use when: Tasks require multiple specialized agents working together, or when workflows are complex enough to benefit from modular architecture. Avoid when: The application is straightforward or single-domain, where one capable agent can handle all tasks effectively. Code Example: This example shows how to use Strands agents as tools in an HR management workflow. Multiple specialized worker agents, each decorated as tools, handle employee data, leave management, performance reviews, and recruitment tasks. A central orchestrator coordinates these workers to respond to complex HR queries. The example also integrates predefined Strands tools like retrieve and http_request to access company knowledge bases and external data sources. \"\"\"Example of agents as tools usage for HR Management.\"\"\" import os from dotenv import load_dotenv from strands import Agent, tool from strands.models import BedrockModel from strands_tools import http_request, retrieve # Define knowledge base load_dotenv() os.environ[\"KNOWLEDGE_BASE_ID\"] = os.getenv(\"STRANDS_KNOWLEDGE_BASE_ID\") os.environ[\"AWS_REGION\"] = os.getenv(\"STRANDS_KNOWLEDGE_BASE_REGION\") # Define prompts EMPLOYEE_DATA_PROMPT = \"\"\" You are an Employee Data Specialist. You have access to employee records and company knowledge base. Use the retrieve tool to search for relevant information from company documents, org charts, job descriptions, and employee databases. Always be professional and respect employee privacy - only share information that would be appropriate for HR or management purposes. \"\"\" HR_ORCHESTRATOR_PROMPT = \"\"\" You are an HR Management Assistant that coordinates various HR functions. You have access to specialized HR agents that can help with different aspects of human resources management: 1. Employee Data Assistant - Employee records, organizational charts, department information 2. Leave Management Assistant - PTO, vacation requests, sick leave, time off policies 3. Performance Review Assistant - Performance reviews, goal setting, career development 4. Recruitment Assistant - Hiring, job postings, candidate evaluation, recruitment strategy When you receive a query, determine which specialist(s) can best help and route the request appropriately. You can also coordinate between multiple specialists if needed for complex requests. Always maintain professionalism and respect employee privacy and confidentiality. \"\"\" RECRUITMENT_PROMPT = \"\"\" You are a Recruitment Specialist. You help with hiring processes, candidate evaluation, job posting creation, and recruitment strategy. You understand job requirements and can match candidates to positions effectively. Focus on: - Job requirement analysis - Candidate screening criteria - Interview question preparation - Recruitment process optimization - Diversity and inclusion in hiring \"\"\" LEAVE_MANAGEMENT_PROMPT = \"\"\" You are a Leave Management Specialist. You handle all aspects of employee time off. Use the retrieve tool to access company leave policies, holiday calendars, and approval workflows. \"\"\" PERFORMANCE_REVIEW_PROMPT = \"\"\" You are a Performance Management Specialist. You handle performance reviews, goal setting, and career development using company resources and best practices. Always search for the latest company guidelines and templates before providing advice. Focus on objective, constructive feedback aligned with company values and processes. \"\"\" @tool def employee_data_assistant(query: str, agent: Agent) -> str: \"\"\" Handle employee data queries like finding employee information, department searches, organizational charts, and basic employee record management. \"\"\" try: employee_agent = Agent( model=agent.model, system_prompt=EMPLOYEE_DATA_PROMPT, tools=[retrieve] ) # Let the agent use retrieve to search company knowledge base enhanced_query = f\"Search company knowledge base for: {query}\" response = employee_agent(enhanced_query) return str(response) except Exception as e: return f\"Error in employee data assistant: {str(e)}\" @tool def leave_management_assistant(query: str, agent: Agent) -> str: \"\"\" Handle leave and PTO related queries including checking balances, submitting requests, approving time off, and providing leave policy information. \"\"\" try: leave_agent = Agent( model=agent.model, system_prompt=LEAVE_MANAGEMENT_PROMPT, tools=[retrieve] ) # First search company knowledge base, then supplement with current data enhanced_query = f\"First, search company knowledge base for leave policies and procedures related to: {query}\" response = leave_agent(enhanced_query) return str(response) except Exception as e: return f\"Error in leave management assistant: {str(e)}\" @tool def performance_review_assistant(query: str, agent: Agent) -> str: \"\"\" Handle performance review queries including review scheduling, performance analysis, goal setting, and career development planning. \"\"\" try: performance_agent = Agent( model=agent.model, system_prompt=PERFORMANCE_REVIEW_PROMPT, tools=[retrieve] ) # Search company knowledge base first, then use current data enhanced_query = f\"Search company knowledge base for performance management resources related to: {query}\" response = performance_agent(enhanced_query) return str(response) except Exception as e: return f\"Error in performance review assistant: {str(e)}\" @tool def recruitment_assistant(query: str, agent: Agent) -> str: \"\"\" Handle recruitment and hiring queries including job postings, candidate evaluation, interview processes, and hiring decisions. \"\"\" try: recruitment_agent = Agent( model=agent.model, system_prompt=RECRUITMENT_PROMPT, tools=[retrieve, http_request], ) response = recruitment_agent(query) return str(response) except Exception as e: return f\"Error in recruitment assistant: {str(e)}\" if __name__ == \"__main__\": # Define the model for the agents model = BedrockModel( model_id=\"amazon.nova-lite-v1:0\", temperature=0.7, max_tokens=3000 ) # Create the main orchestrator agent hr_orchestrator = Agent( model=model, system_prompt=HR_ORCHESTRATOR_PROMPT, callback_handler=None, tools=[ employee_data_assistant, leave_management_assistant, performance_review_assistant, recruitment_assistant, ], ) # Example for employee lookup response = hr_orchestrator( \"Can you find information about Sarah Johnson and tell me about her role and performance?\" ) # Example for leave request response = hr_orchestrator( \"What is Mike Chen's current PTO balance and does he have any pending leave requests?\" ) # Example for performance review response = hr_orchestrator( \"I need to prepare for Sarah Johnson's upcoming performance review. What are her current goals and recent achievements?\" ) # Example for recruitment query response = hr_orchestrator( \"We need to hire a new software engineer for the Engineering team. What skills should we look for based on our current team composition?\" ) # Example with policy lookup response_policy = hr_orchestrator( \"What is our current remote work policy and how many days per week can employees work from home?\" ) # Example with template search response_template = hr_orchestrator( \"I need to conduct a performance review for a Software Engineer. Can you find our performance review template and suggest key areas to evaluate?\" ) # Example with compliance search response_compliance = hr_orchestrator( \"What are the legal requirements for conducting layoffs in California, and do we have internal guidelines for this process?\" ) Swarm Swarm pattern: multiple specialized agents coordinate as autonomous peers. Swarm is a collaborative agent orchestration pattern where multiple specialized agents work together as autonomous peers to solve complex tasks. Unlike hierarchical multi-agent systems with central orchestrators, Swarm enables self-organizing coordination between agents through shared working memory and autonomous handoffs. Each agent has access to the full task context, can see the history of which agents have worked on the task, and can decide when to transfer control to another agent with different expertise based on their discoveries. Characteristics of Swarm: Autonomous coordination without central control Shared working memory accessible to all agents Dynamic task distribution based on agent capabilities and discoveries Peer-to-peer handoffs triggered by findings or needs Emergent intelligence through collective collaboration Self-organizing agent teams with flexible interaction patterns Use Cases & Industries: Viral Content Creation: Autonomous collaboration between trend analysts, meme creators, video creators, copywriters, and community managers who hand off based on discoveries and creative insights — e.g., in Social Media Marketing, Influencer Platforms, or Digital Marketing Agencies. Research and Investigation: Collaborative teams where data scientists, domain experts, and analysts hand off based on findings that emerge during investigation — e.g., in Market Research, Scientific Research, or Investigative Journalism. Crisis Response Teams: Emergency response specialists, communications experts, and resource coordinators collaborating dynamically as situations evolve — e.g., in Emergency Management, Incident Response, or Crisis Communications. When to Use / When Not to Use: Use when: Task outcomes are unpredictable, creative collaboration adds value, no single agent can determine the optimal sequence, or when discoveries by one agent should influence the entire approach. Avoid when: Tasks have clear hierarchies or sequences, central coordination is more efficient, or when agents don’t benefit from shared context and autonomous decision-making. Code Example: In this example we are showing how a simple Swarm Agent can be used to create viral content for social media platforms. \"\"\"Example of a viral content creation swarm\"\"\" from strands import Agent from strands.models import BedrockModel from strands.multiagent import Swarm from strands.types.content import ContentBlock # Agent prompts TREND_ANALYST_PROMPT = \"You are a trend analyst who analyzes viral content. You can view images and videos to understand what visual elements are trending. Identify patterns in successful content and timing windows.\" MEME_CREATOR_PROMPT = \"You are a visual meme creator who can both analyze existing memes and generate new ones. Create engaging visual content using trending formats. You can generate images and critique visual content.\" VIDEO_CREATOR_PROMPT = \"You are a video content creator who can create new videos. Generate short-form videos and analyze what makes videos go viral on different platforms.\" COPYWRITER_PROMPT = \"You are a social media copywriter. You can view images and videos to write appropriate captions and copy that matches the visual content.\" COMMUNITY_MANAGER_PROMPT = \"You are a community manager who can analyze visual content and engagement patterns. You can view memes, videos, and posts to understand audience reactions.\" if __name__ == \"__main__\": \"\"\" Main function to execute the swarm process. \"\"\" # Create the agents trend_analyst = Agent( model=BedrockModel(model_id=\"amazon.nova-pro-v1:0\", temperature=0.7), system_prompt=TREND_ANALYST_PROMPT, ) meme_creator = Agent( model=BedrockModel( model_id=\"amazon.nova-canvas-v1:0\", temperature=0.8 ), # Image generation model system_prompt=MEME_CREATOR_PROMPT, ) video_creator = Agent( model=BedrockModel( model_id=\"amazon.nova-reel-v1:0\", temperature=0.8 ), # Video generation model system_prompt=VIDEO_CREATOR_PROMPT, ) copywriter = Agent( model=BedrockModel(model_id=\"amazon.nova-lite-v1:0\", temperature=0.9), system_prompt=COPYWRITER_PROMPT, ) community_manager = Agent( model=BedrockModel(model_id=\"amazon.nova-lite-v1:0\", temperature=0.6), system_prompt=COMMUNITY_MANAGER_PROMPT, ) # Create the swarm viral_content_swarm = Swarm( [trend_analyst, meme_creator, video_creator, copywriter, community_manager], max_handoffs=15, max_iterations=10, ) # Creating the prompt using ContentBlocks trending_meme_bytes = b\"...\" # Placeholder for trending meme image bytes content_blocks = [ ContentBlock( text=\"Create a viral campaign about AI breakthroughs. Something similar to the campaign from last year:\" ), ContentBlock(image={\"format\": \"png\", \"source\": {\"bytes\": trending_meme_bytes}}), ] result = viral_content_swarm(content_blocks) print(f\"Swarm Status: {result.status}\") print(f\"Node history: {[node.node_id for node in result.node_history]}\") Graph Multi-Agent Pattern Graph multi-agent pattern: agents are nodes in a directed acyclic workflow. The Graph Multi-Agent Pattern is a structured, DAG-based orchestration approach where each node represents an agent (or custom multi-agent group), and edges define execution dependencies. This pattern lets you build complex workflows with explicit structure, allowing agents to coordinate their actions in a defined sequence. Nodes can house specialized agents with distinct capabilities, while edges control dependencies and data flow between them. The pattern supports conditional branching and multi-modal inputs, so workflows can adapt based on intermediate results or different input types. Characteristics of Graph Multi-Agent Pattern: Deterministic execution order creates predictable and reproducible workflows Clear dependency management supports nested patterns, hierarchical coordination, and conditional logic Nodes can contain custom agent types tailored for specific workflow tasks Handles multi-modal inputs and conditional branching for complex scenarios Modular architecture allows you to add or remove agents without breaking the overall workflow Use Cases & Industries: Financial Analysis: Agents fetch market or company data, analyze trends, summarize insights, and generate reports — e.g., in Banking, Investment Research, or Risk Management. Content Creation: Multi-agent pipelines research topics, draft content, edit, and publish — e.g., in Marketing, Journalism, or Educational Content Development. IoT & Industrial Automation: Agents monitor devices, diagnose issues, optimize performance, and trigger alerts — e.g., in Smart Manufacturing, Energy Management, or Logistics. Healthcare & Life Sciences: Data-collection agents gather patient or research data, analysis agents process it, diagnostic agents provide recommendations, and reporting agents summarize findings — e.g., in Clinical Decision Support or Hospital Workflow Management. When to Use / When Not to Use: Use when: Your workflows have complex dependencies, multiple agents bring distinct expertise, task outcomes depend on coordinated execution, or intermediate results need to influence downstream agents. Avoid when: Tasks are straightforward or linear, a single agent can handle the workflow effectively, or when deterministic orchestration adds complexity without meaningful benefits. Code Example: This example shows how to use Strands agents in a graph-based multi-agent workflow to create a structured Dinner Plan. Each specialized agent handles a specific task (recipe creation, beverage pairing, music curation), while a central planner agent combines their outputs into a cohesive final result. \"\"\"Example of a graph-based multi-agent workflow for generating a structured Dinner Plan.\"\"\" from strands import Agent from strands.models import BedrockModel from strands.multiagent import GraphBuilder ROUTER_INSTRUCTION = ( \"Interpret the user's dinner request and dispatch tasks to appropriate agents.\" ) RECIPE_CREATOR_INSTRUCTION = ( \"Propose a refined recipe suitable for the requested dinner style.\" ) BEVERAGE_SUGGESTOR_INSTRUCTION = ( \"Suggest a beverage that complements the dinner style and recipe.\" ) MUSIC_CURATOR_INSTRUCTION = \"Curate a playlist that matches the dinner ambiance and enhances the dining experience.\" DINNER_PLANNER_INSTRUCTION = ( \"Combine the outputs from RecipeAgent, BeverageAgent, and MusicAgent into a single structured DinnerPlan object. \" \"The DinnerPlan should have the following fields:\" \"1. recipe: include all recipe details with subfields:\" \" - name (str)\" \" - ingredients (list of str)\" \" - preparation_time (int, in minutes)\" \" - instructions (str)\" \"2. beverage: include beverage details with subfields:\" \" - name (str)\" \" - type (str, e.g., wine, cocktail, non-alcoholic)\" \" - pairing_notes (str, explaining why it pairs with the recipe)\" \"3. music_playlist: include music details with subfields:\" \" - title (str)\" \" - tracks (list of objects, each with:\" \" - track_name (str)\" \" - artist (str)\" \" - genre (str, e.g., Classical, Jazz, Pop)\" \" )\" \"Return the combined DinnerPlan object in valid JSON format that matches the DinnerPlan Pydantic model exactly.\" ) if __name__ == \"__main__\": user_query = \"Dinner style: formal Italian evening with elegance.\" # Define the model for the agents model = BedrockModel( model_id=\"amazon.nova-lite-v1:0\", temperature=0.7, max_tokens=3000 ) # Create specialized agents input_router = Agent( model=model, name=\"InputRouter\", system_prompt=ROUTER_INSTRUCTION, ) recipe_creator = Agent( model=model, name=\"RecipeAgent\", system_prompt=RECIPE_CREATOR_INSTRUCTION, ) beverage_suggester = Agent( model=model, name=\"BeverageAgent\", system_prompt=BEVERAGE_SUGGESTOR_INSTRUCTION, ) music_curator = Agent( model=model, name=\"MusicAgent\", system_prompt=MUSIC_CURATOR_INSTRUCTION, ) dinner_planner = Agent( model=model, name=\"DinnerPlanAgent\", system_prompt=DINNER_PLANNER_INSTRUCTION, ) # Build the multi-agent graph builder = GraphBuilder() # Add nodes for each agent builder.add_node(input_router) builder.add_node(recipe_creator) builder.add_node(beverage_suggester) builder.add_node(music_curator) builder.add_node(dinner_planner) # Define dependencies builder.add_edge( \"InputRouter\", \"RecipeAgent\" ) # Router → Recipe (user preference input) builder.add_edge( \"InputRouter\", \"BeverageAgent\" ) # Router → Beverage (user preference input) builder.add_edge( \"RecipeAgent\", \"BeverageAgent\" ) # Recipe → Beverage (recipe-specific input) builder.add_edge( \"InputRouter\", \"MusicAgent\" ) # Router → Music (user preference input) builder.add_edge( \"RecipeAgent\", \"DinnerPlanAgent\" ) # Recipe → Plan (recipe-specific input) builder.add_edge( \"BeverageAgent\", \"DinnerPlanAgent\" ) # Beverage → Plan (beverage-specific input) builder.add_edge( \"MusicAgent\", \"DinnerPlanAgent\" ) # Music → Plan (music-specific input) # Set the entry point/s for the graph (Optional - If not spesified, it will be auto-detected) builder.set_entry_point(\"InputRouter\") graph = builder.build() # Execute the graph with a prompt result = graph(user_query) The other example shows how a single agent can dynamically build and run a multi-agent workflow using the Strands graph tool, without manually constructing a GraphBuilder. \"\"\"Example of graph multi-agent pattern using the graph tool (strands tool package).\"\"\" from strands import Agent from strands.models import BedrockModel from strands_tools import graph GRAPH_AGENT_INSTRUCTION = \"Create a graph of agents to interpret the user's dinner request and dispatch tasks to appropriate agents.\" if __name__ == \"__main__\": user_query = \"Dinner style: formal Italian evening with elegance.\" # Define the model for the agents model = BedrockModel( model_id=\"amazon.nova-lite-v1:0\", temperature=0.7, max_tokens=3000 ) agent = Agent(tools=[graph], system_prompt=GRAPH_AGENT_INSTRUCTION) agent(user_query) Conclusion Across these two posts, we’ve seen nine Agentic Pattern — from straightforward workflows to swarm and graph-based systems. The takeaway is simple: choose the pattern that fits the problem. Workflows give you structure and reliability; agents give you flexibility and autonomy; hybrids let you blend both. Use these patterns as a toolbox to build systems that are robust, scalable, and future-ready and remember: the best agentic pattern design is the one that keeps things simple while delivering real impact. References If you haven’t check Part 1 of the blog post series, you can check it on this link: - Part 1: Agentic Patterns 101 with Loka & Strands-Agents"},{"href":"/part-1-agentic-patterns-101-with-loka-strands-agents/","title":"Part 1: Agentic Patterns 101 with Loka & Strands-Agents","description":"These days, Agents are everywhere in daily conversation and it seems everyone wants one. We read or hear about AI Agents, Agentic AI, Agentic Architectures, and Agentic Patterns almost every day. But what do these terms…","abstract":"These days, Agents are everywhere in daily conversation and it seems everyone wants one. We read or hear about AI Agents, Agentic AI, Agentic Architectures, and Agentic Patterns almost every day. But what do these terms…","tags":["Strands Agents","Agentic AI","Generative AI","AI Agents","Amazon Bedrock"],"topics":[],"authors":["Nina Cvetkovska","Petar Kalinovski","Bojan Jakimovski"],"text":"These days, Agents are everywhere in daily conversation and it seems everyone wants one. We read or hear about AI Agents, Agentic AI, Agentic Architectures, and Agentic Patterns almost every day. But what do these terms really mean? How do we design Agentic Systems that are both reliable and powerful? And just as importantly, when are agents the wrong tool for the job? In this short post series, we’ll explore these questions by examining nine common patterns for building AI-powered systems. Some patterns are rooted in structured workflows, while others embrace flexible, autonomous approaches. To ground the discussion, we’ll use Strands-Agents, an open-source SDK from AWS, as our reference framework. The main benefit of Strands is that it is model-agnostic, so you can define an agent using any LLM (cloud-based or local), a system prompt, and a set of tools, while the SDK handles reasoning, planning, and the execution loop. This makes it easy to experiment with both workflow-driven and agent-driven architectures, perfectly illustrating where each pattern excels. Why Do Agentic Patterns Matter? Patterns provide structure to system design. They allow AI applications to grow in capability and complexity without becoming brittle and make it easier to adapt as requirements evolve. A pattern-driven, modular design is far easier to maintain and extend than a one-off build. Patterns also tame the complexity of orchestrating multiple agents, tools, and workflows. Proven templates reduce trial-and-error risk, promote best practices, and establish a shared language among developers. When Should (and Shouldn’t) You Use Agents? Before adding an agent, ask: Do I really need one here? If the problem has a fixed, well-understood solution path, a simple workflow or even a short script will likely be faster, cheaper, and more reliable. Agents introduce flexibility, but that flexibility comes with trade-offs: higher latency, increased compute usage, and potential unpredictability. Agents shine in messy, dynamic, or ambiguous environments, where adaptability and autonomous reasoning are genuine advantages. Quick guide: Workflows: Best for predictability, repeatability, and efficiency. Agents: Best for open-ended, evolving, or uncertain tasks. Even when using agents, keep designs as simple as possible. Overly complex setups can be fragile, hard to debug, and costly to maintain. Because agents can make mistakes, strong error handling, detailed logging, and retry mechanisms are essential — giving the system a chance to recover gracefully. Pattern Overview We’ll explore nine patterns, with some emphasizing the clarity of structured workflows, while others harnessing the autonomy of agentic design, showing how each fits into the broader landscape of AI system architecture. We’ll cover: Sequential Workflow Parallel Workflow LLM Routing Reflection Pattern Pure Python Tools Tools from MCP Servers Agents as Tools (Orchestrator-Workers) Swarm Graph Multi-Agent Pattern In this part of the blog post series, we’ll dive into the first four patterns in detail, leaving the remaining ones for later sections. All of the examples for the patterns can be found on the GitHub repository here. Sequential Workflow Sequential workflow: three Strands agents pass outputs along a chain and call Amazon Bedrock. In a Sequential Workflow (or sometimes called Prompt Chaining), tasks are completed step by step, where each agent’s (LLM’s) output becomes the input for the next. This pattern divides a larger task into a chain of smaller, well-defined steps, ensuring that each stage builds directly on the previous one. It is ideal for processes that follow a predictable, linear progression without branching or parallelization. Characteristics of Sequential Workflow: Fixed, linear sequence of steps Each step depends on the output of the previous step Minimal branching or deviation from the sequence Use Cases & Industries: Structured document generation: Agent 1 (LLM 1) creates an outline, Agent 2 (LLM 2) generates content, and Agent 3 (LLM 3) validates the content against predefined criteria — e.g., in Content Creation for blog posts, marketing copy, or reports. Multi-step data processing: Extract, transform, and summarize information from documents — e.g., in Intelligent Document Processing (IDP) for Healthcare records or Invoices. Research workflow: Agent 1 (LLM 1) collects research references, Agent 2 (LLM 2) synthesizes insights, Agent 3 (LLM 3) formats a report — e.g., in Academic Research or Market Analysis. When to Use / When Not to Use: Use when: Tasks can be broken into discrete, ordered steps with predictable outcomes. Avoid when: Flexibility, parallel processing, or adaptive decision-making is required. Code Example: With strands agents to generate a sequential workflow there are two ways: Pythonic way where we define the sequential workflow as python function or class that resembles a pipeline: \"\"\"Example of a sequential workflow using three agents as a python function (or class) resembeling pipeline\"\"\" from strands import Agent from strands.models import BedrockModel BLOG_PLANNER_INSTRUCTION = \"You are a blog planner. Take the topic that is provided to you and create a detailed outline with 3 sections and key points for each section.\" SECTION_WRITER_INSTRUCTION = \"You are a blog writer. Take the outline provided by the blog planner and expand each section into a detailed paragraph.\" EDITOR_INSTRUCTION = \"You are a professional editor. Improve the following blog draft by fixing grammar, making sentences concise, and ensuring smooth flow.\" def sequential_workflow( blog_planner_agent: Agent, section_writer_agent: Agent, editor_agent: Agent, topic: str, ) -> str: \"\"\" A sequential workflow that involves three agents: 1. Blog planner to create an outline. 2. Section writer to write the blog post based on the outline. 3. Editor to edit the blog post. Args: topic (str): The topic for the blog post. blog_planner_agent (Agent): The agent responsible for creating the blog outline. section_writer_agent (Agent): The agent responsible for writing the blog post. editor_agent (Agent): The agent responsible for editing the blog post. Returns: str: The final edited blog post. \"\"\" print(\"Starting sequential workflow for topic:\", topic) # Step 1: Create a blog outline outline = blog_planner_agent(topic) print(\"Blog outline created:\", outline) # Step 2: Write the blog post based on the outline draft = section_writer_agent(outline) print(\"Blog draft created:\", draft) # Step 3: Edit the blog post final_post = editor_agent(draft) print(\"Final blog post created:\", final_post) return final_post if __name__ == \"__main__\": # Define the model we use for the agents (we want creative response that's why temp is high) bedrock_model = BedrockModel( model_id=\"us.amazon.nova-premier-v1:0\", temperature=0.9, ) # Step 1: Agent that creates a blog outline blog_planner_agent = Agent( model=bedrock_model, system_prompt=BLOG_PLANNER_INSTRUCTION, callback_handler=None, # Optional: You can provide a callback handler for logging or monitoring ) # Step 2: Agent that writes the blog post section_writer_agent = Agent( model=bedrock_model, system_prompt=SECTION_WRITER_INSTRUCTION, callback_handler=None, # Optional: You can provide a callback handler for logging or monitoring ) # Step 3: Agent that edits the blog post editor_agent = Agent( system_prompt=EDITOR_INSTRUCTION, model=bedrock_model, callback_handler=None, # Optional: You can provide a callback handler for logging or monitoring ) # Define the topic for the blog post and create the sequential workflow topic = \"The Future of AI in Content Creation\" final_post = sequential_workflow( blog_planner_agent=blog_planner_agent, section_writer_agent=section_writer_agent, editor_agent=editor_agent, topic=topic, ) print(\"Final blog post created:\", final_post) A strands-agent tool way that easily defines sequential workflow with a predefined tool: \"\"\"Example of a sequential workflow using three agents as a workflow tool (strands-agents-tools)\"\"\" from strands import Agent from strands.models import BedrockModel from strands_tools import workflow BLOG_PLANNER_INSTRUCTION = \"You are a blog planner. Take the topic that is provided to you and create a detailed outline with 3 sections and key points for each section.\" SECTION_WRITER_INSTRUCTION = \"You are a blog writer. Take the outline provided by the blog planner and expand each section into a detailed paragraph.\" EDITOR_INSTRUCTION = \"You are a professional editor. Improve the following blog draft by fixing grammar, making sentences concise, and ensuring smooth flow.\" if __name__ == \"__main__\": # Define the model we use for the agents (we want creative response that's why temp is high) bedrock_model = BedrockModel( model_id=\"us.amazon.nova-premier-v1:0\", temperature=0.9, ) # Create one Agent with one workflow tool blog_agent = Agent(tools=[workflow], model=bedrock_model) # Creating the workflow blog_agent.tool.workflow( action=\"create\", workflow_id=\"blog_agent_workflow\", tasks=[ { \"task_id\": \"blog_planner\", # The unique ID for the Blog Planner agent \"description\": 'Create a detailed outline for the blog post about \"The Future of AI in Content Creation\"', # The description of the task \"system_prompt\": BLOG_PLANNER_INSTRUCTION, # The system prompt for the Blog Planner agent \"priority\": 5, # The priority of the task (higher numbers indicate higher priority) }, { \"task_id\": \"section_writer\", \"description\": \"Expand each section of the outline into a detailed paragraph\", \"dependencies\": [\"blog_planner\"], \"system_prompt\": SECTION_WRITER_INSTRUCTION, \"priority\": 4, }, { \"task_id\": \"editor\", \"description\": \"Edit the blog draft for clarity and conciseness\", \"dependencies\": [\"section_writer\"], \"system_prompt\": EDITOR_INSTRUCTION, \"priority\": 3, }, ], ) # Start the workflow blog_agent.tool.workflow( action=\"start\", workflow_id=\"blog_agent_workflow\", ) # Monitor the workflow progress blog_agent.tool.workflow( action=\"monitor\", workflow_id=\"blog_agent_workflow\", ) Parallel Workflow Parallel workflow: two Strands agents process work concurrently and combine their outputs. In a Parallel Workflow, multiple agents (LLMs) execute tasks simultaneously, often starting from a shared input or from the output of a preceding step. This allows independent subtasks to run in parallel, reducing latency and improving efficiency. The results from parallel agents are typically aggregated or passed to a downstream step for integration. Characteristics of Parallel Workflow: Multiple agents operate concurrently Steps can process shared or partitioned inputs Requires a mechanism to merge or coordinate results Use Cases & Industries: Content enrichment: Agent 1 (LLM 1) drafts an article, while Agent 2 (LLM 2) in parallel checks grammar/style and Agent 3 (LLM 3) performs fact-checking — e.g., in Media & Publishing workflows for news or blog posts. Multi-perspective analysis: Agent 1 (LLM 1) structures a financial report, then Agent 2 (LLM 2) analyzes regulatory risks while Agent 3 (LLM 3) in parallel evaluates market sentiment — e.g., in Finance & Compliance domains. When to Use / When Not to Use: Use when: Subtasks are independent, can safely be run simultaneously, and merging results is straightforward. Avoid when: Steps are highly dependent on each other’s outputs, or when sequencing is critical to correctness. Code Example: With strands-agents the preferred way of implementing Parallel Workflow is to use the workflow tool: \"\"\"Example of parallel workflow using three agents as a workflow tool (strands-agents-tools)\"\"\" from strands import Agent from strands.models import BedrockModel from strands_tools import workflow CEO_INSTRUCTION = \"You are CEO. Your goal is to ensure the company's success and make high-level decisions.\" FINANCE_INSTRUCTION = \"You are finance expert. Always analyze the question and solution from a financial perspective.\" LEGAL_INSTRUCTION = \"You are legal expert. Always analyze the question and solution from a legal perspective.\" if __name__ == \"__main__\": # Define the model we use for the agents bedrock_model = BedrockModel( model_id=\"us.amazon.nova-premier-v1:0\", temperature=0.1, ) # Create one Agent with one workflow tool solution_agent = Agent(tools=[workflow], model=bedrock_model) # Creating the workflow solution_agent.tool.workflow( action=\"create\", workflow_id=\"solution_agent_workflow\", tasks=[ { \"task_id\": \"ceo_agent\", # The unique ID for the CEO Agent \"description\": \"How to increase the efficiency of the team?\", # The description of the task \"system_prompt\": CEO_INSTRUCTION, # The system prompt for the CEO Agent \"priority\": 5, # The priority of the task (higher numbers indicate higher priority) }, { \"task_id\": \"finance_agent\", \"description\": \"Analyze the financial implications of the proposed solutions\", \"dependencies\": [\"ceo_agent\"], \"system_prompt\": FINANCE_INSTRUCTION, \"priority\": 3, }, { \"task_id\": \"legal_agent\", \"description\": \"Ensure all proposed solutions comply with legal regulations\", \"dependencies\": [\"ceo_agent\"], \"system_prompt\": LEGAL_INSTRUCTION, \"priority\": 3, }, ], ) # Start the workflow solution_agent.tool.workflow( action=\"start\", workflow_id=\"solution_agent_workflow\", ) # Monitor the workflow progress solution_agent.tool.workflow( action=\"monitor\", workflow_id=\"solution_agent_workflow\", ) LLM Routing LLM routing pattern: queries are directed to a model suited to their requirements. LLM Routing is used to automatically direct queries to the most appropriate model based on complexity, domain expertise, or computational requirements. Rather than using a single expensive, or inadequate model for all tasks, intelligent routing optimizes both cost and performance by matching query complexity and model capability. Modern AI systems like GPT-5 (In the ChatGPT interface) use routing for automatically choosing between faster models for simple queries and reasoning models for complex problems. With strands-agents, we can implement similar routing patterns explicitly, giving us full control over cost optimization and performance tuning. Characteristics of LLM Routing: Dynamic model selection based on query analysis Cost optimization through appropriate model sizing Performance optimization through complexity matching Centralized routing logic with distributed model execution Continuous learning from routing decisions and outcomes Use Cases & Industries: Software Development Support: Route basic syntax questions to lightweight models (AWS Nova Lite) while directing complex architecture challenges to reasoning models (AWS Nova Pro/Claude) — e.g., in Developer Tooling platforms, Code Assistants, or Technical Documentation systems. Customer Support Systems: Simple FAQ routing to fast models, complex troubleshooting to specialized domain experts — e.g., in SaaS platforms, Enterprise Software, or Technical Support workflows. Financial Analysis: Basic calculations and data retrieval to efficient models, complex risk analysis and regulatory compliance to advanced reasoning models — e.g., in Investment Banking, Risk Management, or Regulatory Reporting. When to Use / When Not to Use: Use when: Query complexity varies significantly, cost optimization is important, or different models have genuinely different capabilities for the domain. Avoid when: All queries require similar complexity levels, routing overhead exceeds benefits, or a single model adequately handles the entire use case spectrum. Code Example: We will use strands-agents for the router and the chosen LLMs. While using a strands-agent for the routing is not necessary, we will use it because it is one of the easiest ways to get structured output: \"\"\"Example of LLM Routing workflow for handling user queries based on complexity.\"\"\" from enum import Enum from pydantic import BaseModel, Field from strands import Agent from strands.models import BedrockModel ROUTER_INSTRUCTION = \"\"\" You are a helpful software development router that can route user queries to the appropriate agent. Based on the user's question, determine the complexity of the query as: simple, complex, or ambiguous. - Simple queries can retrieve factual information but lack reasoning for complex system design. - Complex queries require deeper understanding and reasoning about the system's architecture and design principles. - Ambiguous queries are unclear and may require clarification before they can be properly routed. \"\"\" class RouteType(Enum): \"\"\" Enumeration for the different types of routing that can be applied to a user query. \"\"\" SIMPLE = \"simple\" COMPLEX = \"complex\" AMBIGUOUS = \"ambiguous\" class RouteResponse(BaseModel): \"\"\" Config Model representing the response from the routing process. \"\"\" type: RouteType message: str = Field(..., description=\"The response message\") if __name__ == \"__main__\": \"\"\" Main function to execute the routing process. \"\"\" # User query to be routed user_query = \"What is the difference between == and === in JavaScript?\" # Other example queries: # complex_query = \"Design a microservices architecture for a banking system with regulatory compliance\" # ambiguous_query = \"What is the best way to implement a feature?\" # Initialize the routing model routing_model = BedrockModel( model_id=\"amazon.nova-pro-v1:0\", temperature=0.6, ) # Initialize the router agent router_agent = Agent(model=routing_model, system_prompt=ROUTER_INSTRUCTION) # Get structured response from user query response = router_agent.structured_output(RouteResponse, user_query) # Route the response based on its type # Handle simple response if response.type == RouteType.SIMPLE: print(\"Routing to simple response handler.\") agent = Agent( model=BedrockModel( model_id=\"amazon.nova-lite-v1:0\", temperature=0.9, ), system_prompt=\"You are a fast, efficient assistant for basic programming questions. Provide concise, accurate answers about syntax, commands, and simple explanations.\", ) agent_response = agent(user_query) print(f\" Final response: {agent_response}\") # Handle complex response elif response.type == RouteType.COMPLEX: print(\"Routing to complex response handler.\") agent = Agent( model=BedrockModel( model_id=\"anthropic.claude-sonnet-4-20250514-v1:0\", temperature=0.9, ), system_prompt=\"You are an expert software architect. Analyze complex system design problems, consider trade-offs, and provide detailed architectural guidance with reasoning.\", ) agent_response = agent(user_query) print(f\" Final response: {agent_response}\") # Handle ambiguous response elif response.type == RouteType.AMBIGUOUS: agent = Agent( model=BedrockModel( model_id=\"amazon.nova-pro-v1:0\", temperature=0.9, ), system_prompt=\"You are an ambiguous query handler agent.\", ) agent_response = agent(user_query) print(f\" Final response: {agent_response}\") Reflection Pattern Reflection pattern: an agent revises its output through an iterative feedback loop. Reflection (or Self-Improvement Loop) is an iterative pattern where an agent generates initial output, receives feedback from a judge agent (can be the same agent depending on use case), and then refines its work based on that feedback. This pattern creates a feedback loop that continuously improves the quality of outputs through multiple iterations until the work meets specified criteria or reaches maximum iterations. The pattern mimics human creative processes where initial drafts are refined through critique and revision. Characteristics of Reflection: Iterative improvement through feedback loops Structured feedback mechanisms with clear improvement criteria Quality enhancement through multiple refinement cycles Use Cases & Industries: Creative Content Generation: Initial draft creation followed by critique and refinement for scripts, marketing copy, or creative writing — e.g., in Entertainment Industry, Advertising Agencies, or Content Creation platforms. Code Review and Optimization: Generate code solutions, analyze for bugs/improvements, then refactor based on feedback — e.g., in Software Development, DevOps pipelines, or Automated Code Review systems. Document Review and Editing: Create initial documents, evaluate for clarity/accuracy/compliance, then revise accordingly — e.g., in Legal Document Preparation, Technical Writing, or Regulatory Compliance reporting. Research and Analysis: Generate initial findings, critique methodology and conclusions, then strengthen analysis based on feedback — e.g., in Academic Research, Market Analysis, or Scientific Report generation. When to Use / When Not to Use: Use when: Output quality is critical, iterative improvement adds value, or you need systematic refinement processes with clear evaluation criteria. Avoid when: Simple tasks don’t benefit from iteration, feedback overhead exceeds improvement value, or single pass results are sufficient for the use case. Code Example: For this example, we will demonstrate iterative content improvement through structured feedback. One single strands agent will play dual roles. A content creator and a judge providing feedback. \"\"\"Example of Reflection Pattern for iterative improvement of screenwriting.\"\"\" from pydantic import BaseModel, Field from strands import Agent from strands.models import BedrockModel class JudgeOutput(BaseModel): \"\"\" Model representing the feedback assessment from the judge agent. \"\"\" needs_improvement: bool = Field( ..., description=\"Indicates if the screenwriting needs improvement.\" ) feedback: str = Field(..., description=\"Feedback on the agent's screenwriting.\") if __name__ == \"__main__\": \"\"\" Main entry point for the screenwriting assistant. \"\"\" # Definining Agent agent = Agent( model=BedrockModel( model_id=\"amazon.nova-pro-v1:0\", temperature=0.9, ), system_prompt=\"You are a screenwriting assistant. Help users create scripts, dialogues, and storylines. Critique existing works when asked to and provide suggestions for improvement.\", ) # User query user_query = \"Write a dialogue between two characters. It needs to be a gripping thrilling scene.\" # Get initial screenwriting screenwriting = agent(user_query) # Run reflection_loop iteration = 1 max_iterations = 3 while iteration <= max_iterations: # Get feedback feedback_query = ( \"Please check this dialogue, and unless it's perfect, provide feedback: \" + str(screenwriting) ) feedback = agent.structured_output(JudgeOutput, feedback_query) # Check if feedback is needed if not feedback.needs_improvement: print(\"No feedback provided. Ending the loop.\") break print(\"User feedback received. Processing...\") # Adding feedback to screenwriting iteration screenwriting_feedback = ( \"Make this screenwriting better: \" + str(screenwriting) + \"\\n With the following feedback: \" + feedback.feedback ) screenwriting = agent(screenwriting_feedback) iteration += 1 Wrapping Up So far, we’ve walked through the first four patterns : Sequential Workflow, Parallel Workflow, LLM Routing, and Reflection. Each of these highlights a different dimension of how we can structure AI systems, from simple ordered pipelines to adaptive feedback-driven designs. What ties them together is that they provide clarity and control: workflows ensure determinism, routing adds adaptability, and reflection brings in self-improvement loops. Together, they form the foundation for building more advanced architectures. In the next part of this series, we’ll move beyond foundational workflows and look at tool-based and multi-agent patterns. These unlock even more flexibility, allowing systems to tap into external capabilities, collaborate through agents, and scale into complex, emergent behaviors. Stay tuned -we’ll explore how Pure Python Tools, MCP Server Tools, Agents as Tools, Swarm, and the Graph Multi-Agent Pattern push the boundaries of what AI systems can do !"},{"href":"/flattening-the-curve-with-nextflow-building-a-scalable-and-reproducible-bioinformatic-workflow-for/","title":"Flattening the Curve with Nextflow: Building a Scalable and Reproducible Bioinformatic Workflow for MITNANEX","description":"Loka’s participation in the recent nf-core hackathon in Medellín, Colombia, culminated in the successful development of MITNANEX, a pipeline designed to extract and assemble mitochondrial genomes, identify and annotate…","abstract":"Loka’s participation in the recent nf-core hackathon in Medellín, Colombia, culminated in the successful development of MITNANEX, a pipeline designed to extract and assemble mitochondrial genomes, identify and annotate…","tags":["Bioinformatics","Data Engineering","Nextflow","Oxford Nanopore","Genomics"],"topics":[],"authors":["Jelena Pejovic","José Ribón","Andrés Sacre","Federico Rueda","Nicolás Franco","Javier Dominguez","Juliana Silva"],"text":"Loka’s participation in the recent nf-core hackathon in Medellín, Colombia, culminated in the successful development of MITNANEX, a pipeline designed to extract and assemble mitochondrial genomes, identify and annotate variants and facilitate comprehensive mitochondrial genome annotation. By leveraging nf-core modules and the workflow orchestration tool Nextflow, our team built a solution to explore mtDNA variants potentially linked to specific traits in the human organism. The results of our hackathon efforts streamline MITNANEX’s path to answering its key research question: Do certain mitochondrial variants correlate with exceptional longevity in humans? The nf-core Hackathon The hackathon was part of a globally coordinated initiative led by nf-core and Seqera designed to empower bioinformaticians, developers and researchers to build modular workflows using Nextflow. Loka joined forces with EAFIT University to bring this opportunity to Medellín, opening a space where students and professionals could co-create, test and contribute directly to the nf-core ecosystem. A modular approach allowed multidisciplinary subteams to focus on specific components that were then seamlessly integrated, fostering valuable knowledge sharing between participants of diverse backgrounds. Our collaboration led to proposing MITNANEX as a future nf-core module, with a roadmap defined by Loka and EAFIT. It demonstrated how synergies between academia and industry can lay the foundations for new research and accelerate innovation in the bioinformatics community. The Nextflow & nf-core Framework Nextflow has changed research and development in bioinformatics and revolutionized the way computational pipelines are built, shared and executed by enabling smooth reproducibility and scalability across platforms. It supports scalability, reusability, portability and efficiency while processing large amounts of data across different infrastructures and tools. This is where nf-core comes in: a collection of well-maintained, community-curated pipelines and modules that follow best practices and are designed for portability and reuse out of the box. With nf-core modules, it’s easier to plug in standardized components without the need to build everything from scratch, saving time and potential error. It also means that the same code can run across different environments with easy setup. Users benefit from workflows that are not only reproducible and portable but also easy to implement and well-documented. Developers, on the other hand, can utilize nf-core’s readymade templates and tools to simplify the creation of robust Nextflow pipelines. This is possible thanks to nf-core’s vibrant and collaborative community. Introducing MITNANEX MITNANEX (MITochondrial NANopore reads EXtractor) arose from the observation that many cell processes tied to aging, from oxidative stress to metabolic efficiency, have been traced back to the mitochondria. By analyzing the mitochondrial genomes of people aged 100 and above, researchers aim to uncover shared mutations, deletions or even epigenetic signatures that could explain their extended cellular vitality. Processing mitochondrial genomes involves several steps, especially when working with Oxford Nanopore Technologies (ONT) data. Oxford Nanopore reads present unique challenges due to their higher error rates compared to Illumina short reads, which can lead to inaccuracies in base calling. However, their longer read lengths allow for the assembly of more complex genomes, such as mitochondria, in a single pass, making them ideal for de novo assembly where no reference genome is available or where reference bias must be avoided, despite the need for specialized error-correction tools. Currently there are few pipelines specifically designed to process mitochondrial genomes directly from whole genome sequencing (WGS) data. MITNANEX Case Study MITNANEX is a pipeline designed to de novo extract mitochondrial reads from whole genome sequencing (WGS) data generated by Oxford Nanopore, without the need for seeds or references. It produces a draft assembly of the mitochondrial genome using the assembler Flye. MITNANEX workflow stages from preprocessing through variant calling and VCF post-processing. Overall, MITNANEX streamlines mitochondrial genome recovery with these efficient and integrated steps: 1. Preprocessing & Filtering Chopper: Processes FASTQ data to remove unwanted reads (filtering). 2. Alignment or Assembly (Two paths) a) Reference-based alignment: Clean reads → minimap2 (aligned to mitochondrial reference) Aligned reads → samtools bam2fq to extract mitochondrial reads Extracted reads → MetaFlye for mitochondrial de novo assembly b) Direct de novo path: Clean reads → De-novo assembly → filtered by seqkit → De-novo mitochondria 3. Annotation If a reference GFF is available: Liftoff can transfer annotations If not: Proceed with de novo annotation on assembled genome 4. Read Mapping & Variant Calling Assembled genome → minimap2 for read mapping GATK Mutect2 → variant calling GATK FilterMutectCalls → variant filtering Generates VCF file 5. VCF Post-processing Annotate with Bedtools and Mitomaster So far, MITNANEX has been successfully tested on fungal mitogenomes, achieving near-perfect results: 100% query coverage and over 99% identity when validated via blast against NCBI references. The Loka team is planning more extensive benchmarking but these early results suggest strong performance, especially considering the challenges of working with noisy Oxford Nanopore data. Because it’s built with Nextflow, the pipeline is easy to run, share and adapt to new datasets or environments, making it a solid foundation for future development. Compared to more manual or ad hoc approaches, MITNANEX offers a solution that’s more reproducible and modular and can be quickly extended for other organisms or research goals. Next Steps Looking ahead, we plan to refine MITNANEX into an official nf-core module, share it with the broader scientific audience and make sure our work is cycling back to the nf-core and Nextflow community. By embracing the spirit of open source — creating something valuable together and letting it evolve as others build upon it — we hope to accelerate discoveries and unlock new insights into human aging."},{"href":"/how-to-transition-from-xml-android-view-to-jetpack-compose-view/","title":"How to Transition from XML (Android View) to Jetpack Compose View","subtitle":"Moving from XML to Jetpack Compose helps developers write cleaner, faster and more modern UI code — essential for staying up to date with Android’s best practices.","description":"Moving from XML to Jetpack Compose helps developers write cleaner, faster and more modern UI code — essential for staying up to date with Android’s best practices.","abstract":"Moving from XML to Jetpack Compose helps developers write cleaner, faster and more modern UI code — essential for staying up to date with Android’s best practices.","tags":["Android","Jetpack Compose","Android Views"],"topics":[],"authors":["Gabriel Menezes da Silva"],"text":"For many years, Android View (XML) was the sole way of building layouts in Android. In 2021, Google released Jetpack Compose, which is now the method most recommended by Google for building layouts. Android View uses the syntax of XML; Compose uses a syntax similar to React. Right now XML is still widely used for several reasons: Longevity: Jetpack Compose is very new, while the XML approach has been used since the creation of Android frameworks, making it well-established and familiar for many developers. Developer familiarity: More developers know Android XML than Jetpack Compose. Legacy projects: Many existing Android projects are built using XML layouts, so understanding it is still a necessity. But Jetpack Compose offers a lot of advantages over XML: Declarative UI: It’s easier to describe and understand how the UI works. Kotlin-First: Compose is built using Kotlin, so it leverages language features and makes performance better. Preview and tooling: Compose offers powerful preview features in Android Studio, allowing developers to see UI changes in real time without running the app. Simplified Code: Compose requires less code compared to XML layouts, resulting in more concise and readable UI definitions. In the ideal world, we could transform all of our XML code to Jetpack Compose to harness the benefits of the newer methodology. In reality this transition can create a lot of problems, so it must be done slowly. Below are instructions for managing this gradual transition using both approaches at the same time. This way you can leverage all the benefits of Jetpack Compose while simultaneously delivering features for your clients. Development Here’s a simple login screen built using the old XML approach: <?xml version=\"1.0\" encoding=\"utf-8\"?> <LinearLayout xmlns:android=\"<http://schemas.android.com/apk/res/android>\" android:id=\"@+id/rootLayout\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" android:padding=\"24dp\" android:gravity=\"center\" android:background=\"#FFFFFF\"> <EditText android:id=\"@+id/emailInput\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:hint=\"@string/email\" android:inputType=\"textEmailAddress\" android:padding=\"12dp\" android:background=\"@android:drawable/edit_text\" /> <EditText android:id=\"@+id/passwordInput\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:hint=\"@string/password\" android:inputType=\"textPassword\" android:padding=\"12dp\" android:layout_marginTop=\"12dp\" android:background=\"@android:drawable/edit_text\" /> <Button android:id=\"@+id/loginButton\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"@string/login\" android:layout_marginTop=\"20dp\" android:backgroundTint=\"@android:color/holo_blue_light\" android:textColor=\"#FFFFFF\" /> </LinearLayout> Login Screen Let’s say that the designers of the application requested an alert to inform users that their password is incorrect. This alert will be used throughout the app, making it the perfect opportunity to start the migration to Jetpack Compose. Open your Android Studio and let’s start with the Compose alert component. First create a Kotlin file: 2. Select the option “File” and for the name of the component, you can put “ErrorAlertDialog”. 3. Copy and paste the code below: package com.example.xmljetpackcomposetransition import android.util.Log import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.testTag import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp @Composable fun ErrorAlertDialog( message: String, onDismiss: () -> Unit, ) { Box( modifier = Modifier .fillMaxWidth() .padding(16.dp) ) { Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxWidth()) { Text( text = message, color = Color.Red, style = MaterialTheme.typography.bodyLarge, textAlign = TextAlign.Center ) Spacer(modifier = Modifier.height(12.dp)) Button(onClick = onDismiss, colors = ButtonDefaults.buttonColors( containerColor = Color.Red, contentColor = Color.White )) { Text(\"OK\") } } } } @Preview(showBackground = true) @Composable fun PreviewErrorAlertDialog() { MaterialTheme { ErrorAlertDialog( message = \"This is a preview error.\", onDismiss = {} // No-op for preview ) } Integration with the Existing XML Component First you have to add the ComposeView in the XML component like it’s shown here: <?xml version=\"1.0\" encoding=\"utf-8\"?> <LinearLayout xmlns:android=\"<http://schemas.android.com/apk/res/android>\" android:id=\"@+id/rootLayout\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" android:padding=\"24dp\" android:gravity=\"center\" android:background=\"#FFFFFF\"> <EditText android:id=\"@+id/emailInput\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:hint=\"@string/email\" android:inputType=\"textEmailAddress\" android:padding=\"12dp\" android:background=\"@android:drawable/edit_text\" /> <EditText android:id=\"@+id/passwordInput\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:hint=\"@string/password\" android:inputType=\"textPassword\" android:padding=\"12dp\" android:layout_marginTop=\"12dp\" android:background=\"@android:drawable/edit_text\" /> <Button android:id=\"@+id/loginButton\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"@string/login\" android:layout_marginTop=\"20dp\" android:backgroundTint=\"@android:color/holo_blue_light\" android:textColor=\"#FFFFFF\" /> <!-- Add this --> <androidx.compose.ui.platform.ComposeView android:id=\"@+id/composeView\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:visibility=\"gone\" /> </LinearLayout> In the MainActivity file you just have to add the following code. There are some comments in the in the code for better understanding of what’s happening. package com.example.xmljetpackcomposetransition import android.os.Bundle import android.util.Log import android.view.View import android.widget.Button import android.widget.EditText import android.widget.Toast import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.compose.material3.MaterialTheme import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.ViewCompositionStrategy import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat class MainActivity : AppCompatActivity() { private lateinit var emailInput: EditText private lateinit var passwordInput: EditText private lateinit var loginButton: Button private lateinit var composeView: ComposeView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) enableEdgeToEdge() emailInput = findViewById(R.id.emailInput) passwordInput = findViewById(R.id.passwordInput) loginButton = findViewById(R.id.loginButton) /* This part you're setting the component you created as a content of your XML compose view, very straight forward. */ composeView = findViewById(R.id.composeView) composeView.setContent { MaterialTheme { ErrorAlertDialog( message = \"Password cannot be empty.\", onDismiss = { composeView.visibility = View.GONE } ) } } loginButton.setOnClickListener { val password = passwordInput.text.toString() if (password.isBlank()) { /* Here I'm setting the compose view visibility to visible, so the user will see the compose view component. */ showComposeErrorDialog() } else { Toast.makeText(this, \"Login successful\", Toast.LENGTH_SHORT).show() } } } private fun showComposeErrorDialog() { composeView.visibility = View.VISIBLE } } Your application should work like this: Video And that’s it! By applying this methodology, you can start to enjoy the benefits of Jetpack Compose while working in an XML project."},{"href":"/aws-s3-browser-will-save-you-time/","title":"AWS S3 browser will save you time","subtitle":"Simple interface for data stored in S3","description":"Simple interface for data stored in S3","abstract":"Simple interface for data stored in S3","tags":["AWS","S3","Amplify"],"topics":[],"authors":["Dragan Savevski"],"text":"The S3 browser makes it easy to add secure, scalable file management to your app in minutes. Easy-to-use APIs and pre-made UI elements let developers create secure and scalable file storage experiences without dealing with the complexities of cloud infrastructure, and with built-in authentication and flexible customisation options ranging from theming to advanced UI hooks, you can tailor the experience to your needs. For even more control, you can use Amplify’s storage APIs directly to build custom solutions. In the following sections, we’ll walk through how to set it up, tailor it to your needs, and even create a custom interface from scratch if desired. By the end of this piece you’ll be up and running with your own storage browser. Setting up the S3 browser The quickest way to set up the S3 browser is to use the Amplify template which creates S3 buckets for you. This is the template we’ll use in this guide. (If you’d rather work with an existing bucket(s), another template does exactly that). Deploying this template requires an AWS account with appropriate permissions. See this setup guide for more details. Both of these templates leverage: AWS S3 for encrypted file storage AWS Cognito for user authentication AWS IAM for granular access control React + Vite for a modern frontend architecture Deploying the template We have our template that renders the S3 browser, let’s follow these short steps to deploy it. Video Deploying with AWS Amplify After the deployment is done we are taken to a screen where we can see the URL for our application. Application URL After opening the application URL we are taken to a login screen. That’s because the template comes with authentication features out-of-the-box, making the storage browser secure by default. If you like, you can customise the sign-up/in requirements for your specific needs (for example, only allowing certain users or even disabling authentication altogether). Let’s create a user by signing up and then sign in to the application. Upon signing in, you will see two buckets with three folders each, as configured in the sample template. Notice the familiar file-system-like interface that the S3 browser offers for you users. This configuration sets up the buckets’ folders and their permissions. For more on bucket authorisation rules, check the official Amplify docs. Storage browser component powered by the Amplify UI library And that’s it! With this setup you get enterprise-ready file browsing interface running in almost no time! How to customise the S3 browser There are multiple ways to customise the storage browser for better branding and user experience purposes: The simplest one is to override the Amplify UI theme. In addition to overriding theme, plain CSS can be used to adapt the style of the components. All the design tokens defined in the Amplify theme are CSS variables that can be overridden. The storage browser is made of composable components which can be reordered and customised. This can be achieved with the help of the exposed hooks that have access to the storage browser’s internal state and event handlers. (e.g., Hide the upload button for users that have only read access) Custom-made storage browser from scratch if prebuilt components don’t fit your requirements. While the storage browser component is powerful, sometimes you need complete control over the UI/UX or require features not offered out of the box. In such cases, you can use the underlying Amplify storage module directly. Plain CSS customisation A plain CSS file containing rules that target the Amplify static classes is powerful enough to satisfy many styling requirements. As an example, we can change the title font and the table’s border radius. In the template in App.css add the following CSS code: .amplify-storage-browser__data-table { border-radius: 2rem; } .amplify-storage-browser__title { font-weight: bold; font-family: monospace; } Executenpm run dev and you are ready for local development. Through the Chrome dev tools discover the classes that you seek and adapt them to your liking. ! Beware that plain CSS styles are global and will target multiple instances of the component! Taking advantage of the composable components What if you didn’t need a full-blown table but only a simple listing of the S3 buckets. This can easily be achieved by using the hooks exposed from the storage browser component: function LocationsView() { const state = useView('Locations'); return ( <Grid templateColumns=\"1fr 1fr 1fr\" gap=\"6px\" padding=\"20px\"> {state.pageItems.map((location) => { return ( <Card key={location.id} variation=\"outlined\"> <Flex alignItems=\"center\" justifyContent=\"space-around\" height=\"100%\"> <Heading level={6} flex=\"1\"> {location.prefix} </Heading> <Badge color=\"font.tertiary\" fontWeight=\"normal\"> {location.permissions.join(', ')} </Badge> </Flex> </Card> ); })} </Grid> ); } Customised view of the bucket list By using useView('Locations') we can get access to the internal state of the storage browser. Besides the locations view, you can also customise the location detail, upload, copy, create, and delete. Without the Amplify UI library Maybe you already are using some kind of component library, and you just don’t want to add another dependency. In that case, building something from scratch is a valid approach. Let’s just say we want to build a simple medical file system that categorises some files. The Amplify storage module offers these API endpoints. In this case, we need just the list endpoint. function LocationsViewCustom() { const [locations, setLocations] = useState<{ path?: string }[]>([]); const labResults = locations.filter((location) => location.path?.includes('lab-results')); const clinicalNotes = locations.filter((location) => location.path?.includes('clinical-notes')); useEffect(() => { list({ path: 'public/', options: { bucket: 'myStorageBucket', }, }).then((res) => { setLocations(res.items as { path?: string }[]); }); }, []); return ( <Flex direction=\"column\" padding=\"medium\" width=\"50%\" margin=\"0 auto\"> <Tabs defaultValue=\"lab-results\" items={[ { label: 'Lab results', value: 'lab-results', content: labResults.map((location) => { return ( <Flex key={location.path} backgroundColor=\"white\" marginBlock=\"6px\" padding=\"6px\"> <Text textAlign=\"start\">{location.path}</Text> </Flex> ); }), }, { label: 'Clinical notes', value: 'clinical-notes', content: clinicalNotes.map((location) => { return ( <Flex key={location.path} backgroundColor=\"white\" marginBlock=\"6px\" padding=\"6px\"> <Text textAlign=\"start\">{location.path}</Text> </Flex> ); }), }, ]} /> </Flex> ); } Here we are listing the public folder of the bucket named myStorageBucket. ! Make sure you have the Amplify library installed! If you’ve started with the templated suggested at the beginning that would be the case, otherwise run npm install aws-amplify. Simple medical file system The takeaway Whether you use the prebuilt components or go fully custom, Amplify vastly simplifies cloud file storage browsing so you can focus on building great features for your users."},{"href":"/part-4-benchmarking-deepseek-cost-performance-and-business-use-cases-on-aws/","title":"Part 4: Benchmarking DeepSeek Cost, Performance and Business Use Cases on AWS","subtitle":"Harnessing Open Source AI on AWS","description":"A DeepSeek benchmark on AWS that compares cost, performance, and deployment choices for business workloads using open-weight models.","abstract":"A small GSM8K latency benchmark comparing DeepSeek-R1 Distill Llama 8B deployment paths on Bedrock, SageMaker, and Inferentia2 EC2.","tags":["AI","Generative AI","DeepSeek","Open Source","AWS"],"topics":["inference","benchmarks"],"authors":["Crhistian Cardona","Bojan Jakimovski"],"text":"We began this series on DeepSeek-R1 models on AWS by exploring the model’s general characteristics and how it fits within the current LLM and GenAI ecosystem. We then moved on to practical deployment, starting with AWS Bedrock, where we highlighted its special features, followed by a more flexible setup using AWS SageMaker by utilizing ML instances based on Nvidia GPUs and finally deployed it on EC2 Inferentia2-based instances for optimized performance. This journey has taken us from theory to hands-on deployment, showcasing different AWS environments that each bring distinct characteristics and capabilities. Now we ask perhaps the most important questions of all: How do these models align with real business use cases? And how do we select the most suitable DeepSeek distilled model based on business needs? In this final post, we will address these questions by: Exploring benchmarks for DeepSeek models, including latency comparisons and other key performance metrics across different deployment options discussed in previous posts. Defining common business use cases and evaluating which models, both from DeepSeek and other available AWS models best fit each scenario. Breaking down selection criteria, considering cost, performance, capabilities and complexity for each use case. Our goal is not to provide a rigid manual for solving a single use case but rather to present a structured approach to analyzing business needs and selecting the most appropriate model. By the end of this final entry to the series you’ll have a clear framework for making informed AI deployment decisions based on your specific requirements. Let’s dive in! Benchmarking: Performance Across AWS Deployments To evaluate performance across different AWS environments, we conducted simple benchmarking using the first 20 sample prompts from the classical OpenAI’s benchmark dataset for reasoning, GSM8k, because we are testing the DeepSeek-R1 Distill Llama 8B model. Keep in mind that these results will be appropriate for all open-source models of similar sizes. These prompts were applied to models deployed on Amazon Bedrock, AWS SageMaker (utilizing ML instances based on Nvidia GPUs, ml.g6.2xlarge) and pure EC2 instances (utilizing the latest Inferentia2 chips called inf2.8xlarge). Each sample prompt first was used to trigger a cold start of the model by doing three runs which are not used for calculating the metrics and then we ran five more runs of the same prompt which are used to calculate the metrics that are utilized in this benchmarking process Our benchmarking dataset captures system performance metrics, focusing on response times and variability across different endpoints. Key metrics include: Average Latency (ms): Mean response time in milliseconds 50th Percentile (Median) Latency (ms): The middle value in response times 95th Percentile Latency (ms): High-end response latency Minimum and Maximum Recorded Latencies (ms): Performance variability Standard Deviation (ms): Measure of response time variability, indicating consistency We also analyzed prompt and response characteristics such as input length, response length and the actual generated response to see if the model returns the expected response independent of the service on which it is deployed. Figure 1. Average Latency per Service The benchmark results showcased on the Figure 1 reveal that Bedrock delivers the lowest average latency at approximately 10,975 ms, significantly outperforming both SageMaker at about 32,339 ms and EC2 at roughly 53,125 ms. This suggests that the deployment through Bedrock’s Custom Model Import provides a quicker overall response, potentially offering a better experience for applications where latency is a critical factor. A deeper look into the detailed latency metrics from Figure 2 further underscores these observations. The P50 latencies show that Bedrock has a median latency of 6,137 ms, which is much lower than SageMaker’s 26,212 ms and EC2’s 59,882 ms, reinforcing Bedrock’s consistent performance. Additionally, the P95 values reveal that while all services experience higher latencies under peak conditions, Bedrock remains relatively lower at 21,904 ms compared to the much higher values for SageMaker (55,800 ms) and EC2 (76,853 ms). The range between the minimum and maximum latencies also illustrates that Bedrock has a narrower performance band from about 2,047 ms to 41,984 ms whereas SageMaker and EC2 display wider ranges, with particularly notable extremes on SageMaker, indicating occasional severe delays. Examining the variability in response times shown in the Figure 3, Bedrock again appears to be the most consistent, with a standard deviation of about 5,971 ms compared to SageMaker’s 16,964 ms and EC2’s 18,867 ms. Lower variability in Bedrock’s latency indicates a more stable performance, while the higher standard deviations seen in SageMaker and EC2 point to greater fluctuations that could lead to occasional performance hiccups. Figure 2. P50 Latency, P95 Latency, Min Latency and Max Latency per Service Figure 3. The standard deviation of latency between services When performance consistency and minimal latency are paramount, especially in applications requiring near real-time responses, AWS Bedrock emerges as the optimal choice. Its deployment through Custom Model Import consistently delivers the lowest average latency (approximately 10,975 ms) and exhibits relatively tight response variability. This makes Bedrock highly suitable for user-facing applications, interactive services or scenarios where a predictable response time is critical. AWS SageMaker, deployed on GPU-backed ml.g6.2xlarge instances, offers significant benefits for workloads that demand intensive computation and GPU acceleration. Although its average latency is higher (around 32,339 ms) with more variability, SageMaker is ideal for training, fine-tuning or serving models that require robust computational resources. Its flexibility in handling complex, resource-demanding tasks makes it a better fit for development environments and scenarios where GPU-optimized performance is more important than ultra-low latency. For use cases where cost efficiency or large-scale batch processing is the priority rather than immediate response times, leveraging pure EC2 instances equipped with the latest Inferentia2 chips (inf2.8xlarge) can be justified. Despite having the highest average latency (about 53,125 ms) and broader variability, this option may be well-suited for background processing or non-interactive applications where throughput and cost savings outweigh the need for rapid responses. Calculating: Costs Across AWS Deployments Beyond performance, we also incorporated cost analysis for each deployment setup, detailing instance types used and associated pricing. This cost-performance comparison is particularly relevant for the next section, where we explore real-world use cases and benchmark these results against other models available in AWS environments (Figure 4). This approach provides a practical perspective on both efficiency and cost-effectiveness, aiding in informed decision-making for AI model deployment. Model Name Recommended Nvidia Instance Nvidia Cost Inferentia2 Instance Inferentia2 Cost CMU (Bedrock) Bedrock Cost meta-llama/Llama-3.2-1B g6.xlarge $0.8048/hr inf2.xlarge $0.7582/hr 1 $4.71/hr meta-llama/Llama-3.2-3B g6.xlarge $0.8048/hr inf2.xlarge $0.7582/hr 1 $4.71/hr deepseek-ai/DeepSeek-R1-Distill-Llama-8B g6.8xlarge $2.014/hr inf2.8xlarge $1.968/hr 2 $9.42/hr meta-llama/Llama-3.1-8B g6.8xlarge $2.014/hr inf2.8xlarge $1.968/hr 2 $9.42/hr meta-llama/Llama-3.3-70B-Instruct g6.48xlarge $13.350/hr inf2.48xlarge $12.981/hr 8 $37.68/hr deepseek-ai/DeepSeek-R1-Distill-Llama-70B g6.48xlarge $13.350/hr inf2.48xlarge $12.981/hr 8 $37.68/hr Figure 4. Cost analysis of deployment different size models on different AWS Services The cost analysis reveals interesting tradeoffs between direct instance deployments (using Nvidia‐ or Inferentia2‐based instances) and AWS Bedrock’s managed Custom Model Unit (CMU) pricing. Similar to the performance analysis, the data shows that the relative cost differences vary with model size and complexity. For models like meta-llama/Llama-3.2–1B and Llama-3.2–3B, the recommended Nvidia-based instance (g6.xlarge) costs about $0.8048/hr, while the corresponding Inferentia2 instance (inf2.xlarge) comes in slightly lower at $0.7582/hr. In contrast, AWS Bedrock requires 1 CMU at $4.71/hr — roughly a sixfold premium compared to the hardware options. This indicates that for smaller models, direct deployments on GPUs or Inferentia2 chips are more cost-efficient even though Bedrock may offer additional benefits in terms of managed services and performance consistency. Moving to the 8B model category (deepseek-ai/DeepSeek-R1-Distill-Llama-8B and meta-llama/Llama-3.1–8B), the recommended instance shifts to a more powerful g6.8xlarge, costing around $2.014/hr for Nvidia and $1.968/hr for Inferentia2. Here, Bedrock’s pricing jumps to 2 CMU at $9.42/hr. Although the absolute cost difference is higher for Bedrock, the multiplier compared to direct hardware deployment decreases to about 4.7 times. This narrowing gap suggests that as model size increases, the relative premium for Bedrock diminishes, potentially making it a more attractive option when considering factors beyond cost alone. For the largest models, such as meta-llama/Llama-3.3–70B-Instruct and deepseek-ai/DeepSeek-R1-Distill-Llama-70B, the recommended instances are significantly more powerful, g6.48xlarge for Nvidia at $13.350/hr and inf2.48xlarge for Inferentia2 at $12.981/hr. Meanwhile, Bedrock’s requirement scales to 8 CMU at $37.68/hr. At this scale, the cost multiplier for Bedrock relative to direct deployments drops to approximately 2.8–2.9x. This reduction in the relative cost premium suggests that for high-end, computationally intensive models, the managed service and streamlined operations provided by Bedrock could justify the higher hourly rate. The cost difference between Nvidia-based and Inferentia2-based instances is marginal, with Inferentia2 generally offering a slight cost advantage. Both are attractive for scenarios where minimizing operational costs is critical, especially for lower-latency, real-time applications. While Bedrock incurs a premium especially for smaller models the gap narrows significantly as model complexity increases. For larger models, the managed service benefits and potential performance consistency improvements may well offset the higher cost, making Bedrock a compelling option when ease of use and operational efficiency are prioritized. Over the past few weeks, AWS has made significant strides in expanding Bedrock’s capabilities. Not only is DeepSeek now available as a JumpStart-imported model, but it’s also fully integrated into Bedrock as a fully managed, serverless model, which is ready to use out of the box. As we’ve demonstrated throughout this series, these models can also be deployed on external infrastructure using SageMaker, offering flexibility for more advanced or customized use cases. One of the most compelling aspects of DeepSeek on Bedrock is its affordable pricing: currently around $0.00135 per 1K input tokens and $0.0054 per 1K output tokens. This positions DeepSeek as a cost-effective option for a wide range of applications from internal tools and chatbots to large-scale enterprise analytics making it easier than ever to build with generative AI at scale. In summary, the choice between these deployment methods hinges on the specific requirements of the application. For cost-sensitive or batch processing scenarios, the relatively lower hourly rates of Nvidia or Inferentia2 instances are advantageous. However, for applications where performance consistency, ease of deployment and managed service benefits are critical particularly with larger models, AWS Bedrock’s pricing becomes more competitive despite its higher nominal cost. Choosing the Right GenAI Model for Your Use Case: A Practical Guide As businesses increasingly integrate Generative AI (GenAI) into their workflows, selecting the right model for the job is critical. However, several factors must be considered to ensure feasibility and optimal performance for specific use cases. When matching a GenAI model to a business problem, we need to assess key factors such as: Cost: Budget constraints and operational expenses Speed: How quickly responses are needed Model Capabilities: Performance level required for the problem’s complexity Problem Scope: The depth and nature of the challenge at hand With the release of new models like DeepSeek-R1 models, Llama models, Gemma Models, etc, businesses now have more options than ever. These models offer expanded context windows, cost-efficient lightweight versions and high-performance alternatives, making it easier to find a model that aligns with specific business and technical needs. To guide decision-making, we will focus on models that are readily deployable on AWS, using Amazon Bedrock, SageMaker JumpStart, EC2 and inference instances. Two Key Considerations for Model Selection When selecting a GenAI model, we can categorize the decision-making process into two key dimensions. Matching the Model to the Use Case Different models excel in different business scenarios. Below are five primary applications of GenAI Case 1–Enterprise Applications: Customer support, business intelligence and financial analysis Case 2–Research & Scientific Computing: Complex reasoning, mathematical problem-solving and multilingual tasks Case 3–Conversational AI & Chatbots: Customer service bots, virtual assistants and real-time interactions Case 4–Content Generation & Creative AI: Marketing, blog writing, code generation and document processing Case 5–Multimodal AI: Processing and generating text, images, videos, code and speech Choosing the Right Model Based on Complexity & Capability Models can be categorized into three tiers based on size (parameters) and performance. Small Models: Lightweight, cost-efficient and suitable for simple tasks. Medium Models: Balanced performance, optimized for general business applications. Large Models: Designed for advanced reasoning, deep learning tasks and multimodal capabilities. By combining these two perspectives matching the problem to the model’s capabilities, we can streamline model selection, ensuring the best fit for a given business challenge while optimizing for performance, cost, and deployment feasibility. Model Name Parameters Context Window HumanEval (Coding) MATH-500 MMLU-PRO Appropriate Use Cases Model Size meta-llama/Llama-3.2-1B 1 Billion 128k 40.00% 14.00% 20.00% Basic text generation, simple summarization, lightweight chatbots, and non-critical content creation Small meta-llama/Llama-3.2-3B 3 Billion 128k 56.00% 49.00% 35.00% Entry-level coding assistance, basic Q&A, simple educational support, and low-stakes creative writing Small deepseek-ai/DeepSeek-R1-Distill-Llama-8B 8 Billion 128k 67.00% 52.00% 48.00% Moderate coding support, routine quantitative reasoning, and research assistance for mid-level applications Medium meta-llama/Llama-3.1-8B 8 Billion 128k 84.00% 77.00% 54.00% Advanced code generation and debugging, academic tutoring in math and logic, and professional conversational agents Medium meta-llama/Llama-3.3-70B-Instruct 70 Billion 128k 86.00% 85.00% 71.00% High-quality coding, complex quantitative problem-solving, enterprise-grade research, and detailed content creation Large deepseek-ai/DeepSeek-R1-Distill-Llama-70B 70 Billion 128k 97.00% 94.00% 80.00% Cutting-edge coding assistance, expert-level mathematical reasoning, critical decision support, and advanced research tasks Large Figure 5. Different size models and their use-cases Final Thoughts & Conclusion Throughout this series, we’ve explored how DeepSeek-R1 models (or any open-source model) can be deployed across AWS services Bedrock, SageMaker and EC2, each offering distinct trade-offs in performance, cost and flexibility. By benchmarking these environments and analyzing real-world use cases, we’ve outlined actionable insights to guide deployment decisions. AWS Bedrock is the best choice for real-time, low-latency applications such as chatbots and interactive tools, delivering consistent performance with an average latency of ~11,000 ms and minimal variability. However, its fully managed nature comes at a premium, making it less cost-effective for smaller models. SageMaker, powered by Nvidia GPU-based instances, offers a balance of flexibility and computational power, making it ideal for development, fine-tuning and workloads requiring GPU acceleration, though it has a higher latency (~32,000 ms). On the other hand, EC2 Inferentia2 is optimized for cost efficiency, particularly for large-scale, non-real-time workloads such as batch processing, offering lower hourly rates but higher latency (~53,000 ms). Model size is another critical factor when selecting the right deployment strategy. Small models (1B–3B parameters) are cost-effective for simpler tasks like text generation and basic Q&A but often struggle with complex reasoning. Medium-sized models (8B parameters), such as DeepSeek-R1-Distill-Llama-8B, strike a balance between efficiency and performance, making them suitable for coding support, routine analysis and mid-tier enterprise applications. Large models (70B parameters) are best suited for advanced use cases like scientific research and critical decision-making but come with significantly higher infrastructure costs. Use case alignment further refines deployment choices. For enterprise applications requiring reliability, medium-sized models (8B) or Bedrock’s managed service provide a robust solution. Research and scientific computing, which often demand intensive computation, benefit from large models (70B) deployed on SageMaker or Inferentia2. For conversational AI, Bedrock is the preferred choice for low-latency interactions, while smaller models can be leveraged for lightweight chatbot applications. Content generation needs vary in complexity, with medium-to-large models being ideal DeepSeek-R1–70B excels in producing high-quality outputs. Finally, for multimodal AI, models like Llama 3.3 70B offer broader capabilities across various domains. March 2025 has brought exciting new models available on AWS Bedrock. While not open source, the addition of models like Claude 3.7 Sonnet from Anthropic and Amazon Titan Nova Pro has opened up even more possibilities. These models offer impressive performance, support features like distillation for improved efficiency and come with competitive pricing, making them well-suited for business use cases ranging from high-performance reasoning tasks to scalable, cost-efficient deployments. Choosing the right deployment option ultimately depends on the priorities of your business. If real-time performance is the top priority, Bedrock is the best option despite its higher cost for smaller models. For teams needing more flexibility, SageMaker with GPU instances is ideal for development, fine-tuning and hybrid workloads. If cost efficiency is the main concern, EC2 Inferentia2 is well-suited for batch processing and non-urgent tasks. For complex tasks requiring advanced reasoning and coding capabilities, larger models like DeepSeek-R1-Llama-Distill-70B justify their higher costs with superior performance. By leveraging the structured framework provided in this series, you can confidently navigate these tradeoffs, ensuring that your GenAI investments align with your specific needs and deliver tangible value."},{"href":"/part-2-deploying-distiled-deepseek-r1-models-on-amazon-sagemaker-ai/","title":"Part 2: Deploying Distiled DeepSeek-R1 Models on Amazon SageMaker AI","subtitle":"Harnessing Open Source AI on AWS","description":"A deployment walkthrough for serving distilled DeepSeek-R1 models with Amazon SageMaker AI, including the AWS setup for open-weight reasoning models.","abstract":"A deployment walkthrough for serving distilled DeepSeek-R1 models with Amazon SageMaker AI, including the AWS setup for open-weight reasoning models.","tags":["AWS","Generative AI","AI","DeepSeek"],"topics":[],"authors":["Crhistian Cardona","Bojan Jakimovski"],"text":"Building on our earlier exploration of deploying DeepSeek-R1 distilled models on AWS Bedrock, this post shifts our focus to another powerful service, AWS SageMaker AI. Whereas Bedrock excels at providing easy access to foundation models via API without needing infrastructure management, SageMaker AI is a fully managed machine learning platform that simplifies the end-to-end process of building, training, and deploying generative AI models. By abstracting away the complexities of underlying infrastructure, SageMaker AI empowers developers and data scientists to concentrate on refining model performance, customizing training workflows and ensuring robust security and compliance. In this post we’ll walk through the practical steps to deploy a smaller, distilled version of DeepSeek-R1 (or any other open-source model) on AWS SageMaker AI using traditional GPU-based instances, enabling scalable, production-ready inference. The SageMaker AI Difference SageMaker AI offers a comprehensive, fully managed platform that streamlines every stage of the machine learning lifecycle. It’s an ideal choice for deploying DeepSeek-R1 and other models that feature mixture‑of‑experts architecture and intensive reasoning capabilities that demand robust model parallelism, autoscaling and real‑time monitoring, all of which it provides right out of the box. By taking care of the underlying infrastructure — including scalability, security and high availability — SageMaker AI allows engineers to focus on refining the model’s performance and customization. Its seamless integration with other AWS services, such as S3 for data storage, IAM for access control and CloudWatch for monitoring, simplifies both data management and operational oversight. Additionally, the platform supports a wide range of instance types and GPU configurations, enabling cost-effective, scalable deployments that can be quickly adapted to evolving workloads. SageMaker AI’s flexibility, coupled with AWS’s powerful tools for rapid prototyping and iterative development, ensure that GenAI applications are not only robust and secure but also optimized for production at scale. Compare it to Azure ML, which excels with a no‑code designer for quick deployments, or Google Vertex AI, with its state-of-the-art TPU acceleration: SageMaker AI stands out by offering an extensive suite of built‑in algorithms, robust MLOps tools and seamless integration with the broader AWS ecosystem. This rich array of options not only supports diverse GenAI applications but also enables rapid prototyping and iterative development that optimizes production‑scale performance. Prerequisites Before getting started, ensure you have the following: AWS Account with permissions for SageMaker AI AWS CLI installed and configured. SageMaker AI Domain: Configure a SageMaker AI Domain if you plan to work within SageMaker AI Studio. Service Quotas: Verify that you have sufficient quotas (for example, instance counts for your chosen instance types) in your AWS account. IAM Role with access to SageMaker AI, S3 bucket uv, fast Python package manager Architecture Overview The deployment consists of three main steps: Downloading the model from Hugging Face (automatically handled by the Hugging Face Predictor) Create SageMaker AI Endpoint configuration. Deploy SageMaker AI Endpoint. Architectural Diagram for Deployment of DeepSeek-R1 Distill Models (or Open-Source Models) on Amazon SageMaker AI In this blog, we are going to cover one deployment method: Deployment via Code (with boto3, sagemaker sdk, huggingface) Deploy via Code (with boto3) This method is a typical preferred method for ML or MLOps Engineers. The code can be found on this repository. We have seven triggering process steps to trigger the Deployment via Code method. Step 1: Set Up Environment Clone the repository and install dependencies: git clone https://github.com/LokaHQ/deepseek-distilled-on-bedrock-custom.git pip install uv uv sync Step 2: Configure AWS Credentials aws configure Or use AWS Vault for secure credential management: aws-vault add <profile-name> Step 3: Set Environment Variables Create an .env file and update it with the necessary configurations: hf_model_id = \"deepseek-ai/DeepSeek-R1-Distill-Llama-8B\" role_arn = 'arn:aws:iam::[account_id]:role/service-role/[AmazonSageMaker-ExecutionRole-xxxxxxxxxxxxxxx]' region_info = 'us-west-2' instance_type = 'ml.g6.2xlarge' initial_instance_count = 1 container_startup_health_check_timeout = 600 sm_num_gpus = 1 Step 4: Deploy Model Using Python Script Run the deployment script: uv run ./scripts/deploy.py \\ -hf_model_id <HF-MODEL-ID> \\ -role_arn <IAM-ROLE-ARN> \\ -region_info <AWS-REGION> \\ -instance_type <INSTANCE-TYPE> \\ -initial_instance_count <INSTANCE-COUNT> \\ -container_startup_health_check_timeout <TIMEOUT> \\ -sm_num_gpus <NUM-GPUS> Step 5: Run Inference Once deployed, you can run inference using the following script: uv run ./scripts/inference.py \\ -endpoint_name <ENDPOINT-NAME> \\ -prompt \"<PROMPT>\" \\ -temperature <TEMPERATURE> \\ -max_new_tokens <MAX-NEW-TOKENS> \\ -top_k <TOP-K> \\ -top_p <TOP-P> Step 6: Benchmarking the Model (Optional) If you want to evaluate the deployed model by calculating some statistics about the costs and the latency you can execute the following script: uv run ./benchmark/benchmark.py \\ -endpoint_name <ENDPOINT-NAME> \\ -region_info <AWS-REGION> \\ -output_dir <OUTPUT-DIR> \\ -temperature <TEMPERATURE> \\ -max_tokens <MAX-TOKENS> \\ -top_p <TOP-P> \\ -max_retries <MAX-RETRIES> \\ -cold_start_loops <COLD-START-LOOPS> \\ -stat_loops <STAT-LOOPS> Step 7: Removing the Model After you experiment with your model, it is advisable to remove it (delete it), by deleting the endpoint on which the model is hosted. You can do that by running the following script: uv run ./scripts/delete.py - endpoint_name <ENDPOINT-NAME> Best Practices To ensure a smooth deployment and optimal performance of your DeepSeek-R1 model on SageMaker AI, consider these best practices: IAM Role Permissions: Make sure the IAM role has all necessary permissions for SageMaker AI, S3, and any other integrated services. Environment Variable Configuration: Double-check your .env file to ensure all parameters (like instance type and GPU count) match your resource availability. Endpoint Management: Always delete your endpoints when not in use to avoid unnecessary charges. Testing and Benchmarking: Run benchmarks to measure inference latency and throughput, and adjust parameters (such as temperature and max tokens) for your specific use-case. Instance Selection: Choose the appropriate instance type based on the model size. Refer to the following table for guidance: Model Instance Type GPUs per replica deepseek-ai/DeepSeek-R1-Distill-Llama-70B ml.g6.48xlarge 8 deepseek-ai/DeepSeek-R1-Distill-Qwen-32B ml.g6.24xlarge 4 deepseek-ai/DeepSeek-R1-Distill-Qwen-14B ml.g6.12xlarge 4 deepseek-ai/DeepSeek-R1-Distill-Llama-8B ml.g6.4xlarge 1 deepseek-ai/DeepSeek-R1-Distill-Qwen-7B ml.g6.4xlarge 1 deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B ml.g6.2xlarge 1 Looking ahead, our next blog post will explore how to deploy DeepSeek-R1 distilled models on raw EC2 instances using specialized Trainium or Inferentia chips, offering an alternative approach that emphasizes even greater cost efficiency and performance optimization in a more hands-on cloud infrastructure setup. And later in this series we’ll dive into cost and business considerations. Stay tuned!"},{"href":"/part-3-deploying-deepseek-r1-models-on-aws-designed-silicon-instances/","title":"Part 3: Deploying DeepSeek-R1 Models on AWS- designed Silicon Instances","subtitle":"Harnessing Open Source AI on AWS","description":"Engineering notes on deploying DeepSeek-R1 models to AWS-designed silicon instances and serving open-weight reasoning models on AWS.","abstract":"Engineering notes on deploying DeepSeek-R1 models to AWS-designed silicon instances and serving open-weight reasoning models on AWS.","tags":["AWS","Generative AI","AI","DeepSeek"],"topics":[],"authors":["Crhistian Cardona","Bojan Jakimovski"],"text":"In the previous parts of this series, we explored how easily we can deploy distilled DeepSeek-R1 models on AWS Bedrock and on AWS SageMaker AI. While these managed services abstract infrastructure complexities, they can come with some limitations if we want to deploy something extremely custom. That’s why in this post, we adopt a more hands-on methodology by deploying DeepSeek-R1 distilled models on Amazon EC2 instances equipped with Inferentia and Trainium chips. These AI accelerators, designed by AWS, offer substantial cost savings and enhanced performance for inference tasks compared to traditional GPU instances. Why Inferentia & Trainium (Silicon Chips)? Instances powered by Inferentia and Trainium chips deliver more economical inference solutions than their GPU-based counterparts. Notably, Inferentia-based instances can offer up to 40% cost savings, while Trainium-based instances have demonstrated up to 50% price-performance benefits in certain workloads. The AWS Neuron SDK is engineered to accelerate AI workloads by optimizing hardware utilization, ensuring efficient processing of machine learning tasks. These instances seamlessly integrate with EC2 Auto Scaling and Load Balancers, facilitating effortless scaling to meet production demands. Unlike managed services, deploying on EC2 instances grants complete control over model deployment and optimization processes, allowing for tailored configurations to meet specific requirements. Prerequisites Before getting started, ensure you have the following: AWS Account with permissions for SageMaker AI AWS CLI installed and configured. IAM Role for a IAM role with sufficient permissions to access EC2 and other necessary services. Security group with the necessary inbound and outbound rules(port 22, 80, 443) Key Pair, to access the EC2 instance. uv, fast Python package manage Architecture Overview Architectural Diagram for Deployment of DeepSeek-R1 Distill Models (or Open-Source Models) on Amazon EC2 Silicon Based Instances The deployment consists of only one step: Deploying the EC2 instance using Hugging Face Deep Learning AMI and launch Hugging Face TGI For our purposes we’ll cover one deployment method: Deployment via Code (with boto3) Deploy via Code (with boto3) This method is a typical preferred method for deployment of EC2s (besides using cdk, terraform, pulumi or others). The code can be found on this repository. We have seven triggering process steps to trigger the Deployment via Code method. Step 1: Set Up Environment Clone the repository and install dependencies: git clone https://github.com/LokaHQ/deepseek-distilled-on-ec2-inferentia-trainium.git pip install uv uv sync Step 2: Configure AWS Credentials aws configure Or use AWS Vault for secure credential management: aws-vault add <profile-name> Step 3: Set Environment Variables Create an .env file and update it with the necessary configurations: region_info=us-east-1 instance_type=inf2.8xlarge ami_id=ami-xxxxxxxx security_group_id=sg-xxxxxxxx key_name=your-key-pair endpoint=http://your-ec2-public-dns:8080/generate subnet_id=subnet-xxxxxxxx instance_id=i-xxxxxxxx Step 4: Deploy Model Using Python Script Run the deployment script: uv run python ./scripts/deploy.py \\ --region <AWS-REGION> \\ --instance_type <INSTANCE-TYPE> \\ --ami_id <AMI-ID> \\ --key_name <KEY-NAME> \\ --security_group_ids <SECURITY-GROUP-IDS> \\ --subnet_id <SUBNET-ID> Step 5: Run Inference Once deployed, you can run inference using the following script: uv run python ./scripts/inference.py \\ --endpoint_url <ENDPOINT-URL> \\ --prompt \"<PROMPT>\" \\ --temperature <TEMPERATURE> \\ --max_tokens <MAX-TOKENS> \\ --top_p <TOP-P> Step 6: Benchmarking the Model (Optional) If you want to evaluate the deployed model by calculating some statistics about the costs and the latency you can execute the following script: uv run python ./benchmark/benchmark.py \\ --endpoint <ENDPOINT-URL> \\ --output_dir <OUTPUT-DIR> \\ --temperature <TEMPERATURE> \\ --max_tokens <MAX-TOKENS> \\ --top_p <TOP-P> \\ --max_retries <MAX-RETRIES> \\ --cold_start_loops <COLD-START-LOOPS> \\ --stat_loops <STAT-LOOPS> Step 7: Removing the Model After you experiment with your model, it is advisable to remove it (delete it) from the custom model imports. You can do that by running the following script: uv run python ./scripts/delete.py — region <AWS-REGION> — instance_id <INSTANCE-ID> Best Practices To ensure a smooth deployment and optimal performance of your DeepSeek-R1 model on SageMaker AI, consider these best practices: Inf2 instances are available in 13 AWS regions across 4 continents: Asia Pacific: Mumbai (ap-south-1), Tokyo (ap-northeast-1), Singapore (ap-southeast-1), Sydney (ap-southeast-2).Europe: Stockholm (eu-north-1), Paris (eu-west-3), London (eu-west-2), Ireland (eu-west-1), Frankfurt (eu-central-1). North America: US East (N. Virginia) (us-east-1), US East (Ohio) (us-east-2), US West (Oregon) (us-west-2). South America: São Paulo (sa-east-1). Choose your instance type based on the model variant: 8B Version: Suitable for inf2.8xlarge, 70B Version: Requires a larger instance, for example, inf2.48xlarge. Each Inferentia2 chip has 2 NeuronCores-v2. The DeepSeek-R1-Distill-Llama-8B model, running on an inf2.8xlarge instance, requires only one NeuronCore (/dev/neuron0). The 70B model, running on an inf2.48xlarge, utilizes 12 NeuronCores, aligning with the script configuration. The current deploy.py script deploys the DeepSeek-R1-Distill-Llama-8B model. To deploy the 70B variant, update the user data parameters accordingly. user_data = \"\"\"#!/bin/bash docker run -p 8080:80 \\ -v $(pwd)/data:/data \\ --device=/dev/neuron0 \\ --device=/dev/neuron1 \\ --device=/dev/neuron2 \\ --device=/dev/neuron3 \\ --device=/dev/neuron4 \\ --device=/dev/neuron5 \\ --device=/dev/neuron6 \\ --device=/dev/neuron7 \\ --device=/dev/neuron8 \\ --device=/dev/neuron9 \\ --device=/dev/neuron10 \\ --device=/dev/neuron11 \\ -e HF_BATCH_SIZE=4 \\ -e HF_SEQUENCE_LENGTH=4096 \\ -e HF_AUTO_CAST_TYPE=\"bf16\" \\ -e HF_NUM_CORES=24 \\ ghcr.io/huggingface/neuronx-tgi:latest \\ --model-id deepseek-ai/DeepSeek-R1-Distill-Llama-70B \\ --max-batch-size 4 \\ --max-total-tokens 4096 \"\"\" Deploying distilled DeepSeek-R1 models on EC2 with Inferentia or Trainium offers an affordable, high-performance alternative to SageMaker. While it requires more manual setup, it provides greater control and efficiency for AI inference workloads. In Part 4, we’ll analyze the cost benefits of different deployment methods and discuss business considerations when choosing AWS Bedrock, SageMaker, or EC2 for AI workloads."},{"href":"/harnessing-open-source-ai-on-aws/","title":"Part 1: Deploying Distilled DeepSeek-R1 Models on Amazon Bedrock","subtitle":"Harnessing Open Source AI on AWS","description":"Deploy distilled DeepSeek-R1 open-weight models through Amazon Bedrock, with a hands-on AWS setup from the Loka engineering team.","abstract":"Deploy distilled DeepSeek-R1 open-weight models through Amazon Bedrock, with a hands-on AWS setup from the Loka engineering team.","tags":["AWS","Generative AI","AI","Amazon Bedrock","DeepSeek"],"topics":[],"authors":["Crhistian Cardona","Bojan Jakimovski"],"text":"Advancements in generative AI are evolving as we speak. As we noted in the introduction to this series, AWS supports emerging GenAI innovations through features such as Amazon Bedrock, a fully managed service for building and scaling GenAI applications with a variety of foundation models. Loka’s engineers prefer Bedrock because it offers several advantages for deploying generative AI models. First, it provides a fully managed, serverless environment that allows developers to focus on building applications without worrying about infrastructure management. Second, by leveraging AWS’s cloud infrastructure, Bedrock enables efficient scaling of AI models to meet varying demand levels, ensuring applications remain responsive under different workloads without incurring unnecessary costs. Bedrock also integrates robust security measures, ensuring data privacy and compliance. And perhaps most important of all, it enables seamless integration with other AWS services. From here on out, the rest of this series is aimed at a technical audience of Software Engineers, Solution Architects, ML Engineers, MLOps Engineers and of course AI Engineers. We’ll walk through the technical practical steps required to deploy a distilled version of DeepSeek-R1 — or any other open-source model — on AWS Bedrock as a custom model import. We’ll also explain the reasons why we prefer one model over another. Our goal is to walk you through a spectrum of deployment strategies for DeepSeek-R1 distilled models — or any other open-source model — on AWS. We’ll explore a range of approaches designed to meet different needs: Amazon Bedrock’s user‑friendly, serverless interface that’s perfect for both technical and non‑technical (click‑ops) teams; the more hands‑on, customizable environment provided by Amazon SageMaker for those who want deeper control over their deployments; and finally the ultra‑optimized performance on Amazon EC2 Inferentia for the most advanced, performance‑driven use cases. No matter where you fall on the technical spectrum, this series aims to have something for everyone, empowering you to choose the deployment path that best fits for your use case. Prerequisites Before getting started, you should have the following: AWS Account with permissions for Bedrock and S3 AWS CLI installed and configured IAM Role with access to S3 and Bedrock services S3 Bucket to store model files uv, a fast Python package manager git-lfs, which is required for handling large model files Architecture Overview The deployment consists of three main steps: Download the model from Hugging Face. Upload model artifacts to an S3 bucket. Deploy the model as a custom model in Bedrock. Architectural Diagram for Deployment of DeepSeek-R1 Distill Models (or Open-Source Models) on AWS Bedrock This piece will cover two different deployment methods: Deployment via AWS Management Console Deployment via Code (with boto3) Deployment Methods Method 1: Deploy via AWS Management Console This method is ideal for users who prefer a click-and-configure approach using the AWS UI. Step 1: Download the model. Visit Hugging Face and download the necessary model files (for example, DeepSeek-R1-Distill-Llama-70B). Hugging Face Model Card of DeepSeek-R1 Distill Llama 70B Model Hugging Face Files of DeepSeek-R1 Distill Llama 70B Model Step 2: Upload Model Files to S3. Log in to AWS and navigate to S3. AWS Management Console 2. Create a new bucket. Amazon S3 Console AWS S3 Console for Creating S3 Bucket 3. Upload the downloaded model files. UI for Uploading Files to S3 bucket Step 3: Create an IAM Role. Go to IAM in the AWS Console. AWS IAM Console 4. Create a new role with permissions for S3 and Bedrock. AWS IAM Roles Console UI for Creating IAM Role Step 4: Import Model into Bedrock. Navigate to Amazon Bedrock. AWS Bedrock Console 2. Click “Import Model” and provide the required S3 location and IAM role. AWS Bedrock Console for Importing Models 3. Wait for the model to be imported and deployed. UI for Creating Imported Model 4. Use the result for testing and inference. AWS Bedrock Playground on which we test the Imported Model 5. After testing the model, you can delete it by clicking on the Delete button. UI for Deleting the Imported Model Method 2: Deploy via Code (with boto3) This method is ideal for users who prefer an automated code-oriented deployment by using AWS SDK (boto3) in Python. The code can be found on this repository. Step 1: Set up the environment. Clone the repository and install dependencies: git clone https://github.com/LokaHQ/deepseek-distilled-on-bedrock-custom.git pip install uv git-lfs install uv sync Step 2: Configure AWS credentials. aws configure Or use AWS Vault for secure credential management: aws-vault add <profile-name> Step 3: Set environment variables. Create an .env file and update it with the necessary configurations: bucket_name=”your-s3-bucket” s3_prefix=\"model-prefix\" local_directory=\"./models\" hf_model_id=\"deepseek-ai/DeepSeek-R1-Distill-Llama-8B\" job_name=\"deepseek-job\" imported_model_name=\"deepseek-bedrock-model\" role_arn=\"your-iam-role-arn\" region_info=\"us-west-2\" Step 4: Deploy Model Using Python Script. Run the deployment script: uv run ./scripts/deploy.py \\ -hf_model_id <HF-MODEL-ID> \\ -bucket_name <S3-BUCKET-NAME> \\ -s3_prefix <S3-PREFIX> \\ -local_directory <LOCAL-DIRECTORY> \\ -job_name <CMI-JOB-NAME> \\ -imported_model_name <CMI-MODEL-NAME> \\ -role_arn <IAM-ROLE-ARN> \\ -region_info <AWS-REGION> Step 5: Run inference. Once deployed, you can run inference using the following script: uv run ./scripts/inference.py \\ -model_id <MODEL-ID> \\ -hf_model_id <HF-MODEL-ID> \\ -region_info <AWS-REGION> \\ -temperature 0.3 \\ -max_tokens 4096 \\ -top_p 0.9 \\ -max_retries 10 \\ -prompt \"<PROMPT>\" Step 6 (Optional): Benchmark the model. If you want to evaluate the deployed model by calculating some statistics about the costs and the latency, execute the following script: uv run ./benchmark/benchmark.py \\ -model_id <MODEL-ID> \\ -region_info <AWS-REGION> \\ -temperature 0.3 \\ -max_tokens 4096 \\ -top_p 0.9 \\ -max_retries 10 \\ -cold_start_loops 2 \\ -stat_loops 5 \\ -output_dir <OUTPUT-DIR> Step 7: Remole the Model After you experiment with your model, it is advisable to delete it from the custom model imports. To do so, run the following script: uv run ./scripts/delete.py \\ -model_id <MODEL-ID> \\ -bucket_name <S3-BUCKET-NAME> \\ -s3_prefix <S3-PREFIX> \\ -region_info <AWS-REGION> Best Practices Ensure your IAM role has correct S3 and Bedrock permissions. Use uv for managing dependencies efficiently. Adjust parameters like temperature, max_tokens and top_p based on your application needs. Optimize S3 storage by removing unused model files after deployment. Implementing Guardrails in Amazon Bedrock Guardrails allow us to implement safeguards across deployed AI models, aligning with responsible AI policies and security restrictions. With Bedrock teams can easily create, test and deploy guardrails during model inference and integrate them with agents and retrieval-augmented generation (RAG) solutions to enhance AI reliability and control. Best practices for implementing guardrails include configuring harmful content categories with strength levels, detecting and blocking prompt attacks through level-based filters and restricting topics based on company policies with predefined sample phrases. Additionally, teams can apply word and profanity filters, automatically detect and remove personally identifiable information (PII) and incorporate contextual grounding and relevance checks to ensure AI-generated responses are accurate and appropriate. By leveraging these features within Bedrock’s fully managed environment, organizations can enforce AI policies, prevent security risks and build trust in AI applications while maintaining compliance with corporate and regulatory constraints. Looking ahead, Part 2 will cover deploying DeepSeek-R1 distilled models on Amazon SageMaker, providing insights into model training, fine-tuning, and cost considerations. Stay tuned as we continue our deep dive into AI deployment strategies!"},{"href":"/dive-into-deepseek/","title":"Dive into DeepSeek","subtitle":"How the open-recipe LLM is transforming GenAI","description":"How the open-recipe LLM is transforming GenAI","abstract":"How the open-recipe LLM is transforming GenAI","tags":["DeepSeek","LLM","Generative AI","AWS"],"topics":[],"authors":["Crhistian Cardona","Bojan Jakimovski"],"text":"Just when the world had settled into a post-ChatGPT reality along comes DeepSeek, upending everything we thought we knew, sending stock markets plunging and pundits hyperventilating. The Chinese-made Large Language Model is the latest wave of paradigm-shifting AI, each arriving at what seems like ever-shorter intervals. Does DeepSeek matter? Yes. Will it matter in six months? Possibly. It is indeed important — and important to understand right now — but not for the reasons you might think. GenAI and LLM 101 To set the stage, let’s review the basic principles behind Generative AI (GenAI) and Large Language Models (LLMs). GenAI models create new content based on input, usually text but also images and videos. LLMs use transformers, a model type that analyzes word relationships through self-attention and multi-head attention — the latter which allows the LLM to retain memory of its previous inputs and outputs — to generate natural text at any scale. In these models, words are converted into embeddings that position similar words close together in a mathematical space. Each word and subword is treated as a token, and the model’s context window determines how much text it can consider at one time. LLMs predict the next word based on learned patterns, and their output can be fine-tuned using parameters such as temperature (for creativity), top-p (for probability filtering), and top-k (for word selection limitation). With millions or even billions of parameters capturing vast amounts of knowledge, these models can generate coherent, human-like responses. The result is the kind of popular LLMs like ChatGPT and Claude that can answer complex questions and create astonishing, even lifelike visuals, all with a simple verbal prompt. Diagram sourced via poloclub.github Timeline of Advancements, aka the Hits Keep Coming Since their inception just 18 months ago Claude and ChatGPT have been iterated and improved multiple times. One fulcrum for their advancement is a machine learning technique called mixture of experts (MoE). Imagine a big problem being solved by a team in which each member is really good at one thing. The team leader picks the best person for each task, making the whole team work more efficiently and effectively. With MoE, the LLM works similarly by having different “experts” for specific tasks. Then there’s multi-head latent attention (MHLA). Think of MHLA like the model paying attention to different parts of the information it gets, all at the same time. This simultaneous dividing of focus helps the model understand and respond more quickly and accurately. In addition, multi-token prediction (MTP) further improves efficiency by allowing the model to predict several words at once rather than one at a time. Another crucial advancement is group relative policy optimization (GRPO). Imagine you’re learning to play a new game, and instead of practicing alone, you join a group where everyone shares tips and strategies. By learning together, you all improve faster and make better decisions during the game. Finally, model distillation brings the power of stronger larger (teacher) models to smaller (student) models while significantly reducing computational costs, automatically making distilled models faster while requiring less hardware and resulting in better performance. All of these advancements have arrived over the course of a single year. The culmination is DeepSeek-R1. You may have heard that R1 is open source, which is true to an extent; in the realm of AI the term is more nuanced than in traditional software development. R1 is actually open recipe, meaning the methods and weights by which DeepSeek created the model are available to the public but not the source code and the data. (Fully open-source models include SmolLM models from Hugging Face in which the code, data and weights are all available to the public.) And Now, DeepSeek-R1 DeepSeek-R1 employs a MoE design with 671 billion parameters, 37 billion of which are active during inference, enabling dynamic allocation of computational resources. Additionally, its impressive 128k-token context window, FP8 precision and use of multi-head latent attention and multi-token prediction collectively enhance its reasoning capabilities. These advancements let DeepSeek-R1 process and understand far more detailed information at once, so it can deliver smarter, more context-aware and naturally human-like responses than older models. A notable distinction in its development is the use of reinforcement learning (RL) over traditional supervised fine-tuning (SFT). This approach allows the model to self-correct and refine its outputs without constant human supervision, leading to more robust performance. In fact this particular approach is the sole reason why DeepSeek-R1 is important at this moment: It’s the recipe for creating better reasoning models. DeepSeek points toward the future of AI. DeepSeek-R1 is a cost-effective model because it employs many innovative techniques that lower the cost of inference. For the sake of comparison, OpenAI’s o1 model, which is similar on benchmarks (see the image below), costs $26.3 per 1 million tokens compared to DeepSeek- R1, which costs $3 per 1 million tokens. Finally, distilled models represent a significant advancement in AI training, enabling smaller models to inherit capabilities from larger, more powerful ones. In the case of DeepSeek-R1, the full model was used to curate 800,000 high-quality samples, effectively enhancing the performance of more compact models — six in this instance. To achieve this efficiency, the team leveraged a range of models, including Qwen 2.5 Standard and Math (available in 1.5 billion, 7 billion, 14 billion and 32 billion parameters) and Llama-3.3 Standard and Instruct (8 billion and 70 billion parameters). Across all cases, the balance between model size and performance demonstrated the effectiveness of distillation. This approach not only makes AI more accessible but also optimizes cost and efficiency, proving that smaller, well-trained models can perform exceptionally well without the need for massive infrastructure. Model comparison of price, output speed, and analysis quality, with DeepSeek-R1 highlighted. Yes, But DeepSeek-R1 is not the ChatGPT killer it has been hyped as primarily because of significant data security and privacy concerns. Reports reveal that DeepSeek AI stores user data including conversations and uploaded files on servers in China, raising fears of unauthorized access and surveillance under strict local cybersecurity laws. As a result, US lawmakers have introduced policy to ban the technology and other governments such as Italy have restricted its use on official devices. Deploying DeepSeek-R1 on trusted cloud platforms like Amazon Web Services (AWS) solves these issues. Hosting on AWS enables organizations to store data regionally, comply with local regulations and benefit from robust security measures like encryption and certifications. Additionally, DeepSeek-R1 adheres to content guidelines imposed by Chinese authorities, resulting in censorship of sensitive topics like Tiananmen Square and Taiwan. This limitation challenges users seeking unbiased information and underscores the need for transparency in AI development. Balancing advanced AI capabilities with data integrity and information freedom remains crucial.… ‍And What Comes Next? As we’ve seen, advancements in generative AI are evolving rapidly. DeepSeek marks a turning point, shifting LLM training and inference from high-cost, heavy-parameter models to lighter, more efficient alternatives. Thanks to the open-recipe approach new competitors have adopted this method, leading to the rapid emergence of smaller, more affordable models — and making AI tools increasingly accessible. Meanwhile, platforms like AWS with services such as Amazon Bedrock and Amazon SageMaker support these advancements by enabling seamless deployment, fine-tuning and production use of a wide array of AI models. Their frameworks integrate best practices in security, data privacy and compliance while incorporating techniques like retrieval-augmented generation (RAG) to help businesses scale AI solutions efficiently. Loka’s engineers believe that integrating new models into scalable, cost-effective pipelines can be the deciding factor between successfully launching transformative products and failing to launch at all. In our upcoming blog series, we’ll explore deploying DeepSeek-R1 distilled versions on AWS, analyzing its size, performance, cost and business applications. Our goal is to help the community push boundaries even further and deliver smarter, more affordable AI solutions."},{"href":"/how-http-3-0-and-quic-solve-head-of-line-blocking/","title":"How HTTP/3.0 and QUIC Solve Head-of-Line Blocking","description":"You probably have heard the history of how HTTP was created and you might even know about the new HTTP/3 version. In this article, I want to focus on some of the lesser-known details of HTTP and why we need a new…","abstract":"You probably have heard the history of how HTTP was created and you might even know about the new HTTP/3 version. In this article, I want to focus on some of the lesser-known details of HTTP and why we need a new…","tags":["Networking","Software Engineering"],"topics":[],"authors":["Daniel Pereira"],"text":"You probably have heard the history of how HTTP was created and you might even know about the new HTTP/3 version. In this article, I want to focus on some of the lesser-known details of HTTP and why we need a new version of this ubiquitous protocol. In the following sections, we will explore the evolution of HTTP and how each iteration tackled the challenges of performance and scalability, culminating in the resolution of Head-of-Line (HoL) blocking with HTTP/3 and QUIC. We’ll begin by examining the origins of HTTP and its initial limitations with the short-lived connection model in HTTP/1.0. From there, we’ll dive into the enhancements introduced in HTTP/1.1, including persistent connections and pipelining, and discuss their shortcomings. Next, we’ll explore HTTP/2’s advances and how these improvements shifted but didn’t eliminate the HoL blocking issue. Finally, we’ll uncover how HTTP/3, powered by the QUIC protocol, overcomes TCP’s inherent limitations and provides a robust solution for modern web performance. But first, we need to start from the beginning… HTTP/1.0: Order Amidst Chaos In the early years of HTTP, we saw the emergence of web browsers and the rapid growth of consumer-oriented public Internet infrastructure. However, because this one-line protocol was designed to serve only hypertext documents, it was extremely limited. This simple protocol eventually became unofficially known as HTTP/0.9. With the need for new features, web developers followed an ad hoc process: implement, deploy and see if people adopt them. With that process, a set of best practices and patterns emerged and the informational RFC 1945 documented the “common usage” of the many HTTP/1.0 implementations at the time. Take a look at this excerpt from the RFC: This specification reflects common usage of the protocol referred too as “HTTP/1.0”. This specification describes the features that seem to be consistently implemented in most HTTP/1.0 clients and servers. Even with all this effort, there was a huge problem with the protocol: By default, you should always open a new connection to request a resource and close it immediately after you receive it. This approach is known as a short-lived connection model and it’s generally undesirable because HTTP is built on top of TCP, which requires a Three-Way Handshake to establish a connection, introducing latency. This delay becomes especially problematic when loading numerous resources on a webpage. Moreover, TCP employs a slow-start mechanism to manage network congestion. This means it begins with a conservative use of available bandwidth, gradually ramping up as the connection persists and stabilizes. Frequent opening and closing of connections, as in the short-lived model, disrupts this ramp-up process, preventing TCP from fully utilizing the network’s potential and further degrading performance. Leaked image of a TCP server’s protocol in action (there is still the final ACK btw) HTTP/1.1: Internet Standard This standard was designed to solve some ambiguities and also introduced some performance optimizations like: keep-alive and request pipelining. Keep-alive connections can remain open, meaning that we won’t suffer the overhead of creating and destroying connections every time a resource needs to be fetched. In the image below you can see the short-lived and persistent connection model which represents the default way of handling connections in HTTP/1.0 and HTTP/1.1 respectively. Figure 1 — Models of connections HTTP/1.x Persisting the connection is great for performance, but can we make it even better? Theoretically we can, and this is what HTTP pipelining is for. With it, before you even get the response of your first request, you issue a subsequent request (see Figure 1 above). Therefore you save time because the server can answer those as soon as possible, right? The problem is that with HTTP/1.1 there is no way to link the response with the request, so the only way to implement this pipelining is to respect the ordering of requests. This means that even if the first request is the slowest and the server already has the response for the other requests, it must respect the ordering and thus the first one will block the others since it is way slower. This problem is called Head-of-Line blocking. Respecting the ordering is difficult since there are transparent proxies between a client and a server, and those proxies don’t implement HTTP pipelining, or they implement them in the wrong way. Such problems are so real that by default browsers disable this feature; as a result, pipelining is rarely used in practice. HTTP/2: Optimized Transport HTTP/2 supports all of the core features of previous versions but operates more efficiently than HTTP/1.1 by introducing the concept of frame and streams that would allow multiplexing of request/response. Multiplexing of requests is achieved by having each HTTP request/response exchange associated with its own stream (Section 5). Streams are largely independent of each other, so a blocked or stalled request or response does not prevent progress on other streams. — RFC 9113 This means that over a single TCP connection, multiple HTTP/2 requests can be made in parallel. This process is different than the HTTP/1.1 pipelining where request/responses are sequentially ordered and solves the HoL blocking at the application level. Figure 2 — HTTP/2: Request/Response Multiplexing Although the stream concept is effective to some extent, we can still suffer from HoL blocking at the transport level (TCP). HTTP/2 is built on top of TCP, which is a protocol that guarantees the reliability and ordering of segments. TCP does not know what it is transporting, it just does the job, and because of this it can cause the HoL blocking. Figure 3 below shows an example where the browser is trying to request the files script.js and style.css from the server. The script.js and style.css are being transmitted in streams 1 and 2 respectively. Notice that since TCP is agnostic about what is being transmitted; it could potentially transmit pieces of two files in the same segment. Figure 3 — HTTP/2 packetization and multiplexing for 2 files TCP guarantees order of delivery between its packets and in a scenario where packet 1 is lost, even though it only contains pieces of the script.js file, it will block the other packets from being delivered from stream 2 which relates to styles.js and thus causing the HoL blocking. Figure 4— TCP Head-of-Line Blocking Let’s take a look at another example from Figure 4, focusing on the syscalls (recv in this case). Imagine that each segment — P1, P2, and P3 — is from a different stream. Each stream is independent, allowing them to be delivered to the application individually. However, because TCP is unaware of these separate streams, it won’t deliver any segments to the receiver until they’re in the correct order. If the first segment is lost, TCP will initiate a retransmission, delaying all subsequent segments and negatively impacting performance. You can think of this scenario as if three images were requested in the same connection using HTTP/2 streams, but because of TCP HoL blocking, one of the image’s missing pieces will affect the other images, preventing them from being rendered until the lost piece arrives. You can you see the same problem arising. First we had a problem with HTTP/1.1 pipelining, which tried to solve on HTTP/2 with streams, but TCP has the same problem. How do we solve it then? Simple — don’t use TCP and go with UDP. HTTP/3: Breaking Free from the HoL HTTP/2 did not solve the HoL problem completely, it was just pushed down the stack (transport layer). To solve this issue we could create a new version by: A) Extend TCP to allow streams over it B) Use the Stream Control Transmission Protocol (SCTP) C) Create a new protocol that uses UDP Let’s talk about each of those possible options. Option A — Extending TCP wouldn’t work because middleboxes (the machines that make the internet infrastructure) could inspect the TCP segments, think they are malformed and drop them. Updating these middleboxes to recognize new protocols would solve this problem, but in practice, they’re rarely updated. This inability to extend or deploy new protocols on the internet is known as protocol ossification. Option B — The Stream Control Transmission Protocol (SCTP) could leverage streams to eliminate HoL blocking. Still, SCTP is not a good transport protocol alternative since some firewalls only allow TCP or UDP segments to pass through (A Comparison between SCTP and QUIC). For that reason, protocol designers must ensure that solutions to the HoL blocking issue are middlebox-proof, which has led to the QUIC protocol. Option C — To put it simply, QUIC is a UDP-based multiplexed and secure transport protocol with ambitious goals. One of them is multiplexing without HOL blocking. The fact that QUIC is a UDP-based protocol gives it an advantage over SCTP since most middleboxes already implement UDP. Another aspect of the protocol is that it doesn’t have a clear-text version, which prevents ossification since boxes cannot inspect the transport header (more here). Isn’t that brilliant? As you can see, the QUIC protocol is the natural replacement for TCP and this led to the HTTP/3. Although HTTP/3 uses QUIC, the latter protocol can be used for other use-cases, which is intentional since new protocols can be built on top of it and benefit from its features. See the image below where we compare HTTP/2 and HTTP/3: Figure 5 — Basic HTTP/3 vs HTTP/2 comparison — Layering Focus by Marx, R. As you can see, the QUIC protocol is responsible for the reliability and congestion control provided by TCP and also for stream multiplexing of HTTP/2. So even using UDP we will still have ordering of the same streams as QUIC will ensure it. Figure 6 shows us how the packetization process for one file happens for the protocols discussed in this article. Notice that QUIC uses UDP under the hood, so if we had the exact same scenario as in Figure 4 where all the segments were in the receiver buffer, they would be delivered to the QUIC layer, which would be responsible for figuring out what could really be delivered to the application. Others from different streams would be delivered to the application layer. Figure 6 — HTTP/1.1 vs HTTP/2 vs HTTP/3 packetization for 1 file With this setup, we solved the TCP HoL blocking issue on HTTP/3 for different streams and we still maintain the original features of HTTP/2, all because of UDP. Did you notice that I said that we solved HoL blocking for different streams? That is correct! QUIC still can’t deliver out-of-order packets for the same stream, which makes total sense, right? Why would you even deliver a text totally out of order? You can deliver in chunks, but they should be in order. So yes, we still have HoL blocking, but only for the same stream, and this is fine. And with that, now you know why we need QUIC and HTTP/3! Bonus Another thing I want to shed light on is the fact that QUIC is a user-space protocol, meaning it doesn’t have the same privileges as TCP, which operates in kernel space. While this design allows for rapid evolution and easier updates to QUIC implementations, it also introduces performance challenges, especially on high-speed networks. This is due to receiver-side processing overhead and limited offloading techniques, as highlighted in “QUIC is not Quick Enough over Fast Internet”. By November 2024, 28.8% of all websites were using HTTP/3 and in my opinion, this percentage will increase when QUIC makes it into kernel space because it will make things even faster."}]