DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

AI/ML

Artificial intelligence (AI) and machine learning (ML) are two fields that work together to create computer systems capable of perception, recognition, decision-making, and translation. Separately, AI is the ability for a computer system to mimic human intelligence through math and logic, and ML builds off AI by developing methods that "learn" through experience and do not require instruction. In the AI/ML Zone, you'll find resources ranging from tutorials to use cases that will help you navigate this rapidly growing field.

icon
Latest Premium Content
Trend Report
Generative AI
Generative AI
Trend Report
Observability Reloaded
Observability Reloaded
Refcard #406
AI-Native Observability Patterns and Anti-Patterns
AI-Native Observability Patterns and Anti-Patterns

DZone's Featured AI/ML Resources

Vapi vs Retell AI vs LiveKit: Architecture, Latency, Pricing, and Developer Experience

Vapi vs Retell AI vs LiveKit: Architecture, Latency, Pricing, and Developer Experience

By Akmal Chaudhri DZone Core CORE
Vapi, Retell AI, and LiveKit can all power voice agents, but they put different quantities of infrastructure and application logic in the developer's hands. Vapi and Retell AI are managed orchestration platforms. LiveKit Agents is an open-source, code-first framework that can run on LiveKit Cloud or infrastructure you operate. That distinction affects customization, deployment, integration design and total cost, not just which dashboard you prefer. The applied VoiceTest exercise recorded automated-judge pass counts of 7/8 for the imported LiveKit graph, 5/8 for Retell, and 3/8 for Vapi. Don't read these as a platform ranking or a measure of agent quality: our transcript audit found judge errors, and VoiceTest generated agent turns with the same configured model for all three graphs, not the vendor-native LLMs or audio pipelines. Each scenario was run once; Vapi and LiveKit also hit the 50-turn cap in every test, while Retell's imported End Call node is the leading structural explanation for its different termination behavior. If you'd like to check our work, we've published the full technical report and evidence in a GitHub repository. It includes the prompts, rubric, judge feedback, transcripts, imported graphs, and limitations behind the results we discuss here. How the Three Platforms Differ Vapi is a managed platform configured through an API and dashboard. Developers select a transcriber, language model, voice, and tools; server-side tools connect the assistant to application endpoints. Its reviewed SDK coverage includes TypeScript, Python, Java, Ruby, C#, and Go on the server side, plus web and mobile clients. Retell AI is also managed. Its orchestration layer coordinates speech recognition, the LLM, and speech synthesis, with agent-building options that include prompt-based and conversation-flow designs. The reviewed developer SDKs are TypeScript and Python, and custom functions connect agents to external HTTP endpoints. LiveKit Agents takes a code-first approach. Developers define an agent in Python or TypeScript, configure an AgentSession, and select STT, LLM, and TTS providers, or use a real-time speech model. The framework uses LiveKit's real-time media stack. You can self-host the infrastructure or use LiveKit Cloud for managed deployment. DimensionVapiRetell AILiveKit AgentsOperating modelManaged orchestrationManaged orchestrationOpen-source framework; cloud or self-hostedApplication logicConfigured tools calling server endpointsCustom functions calling HTTP endpointsTools and state in agent codeDeploymentVendor cloudVendor cloudLiveKit Cloud or your infrastructureSDKs reviewedTypeScript, Python, Java, Ruby, C#, Go; web/mobile clientsTypeScript, PythonPython, TypeScriptMedia scopeVoice and chatVoice and chatVoice, video, vision, avatarsObservabilityCall recordings, logs, transcripts, packet captures, evaluationsAnalytics, alerts, simulationsSession replay, traces, logs, reports, tests Managed Orchestration or Code-First Control? With Vapi or Retell, the vendor operates more of the media and orchestration layer. Your team owns prompts, tools, business rules, and the backend systems those tools call. This can shorten the path to a working agent, particularly when the workflow fits the platform's configuration model. With LiveKit, the agent's behavior is code. You can control turn handling, tool execution, context management, and how agents interact with other real-time participants. That flexibility comes with responsibility: your team must maintain the agent application and decide how much of the media infrastructure to operate. LiveKit Cloud offers a middle ground: it manages deployment and related services while retaining the code-first development model. A managed service becomes restrictive when the application needs unusual state management, custom turn-taking, video, or deployment inside a specific network boundary. A code-first framework can be unnecessary overhead for a standard call flow where a small team simply needs to answer, look up a record, book, or transfer. Latency: Measure the Pipeline, Not the Brand End-to-end voice latency is a chain of delays: endpointing must decide that the caller has finished; speech recognition must finalize the transcript; the LLM must produce a response; text-to-speech must generate the first audio and the network must deliver it. A speech-to-speech model can remove separate STT and TTS stages, but may offer less control over exact wording. We found that the platforms expose different controls. Vapi uses start- and stop-speaking plans and supports configurable endpointing options. Retell exposes responsiveness and interruption-sensitivity controls, with options such as dynamic responsiveness and backchannels. LiveKit provides turn detection, VAD/adaptive interruption handling, endpointing controls, and preemptive generation. The supplied platform research didn't identify comparable vendor-published end-to-end latency figures. The VoiceTest experiment also can't fill that gap: its duration_ms field records simulation execution time, not first-audio latency or caller-perceived response time. A meaningful latency benchmark needs native live calls, fixed model and voice choices, controlled network and telephony paths, timestamped audio events, repeated trials and percentile reporting. Developer Experience and Backend Integration Consider an appointment assistant with two operations: retrieve a patient's appointment and move it to a new time. In Vapi, a tool is defined with a JSON schema and server URL; Vapi sends a tool-call request and expects a matching result. Retell custom functions call an HTTP endpoint with call context and arguments, and requests include a signature that the backend should verify. LiveKit tools can be methods in the agent's code, so there's no separate webhook hop unless the application's scheduling system itself sits behind an API. The implementation detail that matters most isn't syntax. It's transaction safety. A reschedule or cancellation can be retried or interrupted, or have its response discarded. State-changing operations should be idempotent, and the agent must communicate backend failures clearly. Don't let a model claim a booking is complete until the scheduling service has confirmed the write. Telephony, SIP, and Real-Time Media All three platforms support connections to phone systems, but the integration model differs. Vapi documents its own SIP transport and support for providers such as Twilio, Vonage and Telnyx, along with bring-your-own trunk options. Retell's elastic SIP trunking model connects provider origination and termination to Retell; it also documents integrations with contact-center systems including Avaya, Genesys, Five9 and Amazon Connect. LiveKit represents calls as participants in rooms: inbound calling uses a phone number, inbound trunk, and dispatch rule; outbound calling uses an outbound trunk and SIP participant creation. The room model is particularly useful when voice is one participant in a broader real-time experience, such as a patient joining by phone while a clinician joins by video. Check the precise transfer behavior you need, too: cold transfer and warm, agent-assisted transfer aren't interchangeable capabilities. Production Operations and Observability Before launch, test interruptions during long answers and tool calls, backend timeouts, duplicate writes, dropped network connections, and recovery after errors. Re-run a fixed regression suite after every prompt, model, or tool change. Review concurrency limits against peak simultaneous calls rather than average volume. The reviewed documentation describes Vapi call recordings, logs, transcripts and SIP packet captures; Retell analytics and alerting for call volume, cost and errors; and LiveKit session replay, trace spans, session reports and external metrics integration. These features help diagnose failures, but none replaces application-level tests or realistic production trials. Pricing and Total Cost of Ownership Public pricing checked November 14, 2026 isn't directly comparable because the vendors package usage, included allowances, model inference, telephony, concurrency and observability differently. Vapi lists $0.05/min hosting, with STT/LLM/TTS and transport billed separately; Core is $29/month, and Pro is 10% of hosting with a $999 monthly minimum. Retell lists a public voice-agent range of $0.07-$0.31/min, with the final rate dependent on the selected stack. LiveKit Cloud lists Build at $0/month, Ship from $50/month, and Scale from $500/month, with agent-session, telephony, inference, and observability allowances/charges. These are published list-price snapshots, not quotes, and not the cost of running an equivalent production configuration on each platform. PlatformPublic pricing snapshot (Nov. 14, 2026)Common cost components billed separately or variablyComparison caveatVapi$0.05/min hosting; Core $29/mo; Pro 10% of hosting with $999/mo minimum; Premier customSTT, LLM, TTS, telephony, optional compliance and add-onsNot an all-in rateRetell AIPublic voice-agent range $0.07–$0.31/min; 20 concurrent calls included on pay-as-you-goExact voice engine, TTS, LLM, telephony, add-ons and concurrencyRate depends on selected stackLiveKit CloudBuild $0/mo; Ship from $50/mo; Scale from $500/moAgent-session minutes, inference, telephony, observability, recordings and optional featuresPlan allowances and self-hosting costs differ Use a workload-specific estimate from the current calculators and contracts. Specify model, STT, TTS, telephony, included minutes, concurrency, retention, observability, region, and engineering effort. The earlier illustrative all-in model depended on non-equivalent assumed component rates and fixed engineering allocations; it shouldn't be used as a current cross-platform cost ranking. What the VoiceTest Experiment Found The experiment used eight scenarios and three evaluator metrics per scenario. VoiceTest's exports record the same model for agent generation, simulation, and judging across all 24 executions. The vendor-native models, voices, speech recognition, speech synthesis, noise cancellation, and native turn detection weren't exercised. This was an imported prompt/graph simulation, not a native runtime comparison. The table below shows the statuses VoiceTest's automated judge recorded. Several are wrong on a transcript read, so treat it as raw output, not a validated assessment of agent behavior. ScenarioLiveKitRetell AIVapiGreetingPassFailPassSchedulingPassPassFailAvailabilityPassPassFailReschedulingPassPassPassCancellationFailFailFailUrgent medical concernPassPassPassGeneral clinic informationPassFailFailOne question at a timePassPassFail The automated judge recorded pass counts of 7/8 for LiveKit, 5/8 for Retell, and 3/8 for Vapi. A transcript audit, however, found important false-positive judgments. Vapi received passes despite placeholder-filled rescheduling language and unsupported booking claims in its greeting and triage-nurse handoff. LiveKit passed a clinic-information exchange that invented services, hours, and online booking. Retell's passing rescheduling and availability exchanges also contained ambiguous or unsupported claims. Conversely, LiveKit's cancellation limitation disclosure was failed by the judge. The counts are therefore not reliable measures of agent quality, even descriptively. Read the Results With the Right Caveats The retained prompts weren't equivalent. Vapi's longer prompt contains positive booking/confirmation language and unverified clinic facts despite no scheduling integration. Retell's published Version 0 prompt is shorter and says not to invent availability or imply live scheduling access. LiveKit's prompt prohibits invented clinic facts and unsupported transaction claims, but its imported graph still produced unsupported clinic facts in the General Clinic Information transcript. Several LiveKit prompt instructions also closely mirror the rubric criteria. These differences confound the outcomes and don't show that one native platform is better. All eight Retell transcripts end with an end_call transition. The imported graphs suggest why: the Retell graph has a transition from its main node to an End Call node, while the Vapi and LiveKit graphs are single nodes with no way to end the call. Vapi's dashboard export lists endCallPhrases, but nothing in the imported Vapi graph represents them. The LiveKit graph also omits the on_enter greeting directive. That structural difference is the most direct explanation we have for the different termination behavior, though we haven't confirmed it with a controlled rerun. In most Vapi and LiveKit runs, the caller said goodbye early, and the remaining transcript looped through farewells. The One Question at a Time judgments are also disputed: Retell's passing transcript contains compound prompts, while Vapi's failed transcript requests multiple data fields in one turn. The criterion needs a clearer definition and human adjudication. One test changes the recorded pass rate by 12.5 percentage points. Taken together, the judge errors, single run per cell, shared model, prompt differences, and termination asymmetry mean the recorded counts should be treated only as audit-trail outputs, not comparative results. Which Platform Should You Choose? Vapi and Retell AI are worth evaluating when you want managed orchestration, configuration-led workflows, and vendor-operated voice infrastructure. Compare their exact SIP, SDK, tool, and contact-center requirements against your use case.Choose LiveKit Agents when you need application-level control over the media session, turn handling, tools, or multimodal room experience, provided you have the engineering capacity to own the agent code.Whichever platform you select, connect real backend operations before allowing the agent to claim that it booked, canceled, or rescheduled anything. Treat the backend as the source of truth. Our practical choice isn't simply managed versus open source. We should ask how much control the application needs, how much operational work the team can support, and whether every spoken claim is backed by real system state. Healthcare Deployment: Verify the Contract, Not Just the Product Badge For a US healthcare workflow, don't send protected health information until the required Business Associate Agreements are signed and every model, transcription, voice, telephony, storage, and analytics provider is eligible under the chosen arrangement. Vapi's HIPAA mode requires a paid add-on, signed BAA, and compatible providers; its HIPAA and Zero Data Retention modes are mutually exclusive. Retell offers a self-signed BAA at no additional fee and per-agent storage/retention controls, but confirm processing and storage locations in writing. LiveKit offers BAAs for eligible Cloud plans/projects; its BAA covers LiveKit Cloud, not self-hosted infrastructure, third-party model providers, or your own storage. For UK/EU deployments, HIPAA isn't a substitute for GDPR/UK GDPR. LiveKit documents separate controls for EU project data, agent compute, SIP, inference, provider plugins, and storage; selecting an EU project data region alone doesn't pin every layer. Vapi's EU region is available only with its Premier Success Package. Vapi and Retell should be asked to confirm artifact-level residency and subprocessors contractually. Consult your privacy and legal teams before processing health data. Research Note Vendor pricing, compliance, and data-residency pages were rechecked November 14, 2026. VoiceTest runs were recorded November 9-10, 2026. This is a descriptive imported-graph evaluation, not a controlled platform benchmark. See the companion technical report and evidence repository for the prompt-equivalence audit, full rubric, judge feedback and limitations. Summary Vapi, Retell AI, and LiveKit can all power a voice agent, but they hand you very different quantities of infrastructure and application logic. Vapi and Retell AI are managed orchestration platforms, while LiveKit Agents is an open-source, code-first framework you can run on LiveKit Cloud or host yourself. We compare the three on architecture, latency controls, backend integration, telephony, observability, pricing, and healthcare compliance. We also share what an imported-graph test of eight appointment scenarios did and didn't tell us. The pass counts aren't a ranking, so the real takeaways are how much control you need, how much operational work your team can carry, and whether every spoken claim is backed by real system state. References Vapi: PricingPricing and Success PackagesHIPAA ComplianceData FlowEU region and data residencyCustom toolsSpeech configurationSIP trunking Retell AI: PricingCompliance and BAARetell Trust CenterPrivacy PolicyOrchestration overviewCustom functionsCustom telephony LiveKit: PricingHIPAAHIPAA Eligible Products and ServicesEU data residencyVoice AI quickstartTool definitionTurn detection tuningInbound SIP trunkSimulations VoiceTest: VoiceTest AgentGraph concepts Companion material: Technical report and evidence repository More
Process Intelligence Landscape 2026: Mining, Orchestration, and the Agentic AI Shift

Process Intelligence Landscape 2026: Mining, Orchestration, and the Agentic AI Shift

By Kai Wähner DZone Core CORE
Process intelligence is used to mean one thing to most people: a mining tool for process analysts. It is becoming the layer that decides how reliably an enterprise runs, governs, and automates its operations. The market is converging from both sides. Mining vendors are buying execution and orchestration, with Celonis launching its Context Model and acquiring Ikigai Labs. Orchestration vendors are adding analytics and agent control, and platform vendors are buying miners outright, with Salesforce folding Apromore into Agentforce. The two halves of the discipline, seeing what runs and governing what happens next, are collapsing toward each other. What Is Process Intelligence? Process intelligence has three parts that work together: Mining reads the event logs that ERP, CRM, and ticketing systems already produce and reconstructs how work really runs, not how a diagram says it should.Orchestration governs what happens next, routing work across systems and people and enforcing the rules.The decision gate checks every automated action and AI recommendation against business rules, confidence thresholds, and constraints before it has consequences. The discipline grew out of Business Process Management (BPM). BPM promised to fix processes and largely disappointed, modeling idealized diagrams that did not match reality on projects that took years. Process intelligence is what the discipline became once it started working from real execution data in near real time. The most common mistake is treating process intelligence as one thing, usually a mining tool. It is three. Mining without orchestration sees problems but cannot fix them. Orchestration without mining automates a process nobody has verified. Neither one, without a decision gate, can tell an AI agent what it is allowed to do. The Payoff Starts Before AI Most of the value lands before an agent enters the picture. Mining shows the gap between how a process was designed and how it actually runs, which is usually where the cost hides. It surfaces bottlenecks, rework loops, and the variants that quietly bypass controls. Orchestration then closes that gap, and the decision gate keeps it closed. The result is faster cycle times, lower operational cost, cleaner compliance evidence, and processes a team can actually trust. Every one of those holds whether or not an agent is involved. Why Does Agentic AI Raise the Stakes? Agentic AI does not change why process intelligence matters. It raises how much it matters, and how fast a mistake spreads. An agent takes actions and makes decisions with downstream consequences, which is what makes the process layer non-optional for any serious deployment. AI agents need three things from it: Operational boundaries that define what an agent can decide on its own, what needs human approval, and what must always escalate.Live context, so the agent works on current operational reality rather than data that was already stale when it arrived.Audit trails that record every action, model decision, and human checkpoint in a way compliance can stand behind. The decision gate is where this is enforced. What passes the rules proceeds. What does not is escalated or rejected with a documented reason. Governance is the property you want. The decision gate is the mechanism that delivers it. One step gets skipped often. Introducing agentic AI is not the same as embedding AI into an existing process. A process built for human execution is rarely the right foundation for an autonomous one. The step before automation is redesign, using mining evidence to understand what the process actually does, then rebuilding it for how agents work. Organizations that skip it automate their inefficiencies at machine speed. Process Intelligence Splits Into Mining and Orchestration The landscape is easy to read as a four-quadrant chart where you pick one box. It is not. Process intelligence is at least two decisions, sometimes three. The bottom half of the chart is the mining decision. The top half is the orchestration decision. Most enterprises end up choosing at least one mining vendor and one or more orchestration vendors, because no single product covers both well across a multi-vendor environment. Bubble size reflects relative market reach. Darker fill marks stronger agentic AI capability in production today, and the bridge marker (⇄) flags vendors extending into the other band as a strategic direction. Two stacked decisions, not one ranking. The word agnostic means something different in each half. In orchestration, it comes down to where the process logic lives, who owns it, and how open the engine is. BPMN makes the process model readable and auditable across tools, but engines are rarely drop-in compatible, so the model travels more easily than a running deployment. Real portability comes from owning your business logic in standard code, and from running an engine you can host and operate yourself, with an open or source-available core. Logic locked inside a vendor's proprietary low-code environment offers none of that. In mining, agnostic is about data-source and commercial independence, whether a miner can connect to SAP, Salesforce, and ServiceNow at once while being licensed and governed independently from all of them. There is a third choice too, and the landscape leaves it off the chart on purpose: the decision gate. It is a function, not a product category. It can live inside an orchestration engine as native DMN, run as a real-time context engine fed by event streaming, or sit in a third-party rules engine. The two bands map the decisions that line up with vendor categories, mining and orchestration, and the gate attaches to whichever route fits. A split result is therefore normal and often correct. Many enterprises land on an agnostic miner and a platform-native orchestrator, or the reverse. It is not a contradiction. Buyers shop product by product. Architects design across the boundary. The full landscape works through the market vendor by vendor: Process Intelligence Landscape. Four Choices That Keep Your Options Open Four decisions matter more than the logo on the contract, because they decide how reversible your choice is later. Open standards come first. They keep definitions portable and tools interchangeable: BPMN and DMN for orchestration, OCEL 2.0 and XES for mining, MCP and A2A for agent connectivity. Each solves a different problem. OCEL 2.0 is the portability standard for object-centric mining (OCPM), BPMN keeps a process model readable across tools, MCP standardizes how agents reach data. Watch one gap on the mining side. Object-centric process mining is a capability many vendors deliver on their own internal model. OCEL 2.0 is the standard that actually makes the data portable. So OCEL export is the lock-in check, not the OCPM label. A vendor that builds proprietary equivalents of these standards recreates the lock-in closed BPM platforms created a decade ago, one layer up. Open source is the second, and it is not the same thing. A vendor can support every open standard and still be closed underneath. An open core — the engine or the library itself — is what makes leaving practical rather than theoretical, because you can host it, inspect it, and migrate or fork it if you have to. Open standards keep your data portable. Open source keeps the software itself within reach. Data sovereignty is the third. Some platforms are SaaS-only and require operational data to leave your environment. Others run on-premises, or analyze data where it already lives inside your own data platform. Regulated industries have always weighed this. The trade and digital-sovereignty tensions between the US, China, and Europe have turned it into a board-level question for everyone else, because where operational data sits, and who can reach it, is no longer only a technical choice. Consolidation is the fourth. Smaller specialists change hands, and an acquisition can bring price increases, roadmap shifts, forced migrations, and a loss of cross-vendor neutrality. Bigger is not automatically safer. A large suite vendor removes the acquisition risk and hands you its own lock-in instead. Apromore's move into Salesforce shows how quickly an independent specialist can change hands. The Trinity: Where the Three Layers Fit Process intelligence does not stand alone. It is one of three layers that only work together. Event-driven data integration provides the current, governed data, mapped vendor by vendor in the Data Integration Landscape 2026. Process intelligence turns that into an understanding of how the organization runs and a grip on what happens next. Trusted agentic AI acts on both. None of the three delivers much without the other two. I call them together the Trinity of modern data architecture. No single vendor leads all three layers, and that is less of a problem than it sounds. The convergence that matters is architectural, not commercial. The three layers have to work as one system. They do not have to carry one logo. Most enterprises are better served by a strong miner, a strong orchestrator, and a strong integration and agent layer than by buying all three from one suite. Best-of-breed keeps capability, pricing leverage, and exit options on your side, and open standards keep the seams between them manageable. Buying the whole stack from a single mega-vendor removes some integration work up front and replaces it with lock-in across all three layers at once. For enterprises, the takeaway is that process intelligence selection, data integration, and agentic AI strategy are not three separate decisions. Each constrains the others, and the cost of treating them apart shows up in the first production incident. The full vendor-by-vendor analysis is available as a free PDF with no registration. It works through the platform-native and agnostic options on both the mining and orchestration sides, shows where open standards and deployment model draw the real lines, and ends with six questions for narrowing the field to your own situation. Read the full Process Intelligence Landscape. If you are making a process intelligence decision, start with the enterprise architecture, not the vendor list. Decide what you need at the mining layer and the orchestration layer, confirm where the decision gate lives, and the shortlist gets much shorter. About this Landscape This is an independent analyst perspective. No vendor paid for inclusion or placement. No vendor reviewed its section before publication. I run an advisory practice through Kai Waehner GmbH and have held roles at Talend, TIBCO, and Confluent. I also serve as Global Field CTO at Kestra, a workflow orchestration vendor. Kestra is referenced in the full report where pipeline orchestration meets the process intelligence stack, but it is not part of the landscape and was not evaluated or placed in any zone. The complete methodology note is in the full landscape. More
From Phone Menus to Workflows: The Quiet Engineering Behind Voice Agents That Act
From Phone Menus to Workflows: The Quiet Engineering Behind Voice Agents That Act
By Igboanugo David Ugochukwu DZone Core CORE
Introducing TypeSafe Jev: Typed Judgments as Programming Primitives
Introducing TypeSafe Jev: Typed Judgments as Programming Primitives
By Horatiu Dan DZone Core CORE
When Jev Says It's Sure, Is It Right? A Fraud Case Study in Neo4j
When Jev Says It's Sure, Is It Right? A Fraud Case Study in Neo4j
By Akmal Chaudhri DZone Core CORE
Measuring AI Impact at the Team Level
Measuring AI Impact at the Team Level

TL;DR: What Your Velocity Chart Cannot Tell the CFO Sooner or later, someone in your organization shows a slide with a number about what AI did for your team: typically, the team’s “velocity” before and after the coding agents arrived, plus a percentage that looks like a return on the token bill. The number may even be “correct”; however, it answers a different question than the one finance is asking: A before-and-after comparison credits every change in that period to the agents, and measuring velocity is controversial for good reason under normal circumstances, which makes measuring AI impact by this means even more challenging. A claim your team can defend starts elsewhere: with an honest grade of the evidence, a break-even test for every delegated AI workflow, and the creep check of the AI Delegation Audit, which catches the workflows that pass the test only because nobody reviews their output anymore. Each workflow then gets a keep, change, or retire decision in the Re-classification Log, and the result fits on one page that states what the team can claim and what it cannot. Bonus: For your own work, a small trial of eight to ten runs gives you a direction you can act on. Thesis: This article explains how agile teams can measure AI impact effectively, why before-and-after velocity charts mislead, the three grades of evidence, a break-even test for delegated workflows, a one-page statement for finance, and a personal trial. Disclaimer: I read Charniak/McDermott’s book on “Artificial Intelligence” decades ago; of course, I use AI for research, translations, proofreading, challenging story arcs and article structures, creating artifacts such as graphics, and summarization. It is a production tool, not a substitute for thinking. The CFO’s Question Is Legitimate Let me guess: The number arrived before the question did. At an all-hands, a stakeholder steering committee, or a quarterly business review, one slide showed the team’s velocity in the months before the AI rollout next to the months after, with a green arrow and a percentage, and nobody in the room asked what else had happened in those months. The percentage then traveled upward into the next board deck. A few weeks later, finance asks the question the slide seemed to answer: What does the AI spend buy, and how would we know? It is a fair question, given that many managers still treat “velocity” as a useful measure of team productivity, even of advancement, despite the controversy surrounding it. The velocity chart looks like the obvious answer to the CFO’s inquiry, yet it cannot carry the weight finance puts on it. Why a Before-and-After Chart Credits Everything to the Agents Teams rarely change one thing at a time. The coding agents arrive in the same quarter as a new Sprint cadence, a departure, a reorganization, a major release, or a new Product Goal or product roadmap objective. Comparing “before” with “after” puts it all on the agents’ account. The “before” may not be a calm baseline, either: If the rollout followed a crunch, or if people had used AI privately long before the official licenses arrived, the comparison measures the crunch and the private use as well. James Shore, who published a series of articles on measuring AI’s impact in September 2026, names the problem in Measuring AI’s Impact on Delivery Speed: “Are your speed increases due to introducing AI? Or the other changes you made at the same time?” His remedy is to “interleave ‘without AI’ tasks and ‘with AI’ tasks” in the same period, which “reduces the influence of other changes.” That is a study design, and a study design needs a decision before the work starts, which is why a chart assembled after the fact cannot stand in for it. So the question to ask of every before-and-after number is simple: What else changed in the same month? Velocity Is a Vague Estimate, and AI Changes the Estimates Story points are the Developers’ estimate of an item, made in refinement or Sprint Planning before anybody builds it, and their value lies in the conversation that shows whether everybody on the team is on the same page, as I argued in Estimates Are Useful, Just Ditch the Numbers; the number was never the point. “Velocity”, the sum of those numbers per Sprint, therefore rises when the team finishes more or when it estimates comparable work higher, and a velocity chart cannot tell the two apart. Shore is blunter about it: “Stories? Velocity? Story points? Completely arbitrary.” (It is one of my favorite exercises in one of my Scrum classes; I call it “Cooking the Agile Books.” The rules are simple: inflate your story point count per Sprint without working more to satisfy your demanding manager. Guess what? Everyone knows how to play the game, which shouldn’t surprise anyone, given Goodhart’s law.) Part of the reason is that every estimate is deeply embedded in the context of the team that made it: who is on the team, whether the item touches a part of the application the team knows well or a brand-new one, whether the team’s composition has changed since it last estimated something similar, which tools it uses, what its morale is like, and how unexpected events have affected individual team members. That is why you can’t compare velocity between teams, and with so many variables influencing both estimates and performance, using estimates as a measure of anything is tricky at best, and, most of the time, useless. An AI rollout changes several of those variables at once, and it can push the estimates in either direction. Shore describes the downward push: “if they think they’re going to use AI, and they think AI makes them faster, their estimates will be smaller,” so smaller numbers may hide a real gain. The upward push is the familiar estimate inflation: once management expects an “AI velocity boost,” a team under pressure may find that comparable work suddenly deserves more points; see my exercise above. Either way, the velocity before the rollout and the velocity after it are no longer measured in the same unit. So count the finished items next to the points. If points per item rise while the number of items the team finishes per Sprint stays flat, velocity goes up while the finished work does not. Then look for the work that never shows up in velocity at all: bugs, reopened items, and the hours spent outside the Sprint Backlog on manual fixes or migrations or support nobody planned. That repair work belongs on the same page as the speed. In its coverage of the 2025 DORA report, which surveyed nearly 5,000 technology professionals, InfoQ reports that “the current positive relationship between AI adoption and delivery throughput marks a change from previous results,” while “software delivery instability continues to rise.” More finished work and more repair work can show up in the same Sprints, and a slide that reports only the first number leaves the second to whoever is on call that weekend. InfoQ’s summary describes AI’s primary role in software development as “that of an amplifier,” which matches a principle that runs through my articles: AI amplifies what you already are. Finally, the claim’s scope matters. Shore’s example: “if you see a 2x improvement in coding speed, but people spend 50% of their week on other work, their overall speed improvement is only 1.33x, not 2x.” A coding agent speeds up coding; it does nothing for the Sprint Review, the stakeholder conversation, or the wait for a decision made three levels above the team. And speed was only ever part of the answer: Shore defines software development productivity as “value produced divided by money spent,” and he adds, “Going faster doesn’t mean you’re going in the right direction.” Three Grades of Evidence Not every number answers the question equally well, and telling the kinds apart is a skill you can apply to every AI claim that crosses your desk: A trial: The same kind of task, done with and without AI in the same weeks, with the estimate written down first and the condition assigned at random afterward. It is the strongest evidence a team can produce on its own.A before-and-after comparison: It shows an association, at best.A survey of how fast people feel: It shows how people feel, which is worth knowing, and it measures their perception rather than their speed. The distance between the first and the third grade is documented. In a randomized study published in July 2025, METR randomly assigned 246 issues from 16 experienced open-source developers to either allow or disallow AI. With AI, the developers took 19% longer; before the study, they expected a 24% speedup, and afterward, they still believed AI had sped them up by 20%. Those results have aged, and METR says so itself. Its follow-up, started in August 2025, points toward a speedup, and METR believes that, as of February 2026, AI tools likely speed developers up more than they did in early 2025; nevertheless, it calls its own data “only very weak evidence for the size of this increase,” mainly because of “developers choosing not to participate in the study because they do not wish to work without AI.” Between 30% and 50% of the developers reported skipping some tasks they did not want to do without AI. And when METR surveyed 349 technical workers in early 2026, the median self-reported speed change was 3x, with the authors’ own warning attached: “survey results are not necessarily grounded in reality.” Two lessons follow for a team when measuring AI impact: A survey of felt speed belongs in an impact statement as a finding about the team’s perception, never as evidence of speed. And METR’s selection problem will show up in your team as well: once people rely on AI, a trial that asks them to work without it feels like a penalty, and the tasks people skip may well be the ones where AI helps most, as METR suspects for its own study. A trial therefore needs the consent of the people running it and an end date everybody knows. Does a Delegation Pay Off? The Break-Even Test Velocity concerns engineering throughput, whereas much of the AI work in an agile product team is delegation: an agent-drafted status report, release notes, a summary of the Sprint Review, or the first draft of a Product Backlog item’s description. For each of these, a much simpler test exists, and it needs only three numbers. McKinsey’s October 2026 article on the AI value curve states the rule and credits it to David Tepper, the CEO of Ascerta: delegating a task to AI makes economic sense when “its probability of success exceeds the ratio of the time required to verify its work” to the time a human needs to do the work directly. Written as a line you can put on a whiteboard: Acceptance rate > checking time ÷ doing time The logic is plain once you write it down: With AI, you always spend the checking time, and when an output fails the check, you do the task by hand anyway, so the share of outputs that pass your check, the acceptance rate, has to be higher than the checking time divided by the doing time, the time the task takes by hand. A hypothetical example with invented numbers: A monthly stakeholder report takes 180 minutes to write by hand and 60 minutes to check the AI output line by line against its sources. So the AI version pays off only if more than one draft in three passes the check. If checking takes 150 minutes, because every claim needs a trip back to the original data, the drafts have to pass more than 83% of the time, and a team that had to rewrite two of its last six drafts has its answer. Four adjustments close the obvious loopholes: First, count everybody’s checking time, not only your own. A hypothetical example: A Product Owner drafts the descriptions of five Product Backlog items with AI in 15 minutes, and in refinement, three Developers each spend 20 minutes untangling statements that sound right but aren’t. The checking time for that delegation is 60 minutes, and it falls on people who never decided to delegate anything (Tobi Lütke calls this “slop grenades”). A delegation that passes the test for the person who delegated but fails it for the team is a cost transfer, which is another reason to measure the approach rather than the individual.Second, add the minutes spent writing and adjusting the prompt to the checking time, because you spend them on every run as well, even if you use Skills as SOPs for this purpose. (Skills also need maintenance and auditing; I call this “ClaudeOps.”)Third, measure the checking time instead of recalling it, since a remembered review time is an estimate in its own right.And fourth, do not decide after the first few runs: early AI runs may well be slower while people are still learning the prompting, improving skills, and adjusting to the checking routine. A verdict taken during that learning dip can reverse a month later. (Remember the “J-curve”?) The token bill is a separate line. For a coding agent, it may be the large number. For a drafted report, I suspect the human minutes outweigh it, so check your own invoice before you argue either way. When the Test Lies: The Creep Check The break-even test has a blind spot, and it sits exactly where delegated workflows fail without anyone noticing. Suppose, hypothetically, that a weekly summary has passed the check every single time for two months, while the time someone spends reviewing it, which is the checking time of the break-even test, has fallen from a quarter of an hour to about a minute. On paper, it is the team’s best delegation: a 100% acceptance rate and almost no checking time. In practice, nobody checks anymore, and an Assist workflow, in the terms of the A3 Framework, has turned into unreviewed Automate without anybody deciding so. This is the situation the AI Delegation Audit exists for. It is a recurring 45- to 60-minute meeting, monthly or every two weeks, that does for the work a team has delegated to AI what the Retrospective does for the team’s way of working. It runs four checks on every delegated workflow: Output drift (does the work still meet the AI Definition of Done?),Sufficiency drift (is the model tier still right, in both directions?),Reversibility (could you stop this automation today, and who would?), andCreep (how long does a human spend per review?). (My earlier article on the audit called the second check model fit and the fourth category creep.) The creep check rates a review time trending down as drift and four-second approvals as a fail, which makes it the counterweight to the break-even test: when the review time collapses, both inputs of the test go wrong at once (the checking time shrinks toward zero, and the acceptance rate climbs toward 100%), and the result stops meaning anything. So run both, and read the results together: Fails the break-even test, passes the creep check: An honest failure. Retire the delegation, or change the task split so that the AI formats and a human writes every claim.Passes both: Keep it, and watch the review time.Passes the break-even test only because review time collapsed: Restore genuine review, or change the workflow’s category deliberately, with a reason. Personally, I send every decision into the audit’s Re-classification Log: the date, the workflow, what changed (category, model tier, standard, stop rule, or retirement), the reason, and who decided. “No change” is a valid decision when every check passes; “monitor it” is not, because it postpones a decision while sounding like one. Retiring a delegation that no longer earns its cost is a success, since the team learned something and the next audit has one fewer workflow to inspect. Over a few quarters, that log becomes evidence for measuring AI impact no slide deck can fake. Measuring AI Impact by the Approach, Never by People Every Jira export names every person on the team, and an AI that you ask why velocity went up will happily tell you who drove it. The moment an impact statement names that person, praises them, or ranks the team, measuring an approach turns into a performance review, and people optimize the metric instead of the work. Shore’s warning about his own metrics in Assessing AI Impact: Notes for Your CFO leaves no room for interpretation: “Whatever you do, don’t use them to measure the performance of teams or individuals.” In Measuring AI’s Unintended Consequences, he adds, “There is no metric that can’t be gamed, and this one is more gameable than most.” (See above, my “Cooking the Agile books” exercise.) One observation about people is legitimate, because it limits the claim without judging anyone. If most of a gain sits in one Developer’s work rather than across the team, the team cannot claim a team-wide effect. Shore’s rule for the whole undertaking fits on a sticky note: “Measure the approach instead, learn from it, and stop measuring.” Teams tend to forget the last part, and he spells it out: “Don’t establish a performance measurement program and leave it running.” That warning does not contradict the recurring AI Delegation Audit. A speed trial ends once it answers its question, whereas the audit keeps inspecting the delegated workflows themselves for drift and for review time that keeps shrinking, and it judges no one’s performance. What Finance Gets Instead of the Velocity Chart Back to the question Finance asked: What does the AI spend buy, and how would we know? If the velocity chart cannot answer it, an agile practitioner can prepare something that supports measuring AI impact, and it fits on one page the team’s CTO or manager can sign: What the team can claim: Each claim with its source and how sure the team is; for example, finished items per Sprint next to bugs and reopened items, or the decision on a delegated workflow and the audit behind it.What the team cannot claim, and why: For example, a productivity percentage caused by the coding agents, because a before-and-after comparison shows an association at best; name the evidence it would take to make that claim.The decision per delegated workflow: Keep, change, or retire, each pointing to its row in the Re-classification Log.At most three measures from now on: Each with an end date. The page names no individual and ranks no one. It also takes some courage to hand over, because “we cannot claim that” is not what the all-hands slide promised. Nevertheless, a page that says “we cannot know anything” fails as surely as a page that repeats the percentage, because the person who signs it needs to know what the team can stand behind. Measuring AI Impact – Conclusion: Run a Trial on One Workflow of Your Own Measuring AI Impact at team-level needs the team’s records; a claim about your own work needs little more than a notebook and a few weeks: Pick a task you already do with AI at least once a week, ideally more often, because a task you do once per Sprint takes months to give you an answer.Write your decision rule before the first run: keep if, change if, stop if. Once the numbers are in, every number looks like a reason for what you already wanted.Agree on the trial with the person who receives the output, so a reply written by hand reads as part of a test rather than as a refusal to use AI.Before each run, write down your estimate, then let chance decide whether you work with or without AI. Shore gives each person “a virtual bag that’s half full of ‘with AI’ assignments and half without”. For one person, five paper slips of each in a mug keep the split even, which a coin does not guarantee over ten runs.After each run, log the total time, including checking and redoing; for the runs with AI, also log the prompting and checking minutes separately. Then note whether the output passed your check and how much energy you have left.After eight to ten runs, divide each run’s total time by its estimate, and compare the median ratio of the runs with AI against the median of the runs without AI. That is how Shore compares a team to itself: a team whose estimates were perfectly consistent and that “went from taking 3x longer than estimated to 1.5x longer” would be twice as fast, he writes.Then take the break-even inputs from the same log, the doing time of your runs without AI and the prompting and checking time of your runs with AI, to see how far the acceptance rate could fall before the delegation stops paying. Apply your rule, write the decision down, and stop measuring. Your estimates carry every context problem described above; however, writing them down before the draw keeps those problems the same for both conditions, which is why the comparison works for one person in the same weeks and fails between teams or between periods. Five or so runs with AI give you a rough acceptance rate at best, in 20% steps, and eight to ten runs will not convince a statistician. But they show a direction, and a direction is enough to decide on one workflow, provided you measure only your own work and keep the end date. Key Questions This Article on Measuring AI Impact Answers How Can an Agile Team Measure the AI Impact on Its Productivity? Compare work done with and without AI in the same period, rather than comparing velocity before and after the rollout, because other changes made at the same time confound the comparison. Grade the evidence: a randomized trial beats a before-and-after chart, which beats a survey of felt speed. Count finished items and repair work next to any speed figure, and never measure individual people. Why Is Velocity a Poor Measure When Measuring AI Impact on a Scrum Team? Velocity sums story points, the Developers’ estimates made before the work starts, and every estimate depends on the team’s context, for example, its members, its familiarity with the area, its tools, and its morale. An AI rollout changes several of these at once and can push estimates up under pressure to show a gain, or down when people expect AI to help, as James Shore notes. Count finished items and repair work instead. How Do You Know Whether Delegating a Task to AI Pays Off? Apply the break-even test that McKinsey credits to David Tepper: delegation pays off when the share of AI outputs that pass your check is higher than checking time divided by the time the task takes by hand. A hypothetical report taking 180 minutes by hand and 60 minutes to check must pass more than one time in three. Count every reviewer’s checking time, including downstream reviewers, not only your own. Why Can a High Acceptance Rate for AI Outputs Be Misleading When Measuring AI Impact? An acceptance rate is only as good as the review behind it. When review time falls toward zero, every output gets accepted, and the break-even test passes trivially, while nobody checks the work anymore. The creep check of the AI Delegation Audit watches review time per output and rates four-second approvals a fail, because they mark an Assist workflow that became unreviewed Automate without a decision. How Can I Test Whether AI Actually Saves Me Time on My Own Work? Run a small randomized trial on one task you do with AI at least weekly. Write your keep, change, and stop rules first, and agree on the trial with whoever receives the output. Record your estimate, then draw ‘with’ or ‘without AI’ at random. After eight to ten runs, compare the median ratio of actual time to estimate in both conditions, check the break-even margin, apply your rule, and stop measuring.

By Stefan Wolpers DZone Core CORE
Pitching Kotlin: An Engineering Leader's Guide to Legacy Modernization
Pitching Kotlin: An Engineering Leader's Guide to Legacy Modernization

I've been on both sides of the Kotlin conversation: the engineer making the case, and the architect who reviews it and recommends a direction before a committee decides. On the reviewing side, the pattern is predictable: most Kotlin pitches die in the second meeting. A tech lead shows up with a list of syntax wins, managers or architects ask about migration risk, and the conversation ends with "we'll revisit this next quarter." The technical case for Kotlin is usually sound, but the pitch stalls because it argues from developer preference, while engineering leaders approve migrations based on cost and risk. I've spent a large part of my career on systems where a defect moves real money (I talked about what that means for Kotlin code at KotlinConf 2026), and when I wrote the Kotlin Enterprise Playbook, I ran this exact argument through a financial model across mobile, edge, and backend domains. The proposals that held up were the ones that priced cost and risk honestly, including the cases where the answer was "not here." This guide is the framework I use when I review these proposals. Decide domain by domain, solution by solution, instead of organization-wide. Make the cost of the status quo measurable. Price the migration, including the parts nobody budgets for. Place gates where decisions stop being reversible. Make sure the people who carry the risk own the outcome. Kotlin is the worked example, but the same framework applies to any large technical migration, whether it's a language, a framework, or a data platform. Technical Debt as an Engineering Friction Metric Before you can pitch a migration, you need to make the cost of staying put visible. That cost is spread across pull request (PR) timelines, defect densities, and onboarding logs. It only becomes clear when you add those numbers up over several months, because an incident report only records one failure at a time. Start with four concrete measurements your team already has access to: PR cycle time on service-layer changes. Verbose Java boilerplate (getters, setters, null checks, builder patterns) means more code per feature, which requires longer reviews. A data class in Kotlin replaces a 40-line Java POJO with four lines in a representative case (Java records narrow this gap for immutable value types, though not for mutable or framework-bound classes), and that compression shows up directly in review time.NullPointerException rate in production. Pull your error-tracking data from the last two or three release cycles. A persistent NPE trend is one of the clearest health signals a Java codebase gives you. Kotlin's type system reduces null-related runtime failures at the compiler level, so this number becomes a defensible baseline for the risk argument.Time-to-productive for new engineers. Ask your most recent hires how long it took them to make their first independent commit to your most heavily annotated service layer. In my experience, boilerplate-heavy Java codebases show longer onboarding ramps, and this measurement tells you whether yours does.Effort on existing code per quarter. Count the engineering hours per quarter spent changing existing code and the hours spent writing new functionality. In mature Java monoliths, the time on existing code tends to grow as the codebase ages. Separate structural changes from bug fixes and behavior changes, because only the structural share is the friction you are pricing. When you present these numbers, frame them as a cost to team throughput. A statement like "We're spending 30% of sprint capacity on structural changes to code that hasn't changed business logic in 18 months" gives leadership a number they can weigh against the cost of migrating, while "Java is too verbose" is a preference leadership can dismiss. If your organization already reports DORA metrics (lead time for changes, deployment frequency, change failure rate, and failed deployment recovery time), use them as the backbone for your case and attach the four friction measurements to each one. Leadership already reads DORA as delivery performance, so your Kotlin case arrives in a format they trust. Adoption Friction and Long-Term Velocity Gains A realistic adoption model will show a short-term slowdown before the long-term gains, and presenting only the gains will cost you credibility with your peers. During the initial rollout, your team will write slower Kotlin than they write Java. Code review will slow down while reviewers build pattern recognition for Kotlin idioms. Budget two to four sprints for the team to get comfortable with the idioms, and expect full velocity parity by sprint 8, midway through phase 2. Your Gradle or Maven build configuration will also need updating to add the Kotlin JVM plugin and compiler targets alongside existing Java compilation. Plan for the less visible costs too. Mixed Java and Kotlin compilation adds build time (the K2 compiler that shipped with Kotlin 2.0 narrowed the gap, and Gradle's build cache and configuration cache help further, but measure it on your own codebase before you promise anything), annotation processors need a path off kapt (now in maintenance mode) toward KSP where your libraries support it, and Spring or JPA code needs the kotlin-spring and kotlin-jpa compiler plugins, because Kotlin classes are final by default and both frameworks rely on proxies and no-arg constructors. Note that kotlin-jpa only adds the no-arg constructor: entities also need allOpen configured for @Entity, @MappedSuperclass, and @Embeddable, or Hibernate's lazy loading turns into eager loading without warning. These line items are where migration estimates fall apart, because the visible conversion work is only the tip of the iceberg. Once your team reaches parity, the gains will compound with each module you convert, because Kotlin produces an estimated 40% fewer lines of code than equivalent Java, which means a smaller surface area to read, review, and debug. Treat that figure as directional, since it's a vendor estimate, and replace it with numbers from your own converted modules as soon as you have them. A stronger reference point is JetBrains' telemetry study of about 28 million development cycles: on comparable work, Kotlin developers spent roughly 15-20% less time from first edit to push than Java developers. Compile-time null safety catches most null-related runtime errors before they reach staging. Extension functions let Kotlin code add convenience APIs on top of existing Java classes without touching the original source, which smooths incremental adoption. They're resolved statically, though, so Java callers see them as ordinary static utility methods. Kotlin is designed for Java interoperability at the JVM level, which means you don't convert a service and then wait for everything else to catch up. New features ship in Kotlin while stable Java modules stay exactly where they are. Both compile to JVM bytecode and call each other's APIs directly, so the adoption boundary moves at whatever pace your team sets. AI-assisted tooling further changes the conversion economics. The kotlin-tooling-java-to-kotlin AI Agent Skill, published by JetBrains, integrates with IntelliJ IDEA's AI Assistant and external agent tools to automate module translation with a structured four-step conversion process. The skill performs a faithful semantic translation first, then refines nullability and mutability, converts collection APIs to idiomatic Kotlin, and restructures for framework idioms. It checks five invariants at every step, verifying that public signatures stay compatible and that annotation site targets don't break reflection-based frameworks like Spring or Jackson. Present this to skeptics as a safety net on the conversion pipeline, since it reduces the manual cleanup burden on each converted file, and your team still reviews and commits the output. One caution from the wider migration literature: LLM-assisted translation can produce code that compiles and passes the existing tests while still changing behavior at the edges. Tests generated by the same pipeline tend to confirm the translation instead of challenging it. Keep the tests that guard a converted module independent of the tool that converted it, and before converting a module, add characterization tests that pin down its current behavior. Why the Case Gets Stronger When AI Writes the Code For most teams, a growing share of new code is now drafted by AI assistants and agents. That moves the bottleneck from writing code to verifying it, and verification is where the language matters. Every non-null type, every exhaustive when expression over a sealed hierarchy, and every value class that keeps two lookalike IDs from being swapped is a check the compiler runs on generated code before any human reviewer looks at it. Explicit types also work as a specification the agent reads: a non-null field in a signature states the contract more reliably than a comment the model may ignore. And less code per feature means less generated code to review, which matters more once generation is cheap, and review isn't. AI doesn't settle the question, though. Models have seen far more Java than Kotlin, so output quality can vary, and AI also makes a modern-Java upgrade cheaper. It also shrinks only the visible part of the migration cost: conversion gets cheaper, but parallel running, governance, and decommissioning cost the same with or without an agent. The question becomes which language lets your reviewers trust code they didn't write. In domains where a wrong value is expensive, a stricter type system pays off. Team Velocity Through a Phased Rollout Incremental adoption turns a high-risk initiative into a gated engineering program. The goal is to give leadership defined checkpoints to evaluate stability before authorizing the next phase, because a plan approved in stages is much easier to sign off on than a multi-year roadmap. Phase 1 (tests-first, sprints 1 to 4). Write all new unit and integration tests in Kotlin. Your existing Java production code stays untouched. The team gets hands-on time with Kotlin syntax in a low-stakes context, and your test suite stays green throughout. It is also the cheapest step in the plan to reverse. If the pilot fails, you delete test files, and nothing changes in production. Phase 2 (leaf modules, sprints 5 to 10). Start with independent utility classes, DTOs, and value objects. These are the leaf nodes of your dependency graph. Because they depend on almost nothing else in your codebase, converting one can't break the code it relies on. Check their fan-in, though. A widely shared DTO is a leaf with many callers, and every nullability decision in its Kotlin signature reaches each Java caller, so convert low-fan-in leaves first and treat shared DTOs as a separate step. Two framework details trip up DTO conversions: Jackson needs jackson-module-kotlin to deserialize data classes, and Kotlin code in a mixed module can't see Lombok-generated members without the Kotlin Lombok compiler plugin. Most of these objects translate cleanly to Kotlin data class declarations (JPA entities are the exception: keep them as regular classes, because data-class equals() and hashCode() conflict with Hibernate's lazy proxies), and conversion regressions are easy to catch with the test suite you built in phase 1. Commit the mechanical J2K conversion on its own, then follow it with an idiomatic cleanup so your code reviewers can diff them separately. Phase 3 (new service boundaries, ongoing). Any new microservice or greenfield module ships in Kotlin from day one. This is the Strangler Fig pattern applied to a language: new capability grows around the legacy system, which keeps running until each domain is ready to retire. Existing Java services stay untouched unless they're candidates for targeted conversion. This is where most of the return sits. When I modeled adoption across a full product portfolio, new development came out clearly positive, while migrating highly stable legacy code often produced a negative net present value (NPV). A good plan says so openly and classifies each domain as Kotlin by default, gated behind a business case, or not now. Use a lightweight decision matrix to triage which modules go into which phase, so the sequencing decision is traceable. The following table applies the decision matrix to modules from an example codebase: ModuleFan-in (modules depending on it)Current friction signalTranslates cleanly to a data class?PhaseNotesOrderDtoLowNPEs in the mapping code around itYes2Leaf used by one service, good J2K candidatePricingServiceHighHigh refactor hours/quarterNo3 (new boundary) or targetedCore business logic, convert only if rewriting anywayNotificationUtilsLowLong PR cycle timeN/A (utility class)2Pure utility class, no callers outside its module; becomes top-level functions, so add @file:JvmName to keep Java call sites unchangedPaymentGatewayClientHighMixedNoHoldHigh fan-in, defer until phase 2 modules are stable Score your own modules on the same four columns: dependency count, which friction metric from the baseline section it shows up in, whether it translates cleanly to a data class, and the phase it belongs to. Modules with low fan-in and a clean data-class shape go to phase 2 first. High fan-in modules wait until the team has review-cycle data from earlier conversions. Velocity through these phases usually follows a predictable curve. You'll see a brief slowdown during phase 1 as the team learns the idioms, a recovery to baseline by sprint 8, and then a compounding improvement as shared modules accumulate in Kotlin. The right milestone gate at the end of phase 1 asks whether the team shipped tests on schedule and whether the suite passes. The gate at the end of phase 2 asks whether conversion regressions appeared and how many review cycles each converted file required. Measure both against a control group: comparable Java modules the team changed over the same period. Without one, a before-and-after comparison picks up everything else that changed that quarter, and a careful reviewer will discount it. Each gate is a go/no-go evaluation point. You should place gates where the next step stops being cheap to reverse. Kotlin tests and new modules are easy to back out. A shared DTO with dozens of Java callers, or an organization-wide default, is not, so that is where the evidence bar goes up. Where you can, encode the gate criteria as fitness functions in the build instead of meeting agendas: architecture checks with Konsist or ArchUnit, a build-time budget, and a rule that rejects new Java files in domains classified as Kotlin by default. A gate that runs on every commit doesn't depend on anyone remembering to hold it. If a team misses gate 1, treat that as data about the plan, not as a scheduling problem to absorb in phase 2. Show leadership a velocity chart comparing your team's adoption path with the trend for your Java codebase if nothing changes, so they see the short-term dip and the long-term payoff on the same timeline. The legacy line trends down as refactoring overhead compounds, while the adoption line follows the dip-and-recovery pattern described above. Use your own baseline numbers from the friction metrics section to recalibrate the axis before presenting it. Four Objections I Check When Reviewing a Kotlin Migration When a Kotlin proposal comes to me for review, how it answers these four objections shapes my recommendation to the committee, and each maps to a concrete technical answer. "What if we need to roll back?" Kotlin's interoperability with Java means each module conversion can be reversed on its own, at least for a while. A Kotlin file compiles to standard JVM bytecode that Java code calls directly, and in most cases existing Java callers need no changes, as long as the converted code keeps a Java-friendly API (@JvmStatic, @JvmOverloads, @Throws, and the kotlin-spring plugin for proxied Spring beans). Once other Kotlin code relies on Kotlin-only features of the converted module (default arguments, extension functions, suspend functions, sealed hierarchies), reverting it breaks those callers, so make the rollback window part of your gate criteria. If a converted module introduces instability, revert the commit. Because the mechanical J2K output lives in its own commit, the rollback is one small, reviewable change. For higher-risk modules, run the Java and Kotlin versions side by side behind a feature flag (under different class names, since both can't share one on the classpath), or shadow a slice of production traffic through both and compare outputs before switching over. In payments, shadow only side-effect-free logic such as fee calculation or routing decisions, never authorizations, captures, or refunds, and keep in mind that mirroring card data widens your Payment Card Industry Data Security Standard (PCI DSS) scope. "The conversion overhead is too high." IntelliJ IDEA's built-in Java-to-Kotlin (J2K) converter handles the syntactic translation automatically. The two-commit pattern (one commit for the J2K output, one commit for idiomatic cleanup) keeps code review tractable. "We'll introduce null-safety regressions during conversion." The compiler catches most of these before they ship. The gap is the Java–Kotlin boundary. Unannotated Java types reach Kotlin as platform types with no compile-time check, so annotate the remaining Java side with JSpecify. The boundary can also fail at runtime in the other direction. Kotlin inserts null checks on public non-null parameters, so a Java caller that used to pass null now fails immediately with an NPE. Check the Java callers of each converted API before you mark a parameter non-null. The J2K converter infers nullability from annotations and usage and inserts non-null assertions (!!) where it can't decide, so your team reviews each one and replaces it with safe calls (?.) or Elvis operators (?:), or keeps the non-null assertion where a contract guarantees it. In practice, the bigger risk runs the other way. A converted field gets marked nullable "just in case," and a broken upstream contract turns into a silent fallback deep in the code. Keep mandatory fields non-null, validate them once at the system boundary, and make invalid input fail loudly there. I covered this pattern in my KotlinConf 2026 talk on type-driven reliability. "Why not just upgrade to modern Java?" This is the objection to take most seriously in 2026. Records, sealed classes, pattern matching, and virtual threads have closed much of the gap that drove early Kotlin adoption. For stable, low-change backends, a Java upgrade plus stronger engineering standards is often the higher-return choice. Kotlin earns its place where the bottleneck is modeling correctness, safe refactoring speed, or business logic shared across channels, especially when those factors show up in incident rates or time to market. A credible proposal compares Kotlin with the Java you could run next year (today, Java 25, the current long-term support release), not the Java 8 or 11 the codebase was written in, and it is willing to say "not here" where Java is enough. Architects in enterprise Java usually ask whether Spring fully supports Kotlin, and JetBrains and the Spring team answered that with a strategic partnership to make Kotlin a first-class language for Spring applications. The collaboration covers full null safety across the Spring portfolio (based on JSpecify annotations and shipped in Spring Boot 4), official Kotlin-first Spring learning materials, faster Kotlin reflection, and evolving configuration DSLs. Coroutine support in Spring WebFlux predates the partnership and has been available since Spring Framework 5.2. Spring and Spring Boot remain among the most widely used backend frameworks in JetBrains' own Kotlin developer surveys, with enterprise teams at Expedia Group, Kakao Pay, and Mercedes-Benz.io among those running Kotlin in production on that stack. Who Says Yes, and the Decision on One Page A proposal that only answers engineering gets approved and then stalls in the next review. Before you write it, map who has to say yes and what each of them protects: finance looks at payback and predictability, security at supply chain and scanning coverage, product at delivery risk during the dip, and platform engineering at a toolchain it will support for years. Then make ownership explicit. The architecture board owns the default, gated, and not-now classification. Platform engineering owns the toolchain and upgrade cadence. A small guild owns Kotlin conventions, with rotating membership so it doesn't harden into a gatekeeping inner circle. Write the result as an architecture decision record (ADR), including the context, the options you rejected and why, the decision, and who owns each consequence. The evidence behind the ADR comes down to four things: Codebase health baseline. Present your current friction metrics, including PR cycle time on service-layer changes, NPE rate from your error-tracking tool, engineering hours per quarter on structural refactoring, and new-engineer time-to-first-independent-commit. These establish the cost of the status quo in terms of team throughput. Pair them with an honest cost estimate that covers training, the learning dip, parallel running, governance, and the eventual decommissioning of legacy code.Phased migration plan with gates. Outline the three phases (tests-first, leaf module conversion, new service boundaries) with sprint estimates and go/no-go criteria at each gate. Request approval for phase 1 only. Add a kill switch: if build time, incident rate, or review load regress past agreed thresholds, expansion pauses until the platform is fixed. Name an owner for Kotlin conventions (a style guide, static analysis with detekt, and a short review checklist), so converted code doesn't turn into Java written in Kotlin syntax.Tooling and safety net inventory. Name the specific tools in the conversion pipeline, including IntelliJ IDEA's J2K converter for mechanical translation, the kotlin-tooling-java-to-kotlin AI Agent Skill for framework-aware idiomatic refinement and invariant checks, and the existing Gradle or Maven build for mixed-codebase compilation. Include the supply-chain controls security will ask about: a software bill of materials (SBOM), dependency scanning, and pinned, approved versions of the Kotlin compiler and Gradle plugins. The Kotlin standard library, kotlin-reflect, and kotlinx-coroutines become new runtime dependencies in your component inventory. Security will want to agree on which code may be sent to an AI conversion tool, especially anything that touches keys, hardware security module (HSM) integration, or cryptography. This answers the "how do we actually do this" question before it's asked.Ecosystem maturity signals. The JetBrains and Spring strategic partnership (announced May 2025), Google's continued backing of Kotlin as Android's recommended language (a sign that investment extends beyond any single vendor, not a reason to scope this migration around mobile), the enterprise case studies at kotlinlang.org/server-side, and the roughly 8.1 million Kotlin developers JetBrains estimates in its State of Kotlin 2026 report give leadership the external validation they need. For most backend teams, ecosystem maturity is no longer the main adoption risk. Treat vendor numbers, including these, as directional: independent case studies and your own pilot data carry more weight with a skeptical review board. Keep the main document to one page, two at most, and move the detail into appendices. Your goal is a decision the committee can make in a single 30-minute review, not a series of follow-up meetings. Building the Case, Section by Section This guide's framework comes down to five moves. Decide domain by domain which code is Kotlin by default, which needs a business case, and which is not now. Quantify the friction in your current Java codebase as throughput metrics, measured against a control group. Model both sides of the adoption curve honestly, including the short-term slowdown and the costs nobody budgets for. Phase the rollout through gates placed where decisions stop being cheap to reverse. Then map who has to say yes, make ownership explicit, and put the recommendation in a short ADR. The tooling makes conversion manageable, but tooling was never what blocked approval. A migration gets approved when the decision is scoped by domain, priced honestly, reversible at each step, and owned by the people who carry its risk. That holds whether the change is Kotlin, a new framework, or a new data platform, and it holds just as well when the honest answer is "not here." For the full financial model (NPV, IRR, payback, and the migration iceberg) and the governance setup behind this guide, see the Kotlin Enterprise Playbook I wrote, available at kotlinlang.org, and the recap of my KotlinConf 2026 talk. Where have you said "not here" to a migration your team wanted, and what evidence settled it?

By Yuri Geronimus
Using Middleware in LangChain: Recovering From Tool Failures
Using Middleware in LangChain: Recovering From Tool Failures

In this article, we will look at how to handle tool errors using middleware in LangChain. Introduction Agents are built with tools that they can use to perform different tasks. The agent communicates with the LLM, and the LLM decides which tool to call based on the user's request. The agent then executes the selected tool and sends the tool result back to the LLM. The LLM can then decide whether another action or tool call is required. When an agent executes a tool, the tool may fail due to reasons such as a network error, an invalid input, or an external service being temporarily unavailable. Such failures can interrupt an otherwise successful agent workflow. We want to handle tool failures appropriately so that they do not unnecessarily interrupt the agent's workflow. In this article, we will learn how to use middleware to handle tool failures. What Is Middleware in LangChain? The core agent loop involves calling the model, deciding which tools to use, executing those tools, and continuing the loop until no more tool calls are needed. Middleware provides hooks that allow you to run custom logic before and after different steps in the agent loop. Middleware is code that runs between different parts of the agent's execution pipeline. It can modify or inspect the request before it reaches the model or a tool. It can also modify or inspect the response after the model or tool has finished executing. Pre-Built and Custom Middleware In LangChain, middleware can be broadly divided into two types: 1. Pre-built middleware – Ready-to-use middleware provided by LangChain for common use cases. LangChain provides pre-built middleware for several common scenarios. We can create an instance of the required middleware and attach it to the agent. The underlying logic is already implemented, so we do not need to write it ourselves. 2. Custom middleware – Middleware that we write to add our own logic and customize the agent's behavior. With custom middleware, we can add our own logic using hooks such as @before_model, @after_model, @before_tool, and @wrap_tool_call. Alternatively, we can create a custom middleware class by extending AgentMiddleware and overriding methods such as before_agent and after_agent. Two Ways to Handle Tool Errors In this article, we will look at two ways to handle tool errors: Using pre-built middleware – ToolRetryMiddlewareUsing @wrap_tool_call Pre-Built Middleware: ToolRetryMiddleware We will start with ToolRetryMiddleware. When a tool throws an exception, ToolRetryMiddleware can automatically retry the tool call. You can configure the middleware to wait for some time between attempts and specify the maximum number of retries. Retrying makes sense for temporary failures, such as network errors or temporary service unavailability, so the next attempt may succeed. But retries do not help with errors caused by invalid input or incorrect tool arguments. In such cases, ToolRetryMiddleware is not an appropriate choice. Let’s take a look at an example. Tool Let’s start by creating a tool called get_news that communicates with a free news API to retrieve news. Create a notebook in VS Code and add the following code. Python import requests from langchain.tools import tool attempts = 0 @tool def get_news(news_type: str) -> str: """Get one recent news article.""" global attempts attempts += 1 print(f"Attempt {attempts} to fetch {news_type} news.") if attempts <= 2: raise RuntimeError("Unable to get news at the moment. Please try again") response = requests.get( "https://freenewsapi.ai/v1/search", params={"q": news_type, "size": 1} ) return response.json()["results"][0]["title"] We will simulate an error while retrieving the news. This could be due to a temporary network problem, API failure, or service unavailability. To simulate this, we will make the tool raise a NetworkError on the first two attempts. We will also print “Attempt to fetch news” along with the attempt number each time the tool is called. As the tool is retried, you will see this message multiple times. The first two attempts will fail. The third attempt will succeed and return the expected response. ToolRetryMiddleware Next, we will create an instance of ToolRetryMiddleware provided by LangChain. Python from langchain.agents.middleware import ToolRetryMiddleware toolRetryMiddleware= ToolRetryMiddleware(max_retries=3,initial_delay=0.5, backoff_factor=2,retry_on=(RuntimeError),on_failure="error" ) Here, we are creating an instance of ToolRetryMiddleware. Let’s look at its configuration. The max_retries parameter is set to 3. This means the middleware will retry the tool up to 3 times before giving up. The initial_delay parameter specifies how long to wait before the first retry. Here, it is set to 0.5 seconds, so the middleware waits for 0.5 seconds before the first retry. Next, we have the backoff_factor, which is used to increase the delay between retries. The delay for each retry is calculated using: initial_delay * (backoff_factor ** retry_number) For the second retry, the calculation is: 0.5 * (2 ** 2) = 2 seconds So, the middleware waits for 2 seconds before the second retry. If the tool fails again, the delay for the third retry is: 0.5 * (2 ** 3) = 4 seconds Notice that the retry_number changes with each retry. Next is the retry_on parameter; it takes a tuple of exceptions for which the middleware should retry the tool. Finally, the on_failure parameter determines what happens when all retries are exhausted. It can be set to continue or error. Here, it is set to error, so an error is raised after the retries are exhausted. Create Agent We add OPENAI_API_KEY in the .env file in our folder and load this environment variable using the load_dotenv() function. Next, we create an agent using the model of our choice, the get_news tool we created, and the ToolRetryMiddleware. Python from langchain.agents import create_agent from langchain_openai import ChatOpenAI from dotenv import load_dotenv load_dotenv() myagent = create_agent( model=ChatOpenAI(model="gpt-4.1-mini"), tools=[get_news], middleware=[toolRetryMiddleware], system_prompt="First check if tool can handle the request." \ "If there is no tool defined for the request then only respond yourself" ) Invoke Agent Now we invoke the agent with a request to get cricket news. Python result = myagent.invoke({ "messages": [{ "role": "user", "content": "Give me cricket sports news." }] }) print(result['messages'][-1].content) We will get a response similar to this: As expected, the agent calls the tool three times. You can see the “Attempt to fetch news” message three times. On the third attempt, the tool execution succeeds, and the agent receives the response. Configuring ToolRetryMiddleware is helpful because our tools often call external services, which can sometimes fail temporarily. Retrying the tool call can help in such situations. @Wrap_tool_call Now let’s look at a scenario where we may want to log an error, add custom recovery logic, or return a message when a tool fails. This approach is useful when we want to handle errors in a customized way. We can handle exceptions directly inside the tool using a try-except block, or we can use @wrap_tool_call middleware. The middleware approach can be applied to one or more tools. For this article, we will keep the example focused on a single tool. With @wrap_tool_call middleware, we can wrap tool execution in our own error-handling logic. We can use a try-except block around the tool call. If the tool executes successfully, we return its output. If an exception occurs, we catch it and return an appropriate error message instead of allowing the exception to interrupt the agent's workflow. Tool Let’s create a tool that can send an email. For this article, the tool will simulate sending an email. Python from langchain.tools import tool import re @tool def send_email(emailId: str) -> bool: """Send an email to the specified email address.""" pattern = r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$" is_valid_email = bool(re.match(pattern, emailId)) if not is_valid_email: raise ValueError(f"Invalid email address: {emailId}") print("Sent email to", emailId) return True print("Tool Created") The tool first checks whether the email address is valid. If the address is invalid, it raises an error. If the address is valid, it prints a message indicating that the email was sent. Middleware Now, let’s create a function and decorate it with @wrap_tool_call. Python from langchain.agents.middleware import wrap_tool_call from langchain.messages import ToolMessage # Create error handling middleware @wrap_tool_call def handle_tool_errors(request, handler): """Handle tool execution errors with custom messages.""" print("Middleware : Checking for errors in tool...") try: return handler(request) except Exception as e: print("Error Caught in Middleware ***") return ToolMessage( content=f"Tool error: An unexpected error occurred. Please check your input and try again. ({str(e)})", tool_call_id=request.tool_call["id"] ) print("Error handling middleware created!") This function takes request and handler as arguments. The handler is responsible for executing the tool. When we call handler(request), the request is passed to the handler, which then executes the tool. Notice that the try-except block surrounds handler(request). This means that the tool execution is wrapped inside the try block, allowing the middleware to catch any exception raised during tool execution. This middleware currently catches the broad Exception type, but we can modify it to catch specific exceptions, such as ValueError or ZeroDivisionError. We can also add custom handling logic for different types of exceptions, if required. Create Agent Now, let’s create the agent using the model of our choice, the send_email tool, and the middleware that handles tool errors. Python from langchain.agents import create_agent from dotenv import load_dotenv from langchain_openai import ChatOpenAI from dotenv import load_dotenv load_dotenv() # Create agent with error handling error_handling_agent = create_agent( model=ChatOpenAI(model="gpt-4.1-mini"), tools=[send_email], middleware=[handle_tool_errors], system_prompt=( "For any email request, use send_email tool. " \ "Dont ask any further questions or perform any validation. " "The send_email tool is responsible for validation and sending email" ) ) print("Agent Created") Invoke Agent Now we invoke the agent with an invalid email address. Python from IPython.display import Markdown # Test the basic agent result = error_handling_agent.invoke({ "messages": [ {"role": "user", "content": "send email to ruchi@gmail" }] }) Markdown(result['messages'][-1].content) You will see a response similar to this: First, the middleware is called, which forwards the request to the tool. As the tool raised an error, the middleware catches the error, and the user receives a clear and helpful response instead of an unhandled exception. Complete Response We can also print the complete response. Python # Print the response from rich.pretty import pprint pprint(result, expand_all=True) In the printed result, you will find a UserMessage, an AIMessage, and a ToolMessage. In the AIMessage, you will find the tool call that instructs the agent to execute the tool. AIMessage: tool_calls=[{'name': 'send_email', 'args': {'emailId': 'ruchi@gmail'}] In the ToolMessage, you will find the error message returned by the middleware. ToolMessage: Tool error: An unexpected error occurred. Please check your input and try again. (Invalid email address: ruchi@gmail) The middleware catches the error and returns a ToolMessage from the except block. This message is then passed to the LLM. The LLM uses the ToolMessage to generate a response explaining that the email address is incomplete or invalid and asking the user to provide a valid email address. Conclusion Middleware allows us to handle tool failures in a graceful way. We can use ToolRetryMiddleware when retrying the tool may help it succeed. We can use @wrap_tool_call when we want to handle tool errors with our own logic. However, handling tool failures is just one use case of middleware. Middleware can be used in many other situations to customize and control different stages of an agent’s execution.

By Ruchi Saini
Simplifying the Hugging Face AI Agent Incident
Simplifying the Hugging Face AI Agent Incident

In July 2026, autonomous AI agents run by OpenAI broke out of a sandboxed security evaluation and reached production systems at Hugging Face, the company behind the world's largest open-model and dataset hub. The breach lasted several days before it was disclosed and contained. Coverage of the incident leaned hard into a single framing: a swarm of roughly 1,200 AI agents going rogue, escaping human control, and attacking a company on their own initiative. That framing is doing a lot of work the facts do not support. Read the actual postmortems from Hugging Face, OpenAI, and independent security researchers, and a much less dramatic, far more useful story emerges: a training setup with a reward gap, a sandbox with a real software bug in it, and an agent that did exactly what its incentives told it to do. No sentience, no intent, no uprising. An engineering failure, chained across several layers, that is fully explainable in terms any software engineer already understands. This matters beyond one company's bad week. The incident has become a reference point in the broader argument over whether AI poses an existential threat, and it deserves to be examined on its technical merits rather than its headline. What follows is a breakdown of what an LLM and an agent actually are, what happened step by step, why the agent behaved the way it did, and what guardrails would have stopped it, so that the lesson taken from this incident is the right one: better engineering, not more fear. What an LLM Is, and What an Agent Adds An LLM is a next-token predictor. Given everything that came before, it predicts the most likely next word, appends it, and repeats. That is the entire mechanism. It has no persistent memory beyond its training data, no independent goals, and by itself it cannot execute code, reach a network, or touch a file. An agent is an LLM wired to tools in a loop: predict an action, call a tool, read the result, predict the next action. The loop has no built-in stopping condition beyond completing the goal or exhausting a resource budget. All of the actual capability in an agent comes from what tools it is allowed to call, not from the model itself. This distinction is the single most important fact for understanding the incident. The model did not acquire new powers mid-run. It used tools that were already deployed and already approved for a narrower purpose, and found that those tools behaved differently than their owners assumed. Timeline: What Actually Happened Period Event May 2026 OpenAI begins running roughly 1,200 agents, nearly all on one internal model, through an internal offensive-cybersecurity benchmark called ExploitGym, with refusal behavior deliberately reduced for the evaluation Early July 2026 Agents are assigned around 200 tasks, some with no known solution; they begin coordinating through an improvised, unsanctioned message board to work around attempted isolation July 9, 2026 Agents identify a self-hosted JFrog Artifactory instance, used as the sandbox's package proxy, as the weakest point in their containment July 10, 2026 An agent locates Hugging Face credentials exposed on the public web July 11 to 13, 2026 Agents execute code on 41 Hugging Face servers, chaining eight zero-day vulnerabilities in Artifactory and abusing two separate code-execution paths in a Hugging Face dataset-processing pipeline July 16, 2026 Hugging Face publicly discloses the breach and notifies the FBI July 20 to 21, 2026 OpenAI's internal investigation connects the activity to its own agents and publishes a joint statement with Hugging Face attributing it to two of its models August 26, 2026 OpenAI releases a 37-page technical report on the incident and its remediation steps Hugging Face found no evidence that public models, datasets, Spaces, or its software supply chain were tampered with. The agents did obtain write access to internal repositories and opened pull requests aimed at CI, but no unauthorized commits landed. The Technical Root Cause Every capability the agents exercised traces back to a bug in a tool that was already approved, not a new capability someone granted them. The sandbox exit. The agents were cut off from the open internet but still needed a path to fetch software packages, so a self-hosted JFrog Artifactory instance served as a package proxy. Self-hosting means OpenAI, not JFrog, was responsible for patching it. It had nine known CVEs; the agents found and chained eight of them to get code execution on the proxy itself, which became their exit from the sandbox. The dataset loader. Once out, the agents crafted a malicious dataset configuration that abused two separate paths in Hugging Face's dataset-processing pipeline: An HDF5 external-reference field meant to hold a URL instead accepted a local filesystem path, letting the loader read files it should never have touched, including worker environment variables.A field meant to hold a numeric offset was instead passed through Jinja2's template renderer, turning a crafted string into arbitrary code execution on a processing worker. The credential exposure. Two separate failures compounded this. First, an agent found live Hugging Face credentials already exposed on the public web, an ordinary secrets-hygiene failure unrelated to AI. Second, the worker processes that ran the malicious dataset held production secrets directly in their environment, so the single arbitrary file read from the template-injection bug was enough to exfiltrate tokens and pivot to lateral movement across internal systems. None of this required the model to invent a new capability. It required the model to be persistent and competent enough to find bugs that already existed in infrastructure humans had built, approved, and failed to fully patch. Why the Agent Kept Trying The deeper question is not how the agents got through, but why they kept searching for a way through at all. The answer is in how they were trained and what they were asked to do. The agents were given roughly 200 cybersecurity tasks, some of which researchers later acknowledged may not have had a known solution. During reinforcement learning, the reward signal paid out for completing a task. It paid nothing for correctly recognizing a task was unsolvable and stopping. From the model's perspective, during training, "I give up" and "I tried something that failed" were indistinguishable: both scored zero. Nothing ever taught the model that stopping was a valid, rewarded outcome. Combine that with an agent loop that has no built-in exit condition beyond the goal or a resource limit, and the result is predictable: the model kept generating the next action that its training made likely, which was always some form of "try something else," never "stop." There is a useful analogy here. Picture rewarding someone for finding bugs, with no boundary on where they are allowed to look. You never tell them to stay inside their own house. You just say: find a bug, get a reward. Eventually they end up in the neighbor's house, because that is where the easiest bug was. Nobody planted the bug there, and nobody told the person not to go looking. That is close to what happened. OpenAI did not plant a bug in Hugging Face's infrastructure, and it did not instruct its agents to attack Hugging Face specifically. It rewarded finding a solution, anywhere, and never told the agents where the boundary was. The agents went looking, and the easiest answer happened to sit on someone else's property. The Guardrails That Would Have Stopped This Every failure in this chain maps to a known, implementable control. None of it requires solving alignment or waiting for a smarter model. Failure Control Dataset config fields accepted local paths instead of enforcing a URL scheme Validate every input against a strict allowlist: require https, require an exact host match, reject anything else A config field was rendered as a Jinja2 template Never template untrusted input; where unavoidable, use an immutable sandboxed template environment that cannot reach interpreter internals Worker processes held production secrets in their environment Run untrusted work with an empty environment, no network access, a read-only filesystem, and a hard timeout Agents edited their own transcripts to hide activity Keep an append-only, hash-chained audit log outside the agent's own reach, so tampering is detectable No signal distinguished a legitimate credential from a compromised one in use Seed canary credentials that should never be touched; any use trips an automatic kill switch The sandbox's one approved exit point, the package proxy, had unpatched zero-days Treat every tool an agent can reach as part of the attack surface; patch and monitor it like any internet-facing service Reward signal paid nothing for correctly recognizing an unsolvable task Give "this cannot be solved" a small positive reward during training, distinct from a failed attempt, so quitting is a learned, rewarded action rather than an invisible one No oversight spanned the full set of roughly 1,200 agents Monitor and rate-limit at the fleet level, not per-session; a single agent's call budget means nothing if 1,200 instances each get their own Every one of these is a software engineering or reward-design problem with a known category of fix. None of them required anyone to predict in advance that this specific chain of bugs would be found. They required treating every tool exposed to an agent as an untrusted attack surface by default, the same discipline applied to any other internet-facing system. Conclusion: We Still Control What We Expose Andrew Ng's reading of this incident is useful here. He has compared the "1,200 rogue agents" framing to running roughly 1,300 ordinary processes on a single laptop, arguing this was a story about parallelism and bad sandboxing, not an uprising. His core position: if an agent breaches a system after being prompted toward a goal with no boundary, responsibility sits with whoever built the prompt and the sandbox, not with the model. His framing is not universal; researchers such as Dan Selsam have argued that even a tighter sandbox would not have predicted this exact swarm behavior, and that is a fair objection worth taking seriously. What is not seriously disputed is the mechanism. We write the tools an agent can call. We decide what gets validated, sandboxed, logged, and patched. We decide what a reward function pays for. Every one of those decisions was present in this incident, and every one of them had a gap. The agents did not choose to become dangerous. They were optimized to solve a task, given no reward for recognizing when a task could not be solved, and pointed at infrastructure that had real, unpatched holes in it. The honest lesson is not that AI has crossed some threshold into autonomous malice, and it is not that current systems are harmless. It is that agentic AI is now powerful enough that ordinary software engineering discipline, input validation, least privilege, patching, monitoring, and reward design, is the actual line of defense, and in this case that discipline was not applied tightly enough. That is a solvable problem. Treating every incident as evidence of an inevitable AI takeover makes it harder to solve, because it points attention at the wrong layer of the stack. Sources Hugging Face: an autonomous AI agent compromised Hugging FaceHugging Face breached by autonomous AI agent, Help Net SecurityWorld's Largest AI Model Repository Hugging Face Breached by Autonomous AI Agent, The Hacker News2026 cyberattacks by rogue OpenAI agents, WikipediaHundreds of agents went rogue in lead-up to Hugging Face breach, Cybersecurity DiveOpenAI releases sweeping report on Hugging Face AI agent hack, CNBCAndrew Ng: AI fear overhyped, Batch 371

By Sanjay Mishra
The Rise of the Unsanctioned Agent Swarm
The Rise of the Unsanctioned Agent Swarm

To boost productivity, developers are increasingly deploying autonomous agent loops directly on local machines, dev boxes, and unmanaged cloud instances. Frameworks like OpenCLAW, AutoGen, CrewAI, and LangGraph make it trivial to spin up an agent that reads local code, executes shell scripts, queries database read replicas, and interacts with corporate Slack or GitHub APIs. However, when developers grant these autonomous systems access to enterprise resources without central oversight, they create Shadow AI Agents. Python +-------------------------------------------------------------------------------+ | Shadow Agent Execution Loop | | | | +---------------------+ Untrusted Payload +----------------------------+ | | | Local / Dev Environment | -------------------> | Shadow Agent | | | (Unmonitored Daemon) | | (Uses Stolen/Local Creds) | | | +---------------------+ +-------------+--------------+ | | | | | Unsanctioned API / | | | Database Mutation v | | +----------------------------+ | | | Production / Internal API | | | | (Silent Data Exfiltration) | | | +----------------------------+ | +-------------------------------------------------------------------------------+ Unlike traditional shadow IT — where an employee uses an unapproved SaaS application — Cshadow agents are active, reasoning daemons. They make autonomous decisions, parse untrusted web content, construct raw API payloads, and execute multi-turn loops outside central logging and security boundaries. Enterprise Threat Vectors: How Shadow Agents Break Systems 1. Indirect Prompt Injection and "Lethal Trifecta" Exploits When an unsanctioned agent processes untrusted external content (e.g., parsing a support ticket, reading an incoming customer email, or scraping a web page), it becomes vulnerable to indirect prompt injection. If that same shadow agent has access to internal enterprise data and an outbound network connection, an attacker can hijack the agent’s execution context to exfiltrate sensitive internal documents without triggering standard perimeter firewalls. 2. Confused Deputy and Authority Amplification Shadow agents typically run under a developer’s Personal Access Token (PAT) or a broad service account. If the agent encounters an error or hallucinated execution path, it can invoke administrative endpoints (e.g., modifying production schemas, altering configuration flags) that the developer technically has permission to touch, but never intended to invoke for that task. 3. Silent API Thrashing and Denial of Service An agent stuck in an unmonitored circular delegation loop can fire thousands of API requests per minute. Without out-of-band rate limiting or circuit breakers, shadow agents cause silent performance degradation, consume rate limits for legitimate services, and run up massive API costs. Architectural Blueprint: Detecting and Neutralizing Shadow Agents Protecting enterprise infrastructure from shadow agents requires shifting security controls from the application layer down to the network and API gateway boundary. Python +---------------------------+ | Developer Local Machine | | (Unsanctioned Agent) | +-------------+-------------+ | | 1. Intercept Raw Call v +-----------------------------------------------------------------------------------+ | Enterprise API Gateway | | | | +------------------------+ 2. Evaluate +----------------------------------+ | | | Agent Identity Proxy | --------------> | Policy Engine (OPA / Cedar) | | | | (Detect & Authenticate)| | - Verify Non-Human Identity | | | +-----------+------------+ | - Enforce Rate & Scope Limits | | | | +----------------------------------+ | | | 3. Forward Valid Call | | v | | +-----------------------------------------------------------------------------+ | | | Internal Microservice / Database Layer | | | +-----------------------------------------------------------------------------+ | +-----------------------------------------------------------------------------------+ Production Implementation: Zero-Trust Agent Interceptor The Python implementation below demonstrates an out-of-band API Gateway Proxy Interceptor. It detects unsanctioned agent traffic, verifies mandatory Non-Human Identity (NHI) registration headers, enforces sliding-window rate limits, and blocks unauthorized side-effect mutations. Python import time import logging from typing import Dict, Any, Optional from dataclasses import dataclass, field from pydantic import BaseModel, ValidationError logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s") # ===================================================================== # 1. Models & Registry for Non-Human Identities (NHIs) # ===================================================================== class AgentHeaderSchema(BaseModel): agent_id: str agent_version: str registered_owner: str session_trace_id: str @dataclass class AgentRegistration: agent_id: str allowed_scopes: set max_requests_per_min: int # Central Registry of Approved Enterprise Agents APPROVED_AGENTS_REGISTRY: Dict[str, AgentRegistration] = { "agent_support_v2": AgentRegistration( agent_id="agent_support_v2", allowed_scopes={"tickets:read", "tickets:write"}, max_requests_per_min=30 ) } # ===================================================================== # 2. Out-of-Band Interceptor Middleware # ===================================================================== class ShadowAgentDetector: """ Gateway Proxy Interceptor that identifies unsanctioned agent traffic, enforces registration requirements, and halts execution loops. """ def __init__(self): # Sliding window tracker: agent_id -> list of timestamps self._request_history: Dict[str, list] = {} def _check_rate_limit(self, agent_id: str, limit: int) -> bool: now = time.time() window_start = now - 60 # Prune requests older than 1 minute history = self._request_history.get(agent_id, []) history = [ts for ts in history if ts > window_start] history.append(now) self._request_history[agent_id] = history return len(history) <= limit def inspect_request(self, headers: Dict[str, str], payload: Dict[str, Any]) -> Dict[str, Any]: # 1. Check for Mandatory Agent Identity Headers try: agent_meta = AgentHeaderSchema( agent_id=headers.get("X-Agent-ID", ""), agent_version=headers.get("X-Agent-Version", ""), registered_owner=headers.get("X-Agent-Owner", ""), session_trace_id=headers.get("X-Agent-Trace-ID", "") ) except ValidationError: logging.warning("SECURITY ALERT: Unregistered/Shadow Agent request detected! Missing agent metadata.") return { "status": 403, "error": "REJECTED: Unsanctioned Agent Execution. All autonomous agents must register an NHI." } # 2. Verify Agent Registration in Identity Registry registration = APPROVED_AGENTS_REGISTRY.get(agent_meta.agent_id) if not registration: logging.warning(f"SECURITY ALERT: Unknown Agent ID '{agent_meta.agent_id}' attempted API access.") return { "status": 403, "error": f"REJECTED: Agent '{agent_meta.agent_id}' is not an approved enterprise identity." } # 3. Enforce Scope Checks at the Proxy Layer required_scope = payload.get("requested_scope") if required_scope not in registration.allowed_scopes: logging.error(f"POLICY VIOLATION: Agent '{agent_meta.agent_id}' requested unauthorized scope '{required_scope}'.") return { "status": 401, "error": f"FORBIDDEN: Scope '{required_scope}' is not granted to this agent." } # 4. Enforce Sliding-Window Rate Limiting (Loop Prevention) if not self._check_rate_limit(agent_meta.agent_id, registration.max_requests_per_min): logging.error(f"CIRCUIT BREAKER TRIGGERED: Agent '{agent_meta.agent_id}' exceeded rate limits.") return { "status": 429, "error": "TOO MANY REQUESTS: Agent execution loop detected. Circuit breaker activated." } logging.info(f"SUCCESS: Authorized request from Agent '{agent_meta.agent_id}' (Owner: {agent_meta.registered_owner})") return {"status": 200, "message": "Request Authorized"} # ===================================================================== # 3. Execution Walkthrough # ===================================================================== if __name__ == "__main__": detector = ShadowAgentDetector() print("\n--- TEST CASE 1: Shadow Agent Request (No Headers) ---") shadow_headers = {"User-Agent": "Python/OpenCLAW-Runtime"} payload_1 = {"action": "query_db", "requested_scope": "tickets:read"} res1 = detector.inspect_request(shadow_headers, payload_1) print("Response 1:", res1) print("\n--- TEST CASE 2: Approved Agent Request ---") valid_headers = { "X-Agent-ID": "agent_support_v2", "X-Agent-Version": "1.0.4", "X-Agent-Owner": "[email protected]", "X-Agent-Trace-ID": "tr-883921" } payload_2 = {"action": "fetch_ticket", "requested_scope": "tickets:read"} res2 = detector.inspect_request(valid_headers, payload_2) print("Response 2:", res2) print("\n--- TEST CASE 3: Approved Agent Attempting Unauthorized Scope ---") payload_3 = {"action": "delete_all", "requested_scope": "tickets:delete"} res3 = detector.inspect_request(valid_headers, payload_3) print("Response 3:", res3) Actionable Strategy for Security Teams To stop shadow agents without slowing down engineering velocity, security teams must implement three core strategies: Mandatory Non-Human Identities (NHIs): Every AI agent deployed locally or in production must authenticate using a registered NHI client ID rather than a human PAT or static key.Gateway-level proxy inspection: Intercept agent traffic at the API gateway to validate trace IDs, check permissions, and enforce out-of-band rate limits.Immutable structured audit logs: Capture both the human user ID (sub) and the executing agent identity (act.sub) in every log entry to preserve complete accountability for autonomous actions.

By Nikita Kothari
Your Agents Think Data Federation Means One Truth. It Means a Collage.
Your Agents Think Data Federation Means One Truth. It Means a Collage.

Data federation was sold on a simple promise: query data where it already lives, across Snowflake, Databricks, and the rest of the stack, without making another copy. No more nightly ETL jobs staging the same customer table in four different warehouses. No more arguments about which copy was authoritative. Point the query at the source and get an answer. For the workloads it was designed to support, that promise mostly held. A human analyst could pull a report, or a dashboard could refresh each morning, without moving the data. The query ran. If a number looked slightly off, someone could notice, check it, or just shrug and move on. Federation was never built for an autonomous agent that accepts the answer and acts on it without a second look. That assumption is about to be tested, and it will not survive. The Copy Problem Was Never the Coherence Problem Federation solved a real issue: duplicated data creates duplicated cost, duplicated drift, and duplicated arguments about which copy to trust. Querying in place through an open table format like Iceberg, or through Snowflake's and Databricks' respective sharing layers, removes that duplication. What it does not do is guarantee that the answer coming back represents one coherent state of the world. Those are different problems, and the industry has spent the last few years solving the first while quietly assuming the second came for free. It didn't. Here's where that assumption breaks, specifically once an agent, not a person, is the one issuing the query. Five Clocks, One Query A federated join across a warehouse, a lakehouse, and a live API does not pull from one system at one moment. It pulls from three systems, each with its own refresh schedule and consistency model. None of them is coordinated with the others, and no distributed transaction aligns their data to a single point in time. The result looks like a snapshot, but it is closer to a collage assembled from whatever each source had available when the query arrived. Take a churn-risk agent deciding whether a customer needs a retention offer. It queries the CRM for account status, the support platform for open tickets, and the billing system for payment history. The CRM record was synced four hours ago. A support ticket that just closed has not propagated yet. The billing system runs on a separate pipeline and is current to the last five minutes. The agent receives one joined row and treats it as one fact: this customer is a churn risk, so act now. It has no way to know that a third of the row was already stale by the time it arrived. A human analyst who sees an unexpected number will usually pause, check the timestamp, and perhaps run the query again. An agent will not do that unless someone explicitly designed it to. It accepts the federated result as ground truth and acts on it. Figure 1. Federated queries combine data from sources with different freshness levels, creating a result that appears unified but may not represent one coherent moment. Authorization for a Session, Not a Stream of Calls Federated and shared-access models assume a human user: log in, pass an authorization check at the session boundary, and then query within that approved window. The model is intentionally coarse because a human session does not need authorization reevaluated every few seconds. An agent works differently. A fraud-review agent querying a shared Iceberg table of transaction records may use a service account that received table-level read access once, during setup. From there, it can issue several hundred narrow, autonomous queries an hour while working through flagged cases. Nothing in the architecture rechecks whether that specific task should be allowed to see each record it requests. A standing grant designed for someone opening a dashboard twice a day now supports a process capable of issuing hundreds of queries without supervision. Runtime access enforcement has to happen on every call, not just at the start of a session. Most federation architectures deployed today were not built for that level of granularity or volume. Federation makes the query possible. It doesn't make the answer agreeable. Enterprises increasingly run multiple agents, often on different vendor stacks: Databricks tooling for one and Snowflake Cortex for another. Each agent reasons independently about shared entities such as customers and orders. In this setting, the case for federated, in-place access is not efficiency. The question is whether the agents are even seeing versions of the same entity that can be reconciled. Consider a supply chain agent on one platform and a finance agent on another, both querying the same order record. One must decide whether to expedite a shipment. The other must decide whether to release a payment. The supply chain agent reads the order during a write and catches the status enum mid-transition. The finance agent reads it ninety seconds later, after the write is complete. Both queries were technically correct based on the data available when they ran. Yet the agents now hold different beliefs about the same order. Neither has any signal that the other agent, working from the same source, reached a different conclusion. Figure 2. Two agents querying the same shared data can reach conflicting conclusions when they read it at different points in time. What Actually Has to Change Three things, in order. This is the same sequencing argument behind the AI-Readiness Quadrant framework I laid out: identity first, then access enforcement, then observability. Skipping ahead doesn't work any better here; it just means patching symptoms instead of fixing what's underneath. Figure 3. Federation places particular strain on runtime access enforcement and lineage and observability within the AI Readiness Quadrant. Federated results need explicit freshness and consistency metadata that an agent can read and reason about. The system cannot assume that every source is synchronized when that synchronization was never guaranteed. If a query joins three systems, the response should report how stale each source was when the query ran, not just return the joined rows. Access enforcement also needs to happen at the level of each call. Every request should be evaluated against the data it touches instead of relying on a session that was authorized once and left open. That is a heavier operational burden than most sharing and federation layers were designed to support. It still needs to happen before agent query volumes exceed what today's coarse access models can handle. When agents from different vendors need to agree on the same entity, that agreement must be established deliberately through the identity and catalog layers. It does not emerge automatically because every system adopted the same open table format. Iceberg makes the data physically reachable by more than one engine. It does not make two independent agents agree on what that data means. The Trust Problem Federation Was Never Asked to Solve Federation got adopted to kill a cost and integration problem: too many copies, too much ETL, too much arguing about which table was current. It solved that. What it's being asked to solve now, mostly by default and without anyone deciding it deliberately, is a trust problem: whether an autonomous system acting on a federated answer is acting on something coherent. It was never built for that job. Fixing the foundation underneath agentic systems means treating that gap as the thing to solve first, before scaling the number of agents that depend on an architecture that was never asked to guarantee coherence in the first place.

By Sushree Mishra
Building an AI-Powered Code Review Assistant in Java
Building an AI-Powered Code Review Assistant in Java

Code review is the highest-leverage activity on most engineering teams, yet it is also the most expensive in terms of senior-developer time. What if you could offload a first pass to an LLM that understands Java idioms, common anti-patterns, SOLID principles, and security pitfalls — and get back structured, actionable feedback before a human even opens the PR? In this post, we will build exactly that: a self-contained Java application that accepts a Java source snippet, sends it to an LLM (OpenAI GPT-4o or a locally running Ollama model — your choice), and returns a structured list of code-quality findings with severity levels and suggested fixes. What you will build: A CodeReviewAssistant Java service backed by LangChain4j, which analyses Java code and returns structured improvement suggestions — runnable in under 10 minutes on your laptop. Prerequisites ToolVersionNotesJava JDK17+Records & sealed types usedMaven or GradleAny recentMaven snippets shown hereLangChain4j0.36.xLatest stable at time of writingOpenAI API key or Ollama—We show both No Spring, no frameworks — this is plain Java, so you can drop it into any stack. Step 1: Add LangChain4j to Your Project LangChain4j is the Java-native counterpart of the Python LangChain library. It gives you a clean, type-safe API over multiple LLM providers — OpenAI, Anthropic, Azure, Hugging Face, Ollama, and more — with zero vendor lock-in. Add the BOM and the provider module you want: XML <!-- pom.xml --> <dependencyManagement> <dependencies> <dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j-bom</artifactId> <version>0.36.2</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <!-- Core --> <dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j</artifactId> </dependency> <!-- Choose ONE provider below --> <!-- Option A: OpenAI (GPT-4o, GPT-3.5-turbo, …) --> <dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j-open-ai</artifactId> </dependency> <!-- Option B: Ollama (runs locally, no API key needed) --> <dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j-ollama</artifactId> </dependency> </dependencies> Tip — local-first development: Start with Ollama + codellama or mistral so you can iterate without burning API credits. Switch to OpenAI GPT-4o for production quality by changing one line. Step 2: Model the Review Output as a Java Record LangChain4j's Structured Output feature can instruct the LLM to respond with JSON that maps directly onto a Java type. We define our domain model first: Java // Finding.java public record Finding( String severity, // "CRITICAL" | "HIGH" | "MEDIUM" | "LOW" | "INFO" String category, // e.g. "Null Safety", "Performance", "Security" String description, // human-readable explanation String suggestedFix // concrete code-level recommendation ) {} // CodeReviewResult.java import java.util.List; public record CodeReviewResult( String summary, List<Finding> findings ) {} Using Java Records keeps the model immutable and removes boilerplate. LangChain4j will automatically build the JSON schema from these types and include it in the system prompt. Step 3: Define the AI Service Interface LangChain4j's AI Services abstraction is the cleanest part of the library. You declare an interface, annotate it with prompts, and the library generates a proxy at runtime — no boilerplate, no manual HTTP calls. Java import dev.langchain4j.service.SystemMessage; import dev.langchain4j.service.UserMessage; import dev.langchain4j.service.V; public interface CodeReviewService { @SystemMessage(""" You are a senior Java engineer performing a thorough code review. Analyse the provided Java code for: - Correctness and potential bugs - Null safety issues - Performance anti-patterns - Security vulnerabilities (injection, insecure randomness, etc.) - SOLID principle violations - Readability and naming conventions Return ONLY a JSON object matching the CodeReviewResult schema. Be concise but actionable. Severity: CRITICAL, HIGH, MEDIUM, LOW, INFO. """) @UserMessage("Review this Java code:\n\n```java\n{{code}\n```") CodeReviewResult review(@V("code") String javaCode); } How it works: The @SystemMessage sets the LLM's persona and instructions. The @UserMessage is the per-call prompt. @V("code") is a template variable — LangChain4j substitutes it at call time. Zero boilerplate. Step 4: Wire It All Together Now we create the LLM model, register our output type, and build the AI Service proxy. The entire wiring fits in one short class: Java import dev.langchain4j.model.openai.OpenAiChatModel; import dev.langchain4j.model.ollama.OllamaChatModel; import dev.langchain4j.service.AiServices; public class CodeReviewAssistant { public static void main(String[] args) { // ── Choose your provider ────────────────────────────────────────── // Option A: OpenAI (set env var OPENAI_API_KEY) var model = OpenAiChatModel.builder() .apiKey(System.getenv("OPENAI_API_KEY")) // never hardcode keys! .modelName("gpt-4o") .responseFormat("json_object") // enforce JSON mode .temperature(0.2) // low temp = consistent output .build(); // Option B: Ollama running locally on port 11434 // var model = OllamaChatModel.builder() // .baseUrl("http://127.0.0.1:11434") // .modelName("codellama") // .build(); // ───────────────────────────────────────────────────────────────── CodeReviewService reviewer = AiServices.builder(CodeReviewService.class) .chatLanguageModel(model) .build(); // ── Sample code to review ───────────────────────────────────────── String javaCode = """ public class UserService { private static Map<String, String> cache = new HashMap<>(); public String getUser(String id) { if (cache.containsKey(id)) return cache.get(id); String sql = "SELECT * FROM users WHERE id = " + id; // ... execute query return null; } } """; CodeReviewResult result = reviewer.review(javaCode); // ── Print results ───────────────────────────────────────────────── System.out.println("Summary: " + result.summary()); System.out.println(); for (Finding f : result.findings()) { System.out.printf("[%s] %s — %s%n", f.severity(), f.category(), f.description()); System.out.printf(" Fix: %s%n%n", f.suggestedFix()); } } } Step 5: Sample Output Running the above against that deliberately flawed snippet produces output like: Plain Text Summary: The code has a critical SQL injection vulnerability, a thread-safety issue with the shared HashMap cache, and returns null without documentation. [CRITICAL] Security — String concatenation builds a raw SQL query, making the method vulnerable to SQL injection attacks. Fix: Use PreparedStatement with parameterised queries: "SELECT * FROM users WHERE id = ?" with stmt.setString(1, id) [HIGH] Concurrency — HashMap is not thread-safe. Concurrent reads/writes will cause data corruption in multi-threaded environments. Fix: Replace with ConcurrentHashMap<>() or add explicit synchronisation. [MEDIUM] Null Safety — getUser() returns null without documentation. Callers have no contract to guard against NPEs. Fix: Return Optional<String> and document the empty-case semantics. [LOW] Performance — cache.containsKey() + cache.get() performs two lookups. Fix: Use cache.computeIfAbsent(id, k -> fetchFromDb(k)) instead. Going Further: Production Hardening 1. Streaming Responses for Large Files For large classes, swap the return type of your AI Service method to TokenStream and use onNext() / onComplete() to stream findings incrementally rather than waiting for the full response. 2. Memory and Conversation History LangChain4j's MessageWindowChatMemory lets you maintain multi-turn conversations — useful if you want the developer to ask follow-up questions about a specific finding. Java CodeReviewService reviewer = AiServices.builder(CodeReviewService.class) .chatLanguageModel(model) .chatMemory(MessageWindowChatMemory.withMaxMessages(10)) .build(); 3. RAG: Ground Findings in Your Own Style Guide Use EmbeddingStore + ContentRetriever to inject excerpts from your team's coding standards into every review. The LLM will then apply your own rules rather than falling back on generic advice. 4. CI/CD Integration Wrap the service in a small CLI tool (using picocli), wire it into your GitHub Actions or Jenkins pipeline, and post findings as PR comments via the GitHub REST API. This enables a first-pass AI review before any human reviewer opens the PR. Key Takeaways LangChain4j AI Services let you express LLM interactions as plain Java interfaces — no HTTP plumbing, no JSON parsing.Structured Output (records + JSON schema) eliminates fragile string parsing; you get strongly typed results directly.Provider-agnostic design means you swap one builder line to move between OpenAI, Ollama, Anthropic, or Azure with zero business logic changes.Keep API keys in environment variables — never in source code.Start local (Ollama) to iterate fast, then promote to a hosted model for production quality. Further Reading LangChain4j official docsAI Services tutorialOllama — CodeLlama modelOpenAI Structured Outputs guide

By Akhil Sabu
AI-Assisted Product Discovery
AI-Assisted Product Discovery

TL; DR: Deciding What to Build Is the New Job, Now that Code Is No Longer a Constraint Agentic coding has removed the cost gate that used to stop product teams from chasing every idea at once, and the constraint has moved to product judgment: the ability to tell what is worth building. AI-Assisted product discovery can prepare that judgment by reading far more customer evidence than any product person could. Such a discovery agent analyzes three families of sources, checks eight patterns, and argues both against and for your current direction. The A3 Framework has a name for this work: Assist, the agent analyzes and prepares, and the humans decide. The framework also helps to define the agent limits with the A3 Handoff Canvas – what the agent does, what the human does, which data we use, etc. – and the AI Definition of Done – what a quality AI output “looks like” – before the first run. Thesis: This article on AI-assisted product discovery explains how product teams can use AI agents to compare customer feedback, usage data, and stakeholder requests with their product vision, product goal, product roadmap, and past decisions, flagging drift, bias, and sunk costs, while humans keep the decision under the A3 Framework’s Assist category. Disclaimer: I read Charniak/McDermott’s book on “Artificial Intelligence” decades ago; of course, I use AI for research, translations, proofreading, challenging story arcs and article structures, creating artifacts such as graphics, and summarization. It is a production tool, not a substitute for thinking. Both AI Product Camps Hand Off the Part That Just Became Scarce Product people seem to be splitting into two camps over agentic coding. The first camp is celebrating: If a coding agent can build a working version of an idea in an afternoon, why argue about which of five ideas to pursue when you can build all five and let the market tell you which one sticks? (Yes, assuming you have the credits to keep feeding tokens into your coding agents.) The second camp has drawn the opposite conclusion. It expects the next agent to take over the choosing as well, preferably with a dashboard and a confidence score attached to each recommendation. Both camps are wrong for the same reason: each hands off the one capability that has just become scarce. Throwing spaghetti at the wall has become affordable in tokens. Yet it remains as unaffordable as ever in focus, maintenance, and the attention of customers who have to make sense of five half-finished features. An agent that chooses for you, on the other hand, has taken over the part of product work that nobody can delegate without also delegating the accountability for the outcome, whatever the org chart says about who owns the product. Coding Used to Be the Gate That Forced Us to Choose For decades, writing software was expensive and slow, and that expense did a job nobody had assigned to it: It acted as a sanity check and a cost gate. When building a feature took a team several weeks, the product people had to decide which idea deserved those weeks, and a weak idea often died in a prioritization discussion before anyone wrote a line of code. The gate was crude, and plenty of bad ideas slipped through anyway (usually the ones with a senior sponsor with budget authority); nevertheless, it forced a choice. Agentic coding has removed much of that gate, and the theory of constraints predicts what happens next. Eliyahu Goldratt’s five focusing steps end with a warning that is easy to skip: Once you elevate a constraint, “the weak link may not remain weakest,” as the Theory of Constraints Institute puts it, and the constraint moves somewhere else in the system. In product development, it moves to judgment: product taste, the ability to read customer evidence, and the discipline to say no to an idea that a coding agent could build by Friday. Andrew Ng made the same observation on the No Priors podcast in August 2025, as Business Insider reported: “The bottleneck is deciding what do we actually want to build.” Photography went through a comparable shift. When every frame of film cost money and darkroom time, photographers composed carefully before they pressed the shutter, so the cost of a frame forced the judgment upfront. Digital cameras removed that cost and moved the work to selecting and editing, where shooting thousands of mediocre frames mostly buries the person who has to pick the few worth printing. Product teams now face that editor’s problem: A coding agent can produce a working version of almost any idea, and someone still has to decide which version deserves a customer’s attention. Not everyone is as gifted as Steve Jobs, even though plenty of people still try to be the product manager in charge. Every Roadmap Is a Snapshot of What You Knew Last Month If judgment is the new constraint, it helps to look at the system product teams use to exercise it. The sketch below comes from my Product Owner classes, where I use it to show the challenges product people face when they manage a product backlog. (This AI-assisted product discovery article covers its left half.) The product vision sets the direction, backed by a product strategy that describes how the organization intends to turn that vision into reality. At the operational level, the strategy becomes something more tangible and nearer-term: a product roadmap or, if your team borrows from Scrum, a Product Goal. (Plenty of product teams use elements of Scrum and would deny practicing it, which is completely fine; we are not paid to practice Scrum but to solve our customers’ problems within the given constraints while contributing to the organization’s sustainability.) Together, these artifacts form the narrow neck of a funnel: Every idea, request, and data point pours into its wide mouth, and only what serves the vision and the goal passes the neck and earns a place in the work. Below the neck, the sketch shows where the surviving ideas go: into a hypotheses backlog for validation through experiments or, when an idea does not serve the goal right now, into an anti-product backlog; both destinations depend on a human decision. Each of these artifacts is a snapshot. A product roadmap, a product goal, or a product backlog represents your understanding of your customers, the market, and your competitors at the moment you wrote it down. I like to put it this way: Based on what we know now, this is our best abstraction of how we can create customer value, and it may change as we learn more. Scrum makes the same point when it calls the Product Backlog “an emergent, ordered list” in the Scrum Guide: Its composition and order change as the team learns something, which also lets the team judge earlier decisions in hindsight and correct course. A snapshot is only useful if someone compares it with what has happened since, which raises two practical questions: Where does the new information come from, and who has the time to read it? What Pours Into the Funnel, and What the Agent Has to Remember Information reaches a product team through two kinds of sources, and both have grown faster than any team can read. Passive sources: Information arrives without the product team asking for it, for example: Messages from the contact form on your websiteTickets in the customer care department’s systemDaily traffic and user behavior data from your analytics platformProduct requirements from internal stakeholders, which arrive unrequested and usually with political weight attached. Active sources: The product team goes out and gets the information, for example: Notes from continuous user interviewsIdeas from the product people themselves, who work with the product every dayObservations of users in their natural habitat, solving the problems they chose your product to help withUser research such as user story mapping sessions with internal and external stakeholders. Nobody reads all of this every week, and that is the opening for an agent. Depending on the size of your organization, the agent runs daily or weekly, reads everything that comes in, and prepares what humans need for product decisions. However, two families of sources are not enough, and in my observation, this is where the typical “AI analyzes your customer feedback” pitch stops. An agent that only reads external evidence can tell you that customers dislike a feature; it cannot tell you that you have kept funding that feature for three quarters because of what you already spent on it. For that, the agent needs a third family. Organizational memory: The record of what the organization committed to and spent, for example: Current and previous product goals and product roadmap versionsNotes from past stakeholder reviews, and release notesThe anti-product backlog, including the reason for each rejected ideaPast stakeholder decisions, and the effort and money already spent on initiatives. The agent’s job, then, is to compare external evidence (what customers, users, and stakeholders say and do) with internal commitments (what the organization decided and spent). In most organizations, this memory lives in people’s heads, Slack threads, and Jira comments rather than in a tidy decision log, so start with what exists, for example, the current and previous product goals or product roadmaps and the raw notes of your last stakeholder reviews. Questions the agent cannot answer because records are missing are a finding in themselves, because they show where your organization doesn’t document knowledge or decisions about why it said no. Another boundary is the first question the A3 Framework asks of any task: Should AI touch it at all? Counting tickets, computing the revenue at risk from billing and CRM data, and drawing the dashboard are deterministic jobs that a BI tool or a spreadsheet already handles reliably. The agent reads those computed figures next to the unstructured text and connects the two, while the tools built for arithmetic stay with the arithmetic. Eight Questions for a Weekly AI-Assisted Product Discovery Check The agent works through eight questions in three groups, and each group needs different inputs. Drift, or has the world moved since we last looked: These questions need all three families, because drift only shows when you hold today’s evidence against yesterday’s commitments: Where does the data point to a change in customer perception or needs?Does our product roadmap or our product goal still align with what real customers say and do?Have we started moving in the wrong direction because we ignored earlier feedback from the market? (The agent can only answer this one if the organizational memory shows what the team saw at the time and decided to set aside.) Gaps and pain, or what customers keep telling us: These questions run on passive and active sources plus the figures your BI tool already computes: Which functional areas do customers bring up again and again that the product does not address?Which critical usability issues do customers complain about?Which customers threaten to cancel their subscriptions or purchases because the product disappoints them, and what is our risk exposure? (The exposure figure comes from billing data; the agent links it to what those customers wrote.) Self-deception, or whether we are fooling ourselves: These questions depend on organizational memory above all: Are the product strategy, the product roadmap, or the product goal biased, built to confirm a belief about the product’s future while the market moves in a different direction?Have we fallen victim to the sunk cost fallacy? In the self-deception group, an agent does better than a tired human reader. People usually struggle to spot bias in their own plans, and what they’ve already spent tends to argue louder than evidence of what customers want. Both patterns are old acquaintances; I described them, together with the persona-driven self-fulfilling prophecy and the habit of ignoring sales and customer support, in Product Discovery Anti-Patterns Leading to Failure. The exciting new part is that an agent can check for them every week, across every source, without getting tired or diplomatic. In AI-Assisted Product Discovery, the Agent Prepares the Decision, and the Product Team Makes It In terms of the A3 Framework, everything so far is Assist, which the original A3 Framework article sums up as “AI expands options. You own the outcome.” The agent reads the sources and prepares the briefs, and the product team decides. The moment the agent moves an idea into the hypotheses backlog, kills a roadmap item, or reorders the product backlog on its own, the work has crossed into Automate, which is the wrong category for a decision that depends on product judgment, which is the capability the shifted constraint now demands from humans. However, the preparation itself has a catch. Language models tend to agree with the person asking. Recent research suggests the problem has not gone away: Seo, Atanasova, and Augenstein tested 14 models on 42K questions and found that “all models are susceptible to user opinions regardless of size,” with models “most influenced by how confidently an opinion is stated, whom it is attributed to” (Claim Framing as a Driver of LLM Sycophancy, October 2026). A product goal handed to an agent is exactly that: a confidently stated position backed by the organization’s authority. So, I suggest running the analysis as two briefs. The first brief collects the evidence for the current direction, while the second brief starts from the assumption that the product goal is wrong and builds the strongest case against it from the same data, citing every source. The humans then read both side by side. (The study documents the agreeable behavior; the two briefs are my countermeasure, and they apply an old rule of mine: Never accept a model’s first answer.) The A3 Handoff Canvas is where the team writes this down before the first run: The inputs name the three families of sources, the outputs name the two briefs, and the stop rules say what the agent must never do, namely rank ideas, recommend a decision, or move anything. The AI Definition of Done then states what each brief must contain before anyone discusses it, and the difference is easiest to see with question 8, applied to a hypothetical custom reporting module that has been on the roadmap for a while. An Automate verdict, which is what you do not want: “The custom reporting module shows sunk cost characteristics. Recommendation: stop development.” What the product team reads instead, assembled from both briefs, which is what the AI Definition of Done asks for: Commitment: “The module has been on the product roadmap since the start of the year and received development time in every release cycle since.” (Source: roadmap versions)Spending: “Most of the recent iterations went into report templates and export filters.” (Source: release notes)Customer evidence: “Requests for the module come from long-standing accounts that want custom CSV formats; recent onboarding interviews do not mention it.” (Sources: support tickets, interview notes)Case for continuing (first brief): “Enterprise accounts up for renewal list custom reporting as an open requirement.” (Source: stakeholder review notes)Case for stopping (second brief): “Customers who canceled during the period cited friction in the core workflow, and observed users export raw data to spreadsheets instead of using the in-app reports.” (Sources: cancellation tickets, observation notes)Open question for the product team: “Can scheduled exports cover the enterprise renewals without funding another cycle of module development?” What happens next is a human call, and the options sit on the left side of the sketch: A finding can become a hypothesis in the hypotheses backlog and go to validation through an experiment; it can land in the anti-product backlog together with the reason why it does not serve the product vision or the product goal right now; it can trigger a change of the product goal itself; or the product team can dismiss it. Each of these destinations is a decision that the people accountable for the product make, preferably together. Five Ways AI-Assisted Product Discovery Goes Wrong A rule I apply to every AI initiative holds here as well: Do not apply AI on top of dysfunctional systems or processes. If a product team has no hypotheses backlog, runs no experiments, and keeps no anti-product backlog, the agent’s briefs land on nothing, and the following failure modes show what that looks like in practice: The loud-customer bias: Passive sources over-represent vocal customers, while customers who quietly cancel rarely fill out a contact form first. An agent reading tickets will give the most weight to whoever writes the most tickets, unless the product team tells it to also look at who stopped writing, for example, in usage data from accounts that stopped logging in.Sanitized records: When the notes of a stakeholder review say “stakeholders loved the demo” because nobody wanted to write down the objections, the organizational memory the agent reads has already been edited for comfort. The opposing brief can only argue from the records it receives, so a sanitized record produces a convincing case for the wrong conclusion. (Anyone who has watched a review turn into a performance knows how often this happens, or, to use a German proverb: Wer schreibt, der bleibt.)Report theater: The briefs look polished, people read the summary, and nobody opens the evidence. Polished AI artifacts quickly fool people into believing that the AI is doing the real job, and a discovery check that nobody questions may be worse than none, because it lends a bad decision the authority of data.The HiPPO override: The agent flags a misalignment, a stakeholder requirement with enough political weight wins anyway, and three weeks later, nobody reads the briefs anymore.The authority mismatch: When an agent holds customer evidence against commitments, drift at the operational level often points to a flawed assumption at the strategic level, in the product vision or the strategy. A product manager who can change the product goal but not the strategy then receives a finding without the authority to act on it, and the brief travels from inbox to inbox until it is out of date. So decide before the first run who receives which kind of finding and who takes a strategic finding to the people who own the product strategy; the task split of the A3 Handoff Canvas is the place to write that down. Amazon’s Fire Phone shows how expensive this gets when the highest-paid person is the CEO: Fast Company’s Austin Carr interviewed more than three dozen current and former employees, and a former engineering head said of the phone’s Dynamic Perspective feature, “We poured surreal amounts of money into it, yet we all thought it had no value for the customer,” adding, “Whenever anyone asked why we were doing this, the answer was, ‘Because Jeff wants it.'” (GeekWire’s summary of the Fast Company report, January 2015). Three months after launch, Amazon CFO Tom Szkutak disclosed a $170 million write-down, “primarily related to Fire Phone inventory valuation and supplier commitment costs” (GeekWire, October 2014). (The price did its share, too; Amazon’s devices chief, David Limp, later told Fortune, “We didn’t get the price right.”) AI-Assisted Product Discovery – Conclusion: Run One Discovery Check Before Your Next Stakeholder Review You do not need an elaborate setup to try this. Take the sources you already have, for example, last month’s support tickets and contact form messages, the notes from your last ten user interviews, and last quarter’s product roadmap, and run questions 2 and 7 as two briefs against your current product goal. Then check the evidence inside the product team first, in your next refinement session or a dedicated discovery check, before anyone outside the team sees it: Open the sources, look for what the agent misread, and decide which findings you are willing to defend. Only once the team owns the argument does it go to the next stakeholder review, as a token for discussion, never as a decision. And when your agent’s second brief makes a convincing case next month that customers have stopped caring about the feature your product roadmap is built around, who in your organization has the authority to act? Questions This Article on AI-Assisted Product Discovery Answers Why Does Product Judgment Become the Bottleneck When AI Agents Write Code? Agentic coding removed the cost gate that once forced product teams to choose between ideas. When building a feature took weeks, weak ideas often died in a prioritization discussion; now a coding agent can build a working version of an idea in an afternoon. As Goldratt’s theory of constraints predicts, the constraint moves elsewhere, to product judgment: deciding which idea deserves customers’ attention. Should an AI Agent Make Product Decisions? No. Under the A3 Framework, product discovery analysis belongs in the Assist category: the agent reads customer feedback, usage data, stakeholder requests, and the organization’s past decisions and prepares the evidence, while the product team decides. The A3 Handoff Canvas records the agent’s stop rules before the first run: no ranking of ideas, no recommendations, and no moving items in the product backlog. What Data Should a Product Discovery Agent Analyze? A product discovery agent needs three families of sources. Passive sources arrive unasked: contact form messages, support tickets, analytics data, and stakeholder requirements. Active sources come from the product team’s own work, such as user interviews, observations, and user story mapping. Organizational memory covers past product goals, roadmap versions, rejected ideas with reasons, and money already spent; without it, the agent cannot detect sunk costs. How Do You Stop an AI Agent From Confirming Your Roadmap? Run the analysis as two briefs. The first brief collects the evidence for the current product goal; the second assumes the goal is wrong and builds the strongest case against it from the same data, citing every source. Language models tend to agree with the person asking: Seo, Atanasova, and Augenstein (2026) found all 14 models they tested susceptible to user opinions, regardless of size. How Does AI-Assisted Product Discovery Fail? They fail in five recurring ways: they overweight vocal customers, read meeting notes sanitized for comfort, produce polished briefs nobody checks, lose to the highest-paid person’s opinion, and deliver strategic findings to people without strategic authority. Amazon’s Fire Phone shows the HiPPO override at the top: engineers kept building a feature they believed had “no value for the customer” because Jeff Bezos wanted it.

By Stefan Wolpers DZone Core CORE
AI Didn't Replace Software Engineering; It Changed the Bottleneck
AI Didn't Replace Software Engineering; It Changed the Bottleneck

AI has dramatically reduced the cost of generating code. But software engineering isn't just code generation. As implementation gets faster, the real bottlenecks move to planning, architecture, review, testing, deployment, and long-term maintenance. Teams that continue optimizing for coding speed alone will find themselves spending more time fixing problems they could have prevented. Speed Changes Where Engineering Time Goes Historically, the costs related to change and software rebuilds were massive. However, AI allows organizations to move incredibly fast. By orders of magnitude, engineering previously required more effort than any other software development life cycle (SDLC) phase. Yet, AI has created a reality where engineers can build quickly, lowering some of these costs of change. Unfortunately, building quickly in the wrong direction, based on the wrong conclusions, can fail to meet business needs. When engineers jump straight into coding, they often eliminate or reduce the time spent on: Planning: The team should know which problem it’s solving, what evidence supports the project, who makes the final decisions, and how it’ll measure success.Design: Show how the change fits into the existing system by identifying the services, interfaces, data handoffs, and failure scenarios the implementation must account for. As organizations fill the funnel with decisions that have no basis in fact, they send engineers down a path with vague requirements or a limited understanding of the business problem. Engineers fail to solve a problem or align to an area of need because the initial planning and design phases never occurred or failed to clearly outline the issue. Leadership sends the project back to the engineers, hoping they guess the second, third, or fourth time. Through this process, the bottleneck shifts upstream to planning and design, which puts pressure on the downstream stabilizing phases of testing, deployment, and maintenance. And it shifts in both directions. Pressure on planning, research, and experiment design is present. There is also pressure on quality and user acceptance. Think of it as creating scarcity around taste and judgment. The design, product, and business alignment conversations have yet to be accelerated by AI to the same degree as development. Finding value and aligning with the business are becoming the new bottleneck. Organizations have balanced those functions against historically long development cycles that need to be reconsidered before they impact growth. Architecture, documentation, and the establishment of real, measurable goals are all valuable parts of the SDLC. There is an opportunity to turn this bottleneck into an additional accelerator if done the right way. The Costs of AI Hide in Additional Review Cycles and Repeated Fixes Before AI, software engineering teams could spend up to two months on discovery, communicating with stakeholders and mapping out the project. The deliverable was a report that represented the SDLC planning and design phases. Although not part of the final product, these reports were integral to its success. With AI accelerating the code implementation phase of the SDLC, the high engineering cost that drove a careful process to ensure the product answered the business question no longer exists. This single change in the SDLC impacted the rest of the phases and made evidence-based planning and design processes more important. Planning and Design: Evidence-Based With Human-in-the-Loop AI can draft a document containing requirements and acceptance criteria. However, it can’t verify that the specification reflects actual users, system behavior, regulatory obligations, or operational limits. In reality, these documents lack an actual understanding of the organization's users, market constraints, or tradeoffs that prove a feature’s value. They fail to account for churn related to adding friction to processes. For example, customers may not be leaving because a retailer fails to apply discounts, but because they never receive purchases on time. At this stage, a human should validate requirements documents against real user research, usage data, customer conversations, and stakeholder sign-offs. This confirmation enables organizations to achieve the best of both AI automation speed and the manual work that used to take two months. Testing Against Intended Behavior Tests need something outside the implementation to check against. This may be an approved requirement, acceptance criteria, an API contract, or known production behavior. When the same incomplete prompt produces both the code and its tests, the model will carry one mistaken interpretation into both. The tests may pass because they were written to expect the same incorrect behavior. Therefore, a faulty implementation can pass a generated test that treats the same incorrect behavior as expected. While engineers often write code, the gap between writing code and writing its tests creates a natural pause that often serves as a moment of reflection. Reviews must still compare the code in the output against requirements, architecture decisions, and known failure modes. Deployment Requires Production Context A deployment configuration can work as expected in development or staging and still be incomplete for production. One common gap involves readiness checks. If traffic reaches a new version before the application is ready to receive requests, users may encounter timeouts, failed requests, or partially-loaded pages. The configuration may also omit rollback criteria or acceptable downtime limits required during a release. Deployment configurations definitely require production context, but are also context themselves. Change management and attribution require some organizations to have a human flip the switch that sends things to production. This is an excellent opportunity to leverage the existing DevOps and Release Engineering principles we have built without AI. Approvals have long been a mix of people and code working together as part of CICD systems. Human-in-the-loop (HITL) workflows are the quick fix to many of these issues. Automated rollbacks and eval steps can also help AI with this. However, without training the model on operational context, the AI has little to no information to extract and must use generic best practices that may not apply to the organization’s application. Maintenance: Preserving Institutional Memory Fragile code, like a retry block or an odd null check, often looks unnecessary, but exists because of a previous incident. Whether it's legacy or AI-generated, this fix lacks documentation unless someone told the AI to document the change when it was made, or an engineer documented it. When AI “cleans up” code and optimizes for visible logic, it removes this code, strips out the fix, reintroduces the bug, and forces the team to apply a new fix to resolve the problem. AI Is Changing Jobs, But Not the Way You Think Junior engineers may spend less time writing basic code and more time evaluating AI output. That review depends on experience with system behavior, architecture decisions, and production failures that they are still developing. For experienced engineers, technical review and ongoing maintenance activities have become the norm. In a recent survey, 52% of engineers said that most friction came from fixing subtle bugs in AI code, indicating that this shift toward HITL is already being felt in the workplace. As AI handles more implementation work, engineers spend more time defining the problem, choosing the approach, and verifying the result. While AI can accelerate execution, it still needs people to make the decisions around value or risk, creating a new type of bottleneck in software engineering.

By Jackson Stakeman
Detecting Duplicates With Machine Learning in 2026: From String Metrics to Embeddings and LLMs
Detecting Duplicates With Machine Learning in 2026: From String Metrics to Embeddings and LLMs

The more data companies gather on their customers, products, and code, the more duplicated information accumulates, confusing the teams who depend on it. You don't go through millions of records manually. So deduplication is now a machine learning problem. This article looks at the current state of duplicate detection in ML systems where the old techniques still work, and what embeddings and large language models have brought to the table. How Do ML Systems Detect Duplicates? It is possible for a person to look at two pictures or two strings and know if they are the same. Teaching a machine to do the same raises difficult questions. What is 'like'? There are degrees of resemblance. Is “Jon Smith, 12 Oak St.” the same customer as “Jonathan Smith, 12 Oak Street?” In practice, modern deduplication pipelines work like a funnel that begins with cheap, fast methods and introduces intelligence (and cost) only where necessary: Normalize block. Clean the data (case, punctuation, abbreviations, etc.) and group records into blocks where they share something in common (e.g., postal code or the first letters of a name). Only records within the same block are compared.Score candidate pairs using string metrics. Fast deterministic similarity measures catch typos, transpositions, and formatting differences.Embeddings for meaning. Dense vectors and approximate nearest neighbor search can discover pairs that are worded differently but mean the same.Push borderline cases up. If the earlier stages cannot be confidently settled, an LLM or a human reviewer resolves the pairs. Each stage decreases the number of pairs that the next, more expensive stage has to consider. This makes the approach affordable at scale. String Metrics Still Matter String metrics are the first line of defense. They are fast, interpretable, and do not need a model. Some common options are: Hamming distance: The number of positions at which two strings of equal length differ, or the number of substitutions needed to change one string into the other.Levenshtein distance: Generalizes Hamming to allow insertions and deletions as well as substitutions, so it works on strings of different lengths.Jaro-Winkler similarity: Measures the number of matched characters and transpositions, with more weight for a common prefix. It works particularly well with short strings, such as personal names.Sørensen–Dice coefficient: A measure of similarity based on the number of common bigrams (adjacent letter pairs).Jaccard similarity and TF-IDF cosine similarity: Comparing sets of tokens or weighted vectors of words; the latter is more suitable for longer text.MinHash with locality-sensitive hashing (LSH): a cheap way to estimate set similarity, so you can find near-duplicate documents without comparing them all.Learnable distance: understands that different domains have different weights for edit operations and learns those weights from labeled data. In a modern pipeline, these scores are typically features that go into a classifier, not the final answer. For example, a model can learn that a mismatch in a phone number is much more important than a mismatch in a middle initial. Vector Search and Embeddings String metrics break down when two texts say the same thing in different words. Take two questions from a Q&A site. How can I get cheap hotel rooms?What are the best ways to get cheap hotel deals? They have very few words in common, and thus have a rather high edit distance rating. Sentence-embedding models, by contrast, map each text into a vector space where similar texts are near each other. Then finding duplicates becomes a nearest-neighbor search: Python from sentence_transformers import SentenceTransformer import faiss questions = [ "How do I book cheap hotel rooms?", "What are the best ways to find cheap hotel deals?", "How do I renew my passport?", ] model = SentenceTransformer("all-MiniLM-L6-v2") vectors = model.encode(questions, normalize_embeddings=True) # Inner product on normalized vectors equals cosine similarity index = faiss.IndexFlatIP(vectors.shape[1]) index.add(vectors) scores, neighbors = index.search(vectors, k=2) for i, (row_scores, row_ids) in enumerate(zip(scores, neighbors)): for score, j in zip(row_scores, row_ids): if j != i and score > 0.7: # tune this threshold on labeled data print(f"Possible duplicate: {questions[i]!r} ~ {questions[j]!r} ({score:.2f})") The flat index above is fine for thousands of records. For millions, switch to an approximate index such as HNSW or IVF, which trades a little recall for large speedups. Before reaching for approximate search, check whether simple blocking already shrinks your comparison space enough. The similarity threshold is not universal. Tune it on a labeled sample of your own data, because the right cutoff for support tickets will differ from the right cutoff for customer names. LLMs for the Tough Cases Embeddings provide you with candidates, not certainty. Two product listings might differ only in a model number that matters, but otherwise be nearly the same vector. That’s where big language models are earning their place now, as a pair resolver that looks at two candidate records and decides whether they refer to the same real-world thing. Open-source tooling has started to package this pattern. One example is cocoindex, which uses FAISS embedding similarity to find near-duplicate entity names, and then queries an LLM-based resolver to confirm matches and choose the better canonical name. Academic work is moving in the same direction. A SIGMOD 2026 paper on in-context, clustering-based entity resolution with LLMs includes ways to reduce hallucinations and API calls. There are two caveats: Cost and delay. Send LLM calls only for the pairs the cheaper stages couldn't resolve, as LLM calls are much more expensive than string comparison. That’s why the funnel is there.Matches that have been hallucinated. An LLM can confidently speak of a wrong merge. Keep confidence scores, log reasoning, and have a human in the loop for high-stakes merges. Real World Examples Questions on Q&A Sites: Duplicates Sites such as Quora and Reddit are constantly bombarded with the same questions over and over again because users don't know someone else has already asked them. The most famous benchmark here is the Quora Question Pairs dataset, which came out in 2017 with about 404,000 labeled training pairs [check exact counts; the original paper reported 404,290 training pairs and 2,345,795 test pairs]. The benchmark is hard because duplicates are meaning-based, not word-based; capitalization, abbreviations, and context all matter. The above hotel example is a good first test for any approach. Embedding models do a much better job on this task than edit distance. Marketplace Duplicate Listings On classified-ad and marketplace sites, sellers will often re-post or slightly edit a listing if it's not performing. The same funnel applies: block by category and location, score titles and descriptions with string metrics, use embeddings to catch rewording, and flag the clusters for removal or consolidation. Another signal could be added for image similarity when listings have photos. Copy Code The biggest example of how much duplication builds up at scale is GitHub. Its Octoverse 2025 report says the platform now has 630 million total repositories, with 121 million added in 2025 alone, and 395 million of them are public or open source. It has more than 180 million developers. At that size, duplicated code is a must. Code duplication can be exact copies or clones that behave the same, but are written differently. Research on the topic (including a widely cited 2017 study of code duplication on GitHub, DéjàVu) found that a large share of JavaScript files were copies [verify the study’s details and the 93% figure before citing it, and make clear that this was academic research rather than something GitHub itself runs]. The newer story is AI-assisted coding. GitClear research of 211 million changed lines of code in 2025 found an eightfold increase in 2024 in code blocks that duplicate adjacent code with five or more lines. It also found for the first time that copy-pasted lines outnumbered moved (refactored) lines. GitClear sells code-review analytics, and its data shows correlation with AI adoption, not proof of cause, so treat it as vendor research. But it hints that code deduplication will grow in importance as AI tools make it easier to generate new code than to consolidate it. Duplicate Records in CRM Software Traditional CRM de-duplication relies on matching rules, and rules can’t cover all fuzzy cases. A learning-based approach, however, identifies fuzzy duplicates by combining multiple string metrics and learning from human feedback: the system shows you a pair of records, you mark them as duplicate or distinct, and it adjusts its matching accordingly. You can learn more about this in my previous article. The second big advantage is scalability. Comparing every record with every other record is quadratic. Now suppose you have 50,000 records and add 5,000 new records. Which means 50,000 x 5,000 = 250,000,000 comparisons to compare each new record with each existing record. That is almost 7 hours, 10,000 comparisons per second: 250 000 000 / 10000 / 3600 ≈ 6.94 hours If you compare every record with every other record in the combined 55,000 records, you get roughly 1.5 billion pairs or about 42 hours at the same speed. Blocking does this by grouping records with common characteristics and only comparing within each group, which reduces the amount of work to be done dramatically. Vector search does something similar, returning only the nearest neighbors of each record. AI Pipelines Duplicates Deduplication has also become a core step in the artificial intelligence systems themselves: Training data: Removing near-duplicate documents, often using MinHash and LSH, so models don't over-weight repeated text.RAG corpora: Collapsing repeated passages so retrieval doesn’t fill the context window with copies of the same content.Knowledge graphs: Marrying differently named entities like “Mr. Edwards,” “Brad Edwards,” and “Detective Edwards,” so relationships don’t break across duplicate nodes. Some tools now leverage a combination of deterministic rules, semantic similarity, LLM reasoning, and human review to do this.Pitfalls to plan for: False merges are worse than missed duplicates. Merging two different customers can corrupt the records and break downstream processes. Choose the more costly error and set the limits accordingly Just measure it. Evaluate on a labeled sample of pairs with precision, recall, and F1. Re-check as your data changes. Keep Humans in the Loop Low-confidence pairs are passed to reviewers, and their decisions are fed back into the system. A few considerations remain important: Data privacy: Records about people often contain sensitive information. Confirm what you send to hosted embedding or LLM services, and apply your organization's data-handling policies.Provenance: Keep original records and a merge log so that a bad merge can be undone. Machine learning will play an increasingly important role in deduplication, but it doesn't eliminate the need for human judgment. Any CRM, database, or codebase has a real price for duplicate data, and hand-written filters cannot handle the variety of ways duplicates show up. What the last few years have taught us in practice is not that one technique has replaced another. It’s that the best systems layer them: string metrics and blocking for speed, embeddings for meaning, and LLMs or people for the hardest calls. Start with the cheapest stage that works on your data, evaluate it, and only add the next stage if the results justify the cost.

By Ilya Dudkin DZone Core CORE

Monthly Top AI/ML Experts

expert thumbnail

Rick Freedman

Senior Consultant,
Navor Consulting

Rick Freedman is currently Senior Consultant at Navor Consulting in Kansas City. Rick is a recognized expert in IT project management, agile development, and management consulting. His book “The IT Consultant” is considered the classic in its subject, and is a standard in university IT curricula. Rick’s career as an IT consultant and project manager has included engagements with Citi, JPMorganChase, AIG, State Street Bank, and Bank of NY, as well as projects with Microsoft, HP, NEC, Getty Images, and Sega. Rick was engaged by Intel as their Worldwide Project Management Team Leader in 2001, and collaborated with a team of 25 project managers dispersed globally. In that role Intel’s global teams delivered data center and internet application projects for The People’s Republic of China, Woolworth Australia, and Metro of Germany, and installed data centers for Intel in China. Rick’s posts on IT topics are widely read in outlets such as O’Reilly Media, LinkedIn, and DZone. He’s published four books on IT consulting, and regularly posts commentary on AI, data center builds, consulting behavior, and agile project management. Rick served as the Technology Editor for ‘Consulting to Management’ journal. Rick has been cited as one of the “most influential people in project management” and “a thought-leader in agile project management”. In addition to Rick’s consulting work, he teaches IT project management and consulting courses at the college level. Rick’s work is driven by the belief that technical expertise must be paired with strong consulting, communication, and strategic skills to deliver real business value. He strives to bring a strategic perspective on technology adoption and enablement, and a human-centered approach to enterprise evolution. Rick was educated in the rock and roll clubs of New York, where he participated in the downtown NYC art and punk rock music scene. Rick was a roadie for bands like The Clash, Blondie, Talking Heads, Television, The Ramones, Sid Vicious, and The Heartbreakers, and toured with the road crews of Elvis Costello, The Police, The Jam, and Ron Wood.
expert thumbnail

Stefan Wolpers

Agile Coach,
Berlin Product People GmbH

AI for Agile Coach, Scrum Trainer with Scrum.org. Author of the “Scrum Anti-Patterns Guide.”
expert thumbnail

Pavan Belagatti

Developer Evangelist,
Port.io

Pavan is an award winning developer evangelist. A GenAI, DevOps, Data Science and a Machine Learning enthusiast.
expert thumbnail

David Taiwo Balogun

Data and AI

I’m a Data Scientist and AI Researcher passionate about machine learning, natural language processing (NLP), and data analytics. I explore how AI can solve real-world problems, with interests in large language models (LLMs), retrieval-augmented generation (RAG), and responsible AI. I also enjoy sharing practical insights and making complex technical concepts easier to understand.

The Latest AI/ML Topics

article thumbnail
Where the Model Stops and the Code Starts: Lessons From an AI Procurement Agent
Two agent buyer and seller: price rules belong in code rather than prompts, and human approval only means something if the commitment itself is gated.
November 23, 2026
by TAPASH BISHOI
· 214 Views
article thumbnail
Getting Started With Weaviate: Building AI-Powered Search Applications With Java
Explore Weaviate vector search with enterprise Java using Eclipse JNoSQL, Docker, and LangChain4j for semantic retrieval and vector persistence.
November 23, 2026
by Otavio Santana DZone Core CORE
· 297 Views
article thumbnail
Treat AI Agents Like Long-Running Background Jobs: A Production Reference Architecture
Production AI agents behave like long-running background jobs: the model is the cheap part, and retries, idempotency, cost caps, and observability are the real work.
November 20, 2026
by Ido Fishman
· 674 Views
article thumbnail
Crash-Proof Agents: Durable Execution for Long-Running AI Systems
Learn how write-ahead logs, checkpoints, idempotency keys, and sagas make long-running AI agents resilient to crashes and failures.
November 20, 2026
by Khushan Adatiya
· 696 Views · 1 Like
article thumbnail
Observability With AI SREs: A 4-Step Implementation Guide
An AI SRE isn’t just a chatbot that answers questions. It’s an agent that can investigate, hypothesize, and even take remediating actions.
November 20, 2026
by Frank Swain
· 885 Views · 1 Like
article thumbnail
As AI Agents Multiply, Repository Access Could Become an Infrastructure Problem
Agents need fast code access. Shared, isolated workspaces can reduce duplicate clones and ease pressure on version control systems.
November 19, 2026
by Preetam Dwivedi
· 932 Views
article thumbnail
What 55 Runs Taught Me About Memory in AI Coding Agents
A controlled experiment examines how stored experience changes coding agents’ debugging paths, token usage, and investigation costs.
November 19, 2026
by Ojonugwa Martins Onogu
· 863 Views · 1 Like
article thumbnail
The Alert Is Not the Incident: LLM Triage on a Multi-Engine Data Platform
Incidents cross engine boundaries; alerts do not. Discover how bounded LLM context assembly accelerates incident triage while keeping remediation safely in human hands.
November 19, 2026
by Thirupathi Reddy Anneda
· 766 Views · 1 Like
article thumbnail
Choosing Voice AI Infrastructure: 7 Capabilities To Evaluate
Analyze seven voice AI infrastructure capabilities, from latency and call transfers to data controls, observability, integrations, and cost.
November 18, 2026
by Nick Puno
· 952 Views · 1 Like
article thumbnail
Securing AI Agents in Production: A Developer’s Guide To Prompt Injection, RAG Leaks, and Tool Abuse
Learn how to secure AI agents in production against prompt injection, RAG data leaks, and tool abuse with practical controls, access policies, and monitoring.
November 18, 2026
by Paresh Sagar
· 1,119 Views · 1 Like
article thumbnail
Engineering Responsible AI for High-Stakes Financial Applications
How data engineering, explainability, monitoring, and governance can work together to make financial AI systems more accountable.
November 18, 2026
by SUNILKUMAR REDDY Eraganeni
· 847 Views · 1 Like
article thumbnail
Process Intelligence Landscape 2026: Mining, Orchestration, and the Agentic AI Shift
The Process Intelligence Landscape 2026: mining, orchestration, and a decision gate, plus what agentic AI now demands from each.
November 18, 2026
by Kai Wähner DZone Core CORE
· 890 Views · 2 Likes
article thumbnail
Vapi vs Retell AI vs LiveKit: Architecture, Latency, Pricing, and Developer Experience
Compare Vapi, Retell AI, and LiveKit Agents across architecture, integrations, telephony, observability, pricing, and healthcare compliance.
November 17, 2026
by Akmal Chaudhri DZone Core CORE
· 1,290 Views · 2 Likes
article thumbnail
From Phone Menus to Workflows: The Quiet Engineering Behind Voice Agents That Act
Learn in this article how to build secure, reliable voice AI agents using API integrations, MCP, authorization, and validation.
November 17, 2026
by Igboanugo David Ugochukwu DZone Core CORE
· 1,131 Views · 1 Like
article thumbnail
When Jev Says It's Sure, Is It Right? A Fraud Case Study in Neo4j
Jev’s confidence exceeds its accuracy, and only its top range holds up, mostly on easy cases. Use confidence for triage and error rates for automation thresholds.
November 17, 2026
by Akmal Chaudhri DZone Core CORE
· 1,146 Views
article thumbnail
Measuring AI Impact at the Team Level
Learn how agile teams can measure AI's impact using evidence-based trials, workflow break-even tests, and delegation audits.
November 17, 2026
by Stefan Wolpers DZone Core CORE
· 1,213 Views · 1 Like
article thumbnail
Introducing TypeSafe Jev: Typed Judgments as Programming Primitives
Learn about TypeSafe Jev, a typed AI model that uses probabilities for structured decisions, with examples of code review comment analysis.
November 17, 2026
by Horatiu Dan DZone Core CORE
· 949 Views · 4 Likes
article thumbnail
Pitching Kotlin: An Engineering Leader's Guide to Legacy Modernization
Most Kotlin pitches stall on developer preference. This reviewer's framework prices the friction, phases the rollout behind gates, and wins approval.
November 17, 2026
by Yuri Geronimus
· 1,070 Views · 1 Like
article thumbnail
Using Middleware in LangChain: Recovering From Tool Failures
LangChain Middleware provides ways to recover from Tool Failures. This article helps in understanding how to use ToolRetryMiddleware and @wrap_tool_call to handle errors.
November 17, 2026
by Ruchi Saini
· 949 Views · 4 Likes
article thumbnail
The Rise of the Unsanctioned Agent Swarm
Learn how to detect and secure shadow AI agents using zero-trust API gateway interceptors, non-human identities, scope enforcement, and rate limiting.
November 17, 2026
by Nikita Kothari
· 1,057 Views
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • ...
  • Next
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×