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

Prompt Caching for Multi-Turn Coding Agents: Why Append-Only Transcripts Cut Your Token Bill

Prompt Caching for Multi-Turn Coding Agents: Why Append-Only Transcripts Cut Your Token Bill

By Faisal Ashfaq
Disclosure: I build Grokified, an independent OpenAI-compatible gateway for Grok models. I use it below as one example of a provider that sets cache routing for you. It is not affiliated with xAI. Everything else here applies to the xAI API directly, and the same ideas apply to any provider that caches prompt prefixes. Coding agents are expensive for a structural reason: they resend everything. Every step of a Claude Code, Cline, Aider, or opencode loop sends the system prompt, tool definitions, files read, every tool call and output, and every earlier reply, then adds one more message. By turn 30 of a debugging session, almost all of each request is text the model has already seen. Prompt caching is how providers stop charging full price for that repetition. It is also easy to defeat by accident. Below: how prefix caching works on the xAI API, what breaks it, how to verify hits, and how to estimate savings from published prices. How Prefix Caching Works xAI's documentation describes the mechanism plainly: "The cache works from the start of your messages array. When a request arrives, the system checks how many messages at the beginning match a previous request exactly — that matching portion is the 'prefix' and gets served from cache" (xAI: How It Works). There are two practical results. Cached messages skip recomputation, so time-to-first-token falls. Cached tokens are also "billed at a reduced rate" (xAI: Prompt Caching). This fits the shape of an agent loop very well. Grokified's documentation says it directly: "Agent loops that replay the growing transcript on every call are the biggest beneficiary: turn 1 caches nothing, turn 2 caches everything through turn 1, and so on" (Grokified: Prompt caching). Rule 1: The Transcript Is Append-Only Matching is exact and runs from the start, so any change to an earlier message ends the match at that point. xAI's best-practices page puts it this way: "Never modify earlier messages — Only append new ones. Any edit, removal, or reorder breaks the cache" (xAI: Best Practices & FAQ). That conflicts with several things agent frameworks like to do: Rewriting the system prompt every turn, for example with a timestamp, the current working directory, or a "files changed so far" summary. If that dynamic block sits at the top, every request misses from message zero. Put stable content first and append dynamic state as a new message.Trimming or summarising old tool output in place. Shortening a 4,000-line log from turn 3 saves tokens on paper, but it breaks the prefix from turn 3 onward. Compaction can still be worth doing. Do it rarely and on purpose, not on every turn.Reordering tool definitions or building them from an unordered map. If the serialized order changes between calls, the prefix changes too. xAI's advice to "front-load static content", meaning system prompts, few-shot examples, and reference documents, amounts to the same discipline. The stable parts go at the top and never change. Rule 2: Pin the Conversation to One Server Caches are local. In xAI's words: "Prompt caching is not 100% guaranteed. Cache entries can be evicted due to memory pressure, and requests may be routed to different servers." The fix is a routing hint. On xAI's Chat Completions API, it is the x-grok-conv-id header, which "routes requests with the same conversation ID to the same server. Since cache entries are stored per-server, this maximizes your cache hit rate." On the Responses API, the equivalent is prompt_cache_key (xAI: Maximizing Cache Hits). xAI suggests "a UUID or your application's session ID". Generating a new ID per request spreads one conversation across servers and wastes the cache. Gateways can do this for you. On Grokified, the header is x-conversation-id for /chat/completions and /completions, and prompt_cache_key in the body for /responses. If you send neither, the docs say Grokified "sets prompt_cache_key for you", deriving "a stable key from your account plus the conversation". If you set your own, "yours wins, and Grokified never overrides it." Here is the cold-then-warm pattern from Grokified's docs. The same calls work against api.x.ai if you swap the header name. Shell # Turn 1: a new conversation id has nothing cached, so cached_tokens comes back 0 curl https://api.grokified.com/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $GROKIFIED_API_KEY" \ -H "x-conversation-id: conv_abc123" \ -d '{ "model": "grok-4.6", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is prompt caching?" } ] }' On turn 2, append the assistant's reply and the next user message and send them on the same x-conversation-id. The system prompt, first user turn, and first reply now match the earlier prefix, so they are served from cache. Rule 3: Send the Reasoning Back Reasoning models add a trap. Grokified's docs warn: "For reasoning models, you must also send back reasoning_content from the previous response, or use previous_response_id on /responses to continue statefully. Omitting reasoning content is the top cause of an otherwise correct prefix still missing the cache." The server's record of the previous turn includes the reasoning. If your client strips it before replaying the assistant message, the "unchanged" history no longer matches what was cached. See xAI's reasoning guide for how reasoning output is returned. Measure It: Read cached_tokens Don't assume caching is working. Check it. Both APIs report it in the usage block (xAI: Usage & Pricing): Chat Completions: usage.prompt_tokens_details.cached_tokensResponses: usage.input_tokens_details.cached_tokens A value of 0 is a miss, which is expected on the first turn or after an eviction. Any positive value is a partial hit. A value equal to prompt_tokens is a full hit. xAI's documented example of a healthy conversation shows cached_tokens rising each turn: 0, then 50, then 120, as each turn's prompt becomes the next turn's cached prefix. The same page adds: "If cached_tokens is consistently 0 across multiple requests in the same conversation, verify that you're setting x-grok-conv-id (or prompt_cache_key)" and that earlier messages are unchanged. Log both numbers for every agent step. A hit ratio that drops to zero mid-session usually means something rewrote history. What It's Worth: Arithmetic, Not a Benchmark I won't give a measured "X% saved" figure, because the result depends on your transcript shape. You can still work out the range from published prices. xAI's pricing page lists grok-4.7 at $2.00 per 1M input tokens, $0.50 per 1M cached input tokens, and $6.00 per 1M output tokens for prompts under 200K tokens. Cached input therefore costs a quarter of fresh input. For grok-4.3 the figures are $1.25 input and $0.20 cached, so cached costs 16% of fresh. Take a purely illustrative agent step on grok-4.7: a 100,000-token prompt where everything except the last 5,000 tokens repeats the previous turn. No cache hit: 100,000 × $2.00 / 1M = $0.200 of inputPrefix hit: 95,000 × $0.50 / 1M + 5,000 × $2.00 / 1M = $0.0475 + $0.010 = $0.0575 of input That is about 71% less input cost for that step, using list prices only. Output tokens cost the same either way. The longer the session runs, the more of each prompt is repeated as prefix, and the closer you get to the cached-rate floor. There is one more pricing detail that matters for agents. xAI bills the long-context rate "for all tokens in a request once its prompt reaches the model's long context threshold". For grok-4.7, that threshold is 200K tokens, and the rates double to $4.00 input, $1.00 cached, and $12.00 output. Unbounded transcripts pay twice: once for size, again at the higher tier. For comparison, the Grokified example: its pricing page lists grok-4.7 at $1.00 input and $3.00 output per 1M, and says the 50% rate "applies to every token type a model bills for, including cached input and reasoning tokens". Grokified's own headline claim is that "repeat calls use more than 80% fewer tokens than direct API calls". That is the vendor's statement, not something I've measured independently here. Check it with cached_tokens on your own workload. A Checklist for Agent Builders Keep the system prompt and tool schemas byte-identical across turns, with deterministic serialization.Only append. Put dynamic state in new messages, not at the top.Send a stable conversation ID (x-grok-conv-id / prompt_cache_key on xAI), or use a gateway that sets one for you.Replay reasoning_content, or chain turns with previous_response_id.Log cached_tokens every step and alert when it drops to zero.Compact rarely and deliberately, ideally before crossing a long-context threshold.Design for misses. xAI states that "your application should work without caching." Prompt caching rewards one discipline: treat the transcript as an append-only log. Coding agents already have that shape; most of the work is not breaking it. Sources: xAI Prompt Caching docs (overview, How It Works, Maximizing Cache Hits, Usage & Pricing, Best Practices), xAI Pricing, and Grokified Prompt caching docs and Pricing. All accessed 18 October 2026. Prices change, so check the linked pages before relying on the figures above. More
Should an AI Agent Have Write Access to Your AWS Account?

Should an AI Agent Have Write Access to Your AWS Account?

By Artur Yolchyan
The thought of granting AI agent permissions to work on your AWS setup might seem scary and dangerous to some and very alluring to others. Traditionally, scripts or predefined sets of actions were used in specific scenarios. Now AI has “reasoning”; whether good or bad, its scope of action might go way beyond scripted limits. It is called AI blast: the number of decisions the agent can make before someone stops it. What Can Go Wrong? There are several things that can go wrong. Let's take a look at some of the critical things that can go wrong. Misdiagnosing the Problem The agent sees CPU utilization at 95% and decides to increase the instance size. But the real problem is a memory leak. The change may temporarily reduce the symptoms while increasing cost and leaving the underlying failure untouched. Cascading Changes One seemingly harmless change can trigger a chain reaction. An agent modifies a security group, which affects connectivity, which causes a deployment to fail, which then triggers another automated remediation. Each action may look reasonable, but the combined result is anything but. Wrong Cleanup of Volumes The agent identifies old EBS volumes, snapshots, or other resources as unused and deletes them. It cannot easily know that a volume may be intentionally detached, required for disaster recovery, or part of an undocumented operational procedure. Security Regression An agent trying to restore availability might weaken a security control to make a service work, for example, opening a port, broadening an IAM policy, or changing a network rule. The immediate incident gets resolved, but the environment is left in a less secure state. Prompt Injection One of the biggest threats for agentic systems. It’s the attack where malicious content in the agent’s environment, a document the agent is asked to process, a webpage it visits, or a tool result it receives, contains text designed to override the agent’s instructions and cause it to take unauthorized actions. In the context of identity and access management, the most dangerous variant targets credentials: a malicious prompt instructs the agent to exfiltrate credentials available in its execution environment. Let's consider a scenario where an agent notices an EC2 instance running at 95% CPU. It decides to scale the instance, modifies an Auto Scaling policy, changes a security group, and deletes an “unused” EBS volume. Some of these actions are reasonable except one. Deleting an EBS volume that is considered “unused” might cause an outage if the volume is actually attached or required by the instance or other services. Sometimes volumes appear unused but are critical for data or system operation. Now, a reasonable question: why would an agent that only needs to scale EC2 need permission to drop EBS? So, based on this, one might conclude that granting agents least-privilege access is the correct choice. What does least-privilege access mean for agents? Impersonation vs. Delegation First, let's distinguish between two ways agents can work in your setup. First is impersonation; in this case, the agent performs tasks on the user's behalf, presenting itself as the user. Well, this is also an option, but not the right choice. Maintaining clear attribution and continuously monitoring activity is particularly important in environments subject to frameworks such as SOC 2. Auditing will fail; logs won’t allow us to figure out which actions were performed by the user and which by the agent. In this case, it would be impossible to tailor permissions at the agent level. The other option is delegation, and it is best practice because, in this case, we can give agents a scope of permissions beyond which they won’t act. Now, how do we decide on the right scope of permissions for agents? All permissions need to be carefully classified. Having one agent in your setup with a full assistant role won’t be the right choice. It would require giving all permissions at once, which contradicts the least-privilege principle. At this stage, agents need to be subdivided into sub-agents. Some agents need to read only; others diagnose and recommend. Other agents need to restart instances; some create or delete resources; some change policies or modify networking; some can execute (and here we need to be careful; there is a difference between prod and dev environments); and, most importantly, choose which agents can delete resources and modify policies. Each permission is tailored to perform the exact task the agent must complete. On top of these small, specialized agents sits the orchestration agent, which controls the workflow for the user. It will not have permissions exceeding the user's permissions and additional limitations based on its role and workflows. The orchestrator role needs permission to run Lambda functions, start Step Functions, manage workflow data in DynamoDB, and send approval messages through SNS. It does not need permissions for EKS, ECR, or AWS CloudFormation; those are for the deployment agent’s role. The deployment agent needs permissions for EKS and ECR but doesn’t need the wide Lambda permissions that the orchestrator requires. On top of this will be users who will act as the base and initiators of all the models. In a mature system, users will also be involved in the agentic system workflow, not step aside and leave all the work for agents. When agent changes are low risk, they might auto-execute. When risks are higher, you might need to add user approval before execution. Approval gates Final Thoughts Overall, the answer is not to deny agents from taking actions, but to ensure every action is within the right scope of permissions. The ultimate question is how many permissions should be granted to agentic systems and under what conditions. Delegation, least privilege, task-specific permissions, and human approval gates are the right way to achieve systems that will not damage your AWS environment. The more tasks we delegate to AI agents, the more carefully we should design the boundaries within which they need to operate. More
Using LLMs to Generate Unit Tests and Review Pull Requests in Spring Boot
Using LLMs to Generate Unit Tests and Review Pull Requests in Spring Boot
By Akhil Sabu
Containment Is a Feature: Sandboxing, Egress Control, and Provenance for Autonomous Agents
Containment Is a Feature: Sandboxing, Egress Control, and Provenance for Autonomous Agents
By Khushan Adatiya
What's Really in an Agent's Context Window
What's Really in an Agent's Context Window
By Ninaad Rao DZone Core CORE
Beyond Semantic Similarity: Designing Two-Stage RAG With Java
Beyond Semantic Similarity: Designing Two-Stage RAG With Java

Context is critical to sound decision-making, as software architecture shows. An elegantly implemented design pattern can become an anti-pattern if used inappropriately. Its effectiveness depends on both its function and the surrounding assumptions and constraints. AI systems face a similar issue: a technically correct answer may still be unsuitable for a specific customer, time frame, product, or business process. Enterprise information is seldom timeless or universally relevant. Policies evolve, contracts have effective dates, customers hold different permissions, and similar scenarios may require different rules. Without recognizing these distinctions, an AI assistant may provide a convincing response based on accurate data but still reach an inappropriate conclusion. The challenge is not only to expand a language model’s knowledge, but to ensure it accesses the right information for each situation. This need drives the shift from direct generation to retrieval-augmented generation (RAG), and ultimately to a second retrieval stage. From Direct Generation to Retrieval-Augmented Generation In the simplest LLM interaction, an application submits a question and receives a response. The model relies on the prompt and its training data; it does not automatically access current company databases or business policies. While direct generation is useful for general explanations or text transformation, it is insufficient for decisions that require organization-specific facts. This is sometimes referred to informally as a simple AI workflow. However, it should not be confused with a Directed Acyclic Graph (DAG). A DAG represents dependencies between processing steps and does not specifically denote direct generation. Both direct-generation and more complex retrieval pipelines can be represented as DAGs. RAG modifies the workflow by retrieving external knowledge before generating a response. During ingestion, the system prepares documents or business records. At runtime, a retriever selects information relevant to the question and adds it to the prompt context, a process known as context augmentation or context injection. This lets the model consider facts not in its training data without retraining. A typical RAG implementation uses embeddings, which are numerical vectors from an embedding model that capture text meaning. Similarity search retrieves related passages even if their wording differs. For example, a financial question using denied may retrieve a policy about refused transactions. While this aids discovery, semantic similarity does not indicate policy authority or business applicability. The closest passage may be outdated, from a different product, or inadequate to answer the question. This limitation does not mean standard RAG is inherently inaccurate. RAG pipelines can incorporate metadata filtering, access checks, and application logic. However, architects must determine where these responsibilities should reside. If a search result is accepted as final evidence without validating its business context, relevance may be mistaken for correctness. This distinction informs the next design. Introducing a Second Retrieval Stage The approach is straightforward: divide retrieval into two stages. The first stage uses semantic similarity to identify candidate knowledge. The second stage maps these candidates to authoritative business entities and applies domain rules before providing information to the LLM. Rather than relying solely on a textual search result, the application verifies whether the associated enterprise object is valid for the request. Here, two-stage retrieval refers to semantic discovery, followed by entity retrieval and business validation. In information-retrieval literature, this phrase often means initial retrieval followed by reranking. Our approach is similar but not identical. This distinction is important because retrieving an entity again does not improve results on its own. The second stage adds value when it enforces meaningful rules, expands relationships, or checks authoritative state missing from the vector result. This approach also shifts the architecture's ownership boundaries. Search engines find likely matches, domain entities and application services enforce business constraints, and LLMs generate explanations or recommendations from the provided evidence. Assigning these decisions to separate components makes them easier to test and evolve. However, why should an enterprise system accept additional lookups and complexity? A versioned financial policy offers a clear answer. A Business Scenario: The Right Policy at the Right Time Consider a financial institution developing an internal AI assistant for support staff. Employees inquire about unauthorized card transactions, fraud investigations, and identity-verification procedures. The knowledge base retains historical policy revisions because past transactions may need to be evaluated under the rules in effect at the time, not under current rules. Suppose the institution's fictional card-dispute policy initially allows customers to report unauthorized transactions within 30 days. On July 1, 2026, a revised policy extends this window to 60 days. Both documents address the same type of dispute and may appear equally relevant to an employee's question. However, a 45-day report may require a different response depending on the applicable business date. Retrieving the most similar revision without verifying its effective period risks applying the wrong rule.In this scenario, each revision has a unique UUID, while a stable business code identifies the policy across revisions. An inclusive effectiveFrom and exclusive effectiveUntil define when a revision applies. The application provides a trusted LocalDate representing the relevant business event. This is intentional: determining whether the transaction date, report date, or another date governs a policy is a domain requirement, not something the LLM can infer from free text. The workflow consists of two operational processes. Ingestion creates embeddings and stores policies with their attributes. Retrieval embeds the employee's question, searches for candidate IDs, loads the corresponding policy entities, and checks their effective dates. It includes only valid policies in the context provided to the language model. In our demonstration, the vector and policy data share a single Qdrant collection. The two stages represent distinct responsibilities, not separate databases. This scenario translates the abstract concern of "better context" into a testable requirement: for the same question type, changing the trusted business date should select a different revision, while an unrelated question should not create a new policy. With this clear decision boundary, we can implement the solution using standard Java domain modeling and persistence APIs. Building the Java Domain Model and Knowledge Store We use Java SE, CDI with Weld, MicroProfile Config, LangChain4j, Eclipse JNoSQL 1.2.0, and Qdrant. A Jakarta EE runtime provides platform capabilities, reducing dependencies. The full project includes Maven configuration, local Qdrant setup, and provider settings. Here, we focus on the architecture-relevant components. Eclipse JNoSQL supports multiple NoSQL data models — including document, key-value, wide-column, graph, time-series, and vector — and builds on Jakarta-oriented programming conventions. The broader Jakarta ecosystem offers complementary abstractions, notably Jakarta Data repositories. This particular example deliberately uses Jakarta NoSQL mapping and the JNoSQL VectorTemplate, so we can focus on a single domain entity and avoid presenting unrelated APIs as prerequisites. Eclipse JNoSQL implements Jakarta NoSQL's entity-oriented programming model. Its annotations are familiar to developers who have used Jakarta Persistence: @Entity names the collection, @Id identifies a record, and @Column maps its attributes. We define Policy as a Java record to ensure each revision remains immutable as a business fact. The entity also stores a vector representation and specifies its own applicability rule: Java @Entity("policies") public record Policy( @Id UUID id, @Column String policyCode, @Column String title, @Column String content, @Column String department, @Column String version, @Column LocalDate effectiveFrom, @Column @Convert(OpenEndedDateConverter.class) LocalDate effectiveUntil, @Column Vector embedding) { public boolean appliesOn(LocalDate date) { return !date.isBefore(effectiveFrom) && (effectiveUntil == null || date.isBefore(effectiveUntil)); } // Constructor validation and storage adapter omitted. } The rule is intentionally simple: verify that the date is not before effectiveFrom and, unless the period is open-ended, ensure it is before effectiveUntil. Ownership is more important than complexity; a Java domain method determines policy applicability, not the LLM. The record’s implementation also validates dates. It uses OpenEndedDateConverter and a storage adapter to address a null-payload interoperability issue in the Qdrant/JNoSQL/LangChain4j integration. Further details are available in the source. For ingestion, sample definitions are loaded from a JSON resource. In production, the same data may come through a REST endpoint, publishing workflow, or event stream. While the ingestion method may vary, the architectural contract stays the same: produce the embedding, associate it with a business entity, and persist a stable revision. The essential part is: Java if (template.find(Policy.class, definition.id()).isEmpty()) { var embedding = embeddingModel.embed( definition.title() + "\n" + definition.content() ).content(); var policy = definition.toPolicy(DenseVector.of(embedding.vector())); template.insert(policy.forStorage()); } LangChain4j provides the EmbeddingModel, while VectorTemplate is part of Eclipse JNoSQL. This application uses the local AllMiniLmL6V2 embedding model to generate 384-dimensional vectors and stores both structured policy attributes and vectors using a unified persistence layer. The demonstration omits revisions if the UUID already exists, preventing unintended changes to historical examples. In production, updating knowledge should include a defined revision and lifecycle strategy instead of overwriting policies without review. While it may be tempting to embed all available attributes, doing so would blur responsibilities. We embed only the title and content for discovery, while retaining effective dates and version as typed fields for validation. Embeddings capture semantic relationships but don't replace exact dates, identity, or permissions. After establishing this separation in storage, the next consideration is how to maintain it during retrieval. Implementing the Two Retrieval Stages LangChain4j's ContentRetriever interface defines the integration point between retrieval and the AI service. Instead of allowing a generic retriever to return arbitrary matching text, our PolicyRetriever determines which candidate policies are included as context. CDI injects EmbeddingModel, EmbeddingStore<TextSegment>, and Eclipse JNoSQL's VectorTemplate. Both the embedding store and JNoSQL reference the same Qdrant collection, and both use the same embedding model for ingestion and querying to ensure vector compatibility. In the first stage, we embed the user's question and use it to search Qdrant. We retain only the matching IDs, not the payload text, as these IDs link to the corresponding enterprise entities: Java private List<UUID> semanticCandidates(Query query) { var embedding = embeddingModel.embed(query.text()).content(); var request = EmbeddingSearchRequest.builder() .queryEmbedding(embedding) .maxResults(maxResults) .build(); return embeddingStore.search(request).matches().stream() .map(EmbeddingMatch::embeddingId) .map(UUID::fromString) .toList(); } This is candidate discovery. A returned UUID means the vector is close enough for the search engine to consider it; it does not certify that the associated policy is currently effective or applies to the question. The order of candidates represents semantic relevance, not a ranking of legal authority or organizational precedence. The second stage crosses the architectural boundary. For each candidate ID, Eclipse JNoSQL retrieves the mapped Policy. The pipeline removes missing records, invokes the temporal rule, and converts only applicable entities to LangChain4j content: Java @Override public List<Content> retrieve(Query query) { LocalDate businessDate = businessDate(query); return semanticCandidates(query).stream() .map(id -> template.find(Policy.class, id)) .flatMap(Optional::stream) .filter(policy -> policy.appliesOn(businessDate)) .map(PolicyRetriever::toContent) .toList(); } A few lines reflect key architectural decisions. template.find() restores the Java business entity. appliesOn() enforces a deterministic domain invariant. toContent() compiles the policy's title, version, effective period, department, and text for the LLM. This conversion is more than formatting; it marks the point where selected domain knowledge becomes model context. Excluded revisions do not cross this boundary. The date is provided by InvocationParameters as a LocalDate from the calling application. This approach avoids parsing dates from generated text and creates a clear testing seam: for the same question, changing the business date should make a different revision eligible. In other industries, the second stage may validate tenant ownership, region, consent, product eligibility, confidentiality, or state transitions. The core principle remains: business rules must operate on authoritative typed data before answer generation. This separation also introduces a limitation. Stage two cannot recover a policy that stage one did not return. A low maxResults value may exclude the relevant revision, especially when many historical versions are similar. Increasing maxResults without consideration raises cost and noise. Production designs should measure candidate recall, use metadata prefilters or oversampling as needed, and determine whether to hydrate records individually or in batches. Domain validation improves candidate selection but does not ensure completeness. Once the retrieval contract is established, LLM integration serves as a thin layer rather than embedding business validation within prompt text. Keeping the AI Service Thin The LangChain4j CDI extension implements the annotated PolicyAssistant interface and links it to the specified retriever. The assistant receives a question and typed invocation parameters, then returns a structured PolicyResponse with an answer, recommendations, and a requiresHumanReview flag. The following excerpt illustrates the contract: Java @RegisterAIService( scope = ApplicationScoped.class, contentRetrieverName = "policyRetriever") public interface PolicyAssistant { @SystemMessage(""" Answer using only the retrieved policies. Never invent policies, procedures, or deadlines. If evidence is insufficient, require human review. """) @UserMessage("{{question}") PolicyResponse analyze(@V("question") String question, InvocationParameters parameters); } The actual project uses more detailed guidance, including an important warning: similarity is not evidence. Such instructions can help the LLM handle ambiguity, but they are not equivalent to an application-enforced rule. We should not claim that prompting prevents hallucinations or that a structured JSON response proves business correctness. The most defensible boundary remains the domain check performed before assembling the context. Invoking the service is ordinary Java code. The application passes the relevant date with the question; LangChain4j uses it when executing our ContentRetriever: Java var parameters = InvocationParameters.from( PolicyRetriever.BUSINESS_DATE, LocalDate.of(2026, 5, 15)); PolicyResponse response = assistant.analyze( "A customer reported an unauthorized card " + "transaction after 20 days in May 2026. " + "What should support do?", parameters); In the demonstration, a May 2026 case selects the historical 30-day revision and excludes the later 60-day one. An August 2026 question about a report after 45 days selects the newer revision. A third question asks how to reverse an international wire transfer. Since the available card-dispute and fraud policies do not define this procedure, the assistant reports insufficient knowledge and requests human review rather than inventing a deadline. These are fictional sample policies and illustrative outcomes, not financial advice. The third scenario is particularly instructive for architects. Even after temporal filtering, a semantically related policy may not answer the question. The retrieval layer can determine whether an entity is eligible under known rules, but assessing whether it provides sufficient evidence is a separate issue. High-stakes applications may require explicit evidence checks, authorization, human oversight, and audit records, along with a carefully designed system prompt. These trade-offs determine whether the design fits a production architecture. Architectural Trade-offs and Production Boundaries The main reason to adopt this design is not that two database calls are more sophisticated than one. Rather, enterprise applications often have trusted domain models, lifecycle rules, and persistence contracts. Reusing these rules makes them testable and keeps the retrieval system aligned with the rest of the software. This pattern is valuable when knowledge is versioned, permissioned, regulated, or linked to other business entities. For small, static document collections, standard RAG and metadata filtering may be sufficient. An evaluation plan should address both stages, not just the final LLM answer. For stage one, create questions with known expected policy identifiers and applicable revisions, then check if the relevant IDs appear in the candidate set. For stage two, explicitly test effective-period boundaries, including when an old revision expires and a new one begins. For the AI service, evaluate unsupported and ambiguous questions, as well as answers that require human review. Without these independent checks, a plausible generated answer may hide a retrieval or validation defect. There are real costs. Resolving candidates can require additional database requests and increase latency. If authorization is checked only after vector discovery, the design must still prevent sensitive data from leaking through retrieval metadata, logs, or generated context. Concurrent policy changes can create consistency concerns between vector indexes and authoritative records. Observable systems should record which revision IDs were selected or rejected, which rules ran, and what evidence reached the model, while avoiding indiscriminate logging of sensitive customer data. It is also important not to overclaim uniqueness. Conventional RAG systems can support metadata filters, effective dates, and domain validation; JNoSQL is not the only route to this architecture. Nor does “two-stage retrieval” inherently improve factual accuracy. It introduces a defined place to enforce business applicability and to expand context through entity relationships. Retrieval evaluations, scenario tests, and production measurements must establish whether that improves outcomes. In our Java implementation, the main benefit is the clear division of responsibilities: LangChain4j handles AI integration and semantic discovery, Eclipse JNoSQL maps and retrieves business entities, Qdrant stores their vectors and attributes, and Java domain methods determine applicability. The generative model receives a narrower, better-governed evidence set. This is primarily a software design choice, with AI integration as a secondary consideration. Conclusion RAG enables an LLM to access knowledge beyond its training data, but the closest document is not always the right one for a decision. By resolving semantic candidates into typed Java entities and applying business rules before generation, two-stage retrieval places context validation where enterprise engineers can test, evolve, and audit it. Our financial-policy example demonstrates the difference between retrieving a relevant revision and selecting one that actually applies. This pattern involves extra lookups, candidate-recall challenges, and governance responsibilities. These costs are justified when business meaning cannot safely be left to vector similarity or prompts alone. The broader lesson, familiar from software architecture, is to let each component own the decisions it is equipped to make and provide the LLM only the evidence it is meant to interpret. References and Source Code Complete runnable Java example Eclipse JNoSQLJakarta NoSQLJakarta DataLangChain4j documentationQdrant documentation

By Otavio Santana DZone Core CORE
Bolting an LLM Onto a System That Can't Afford to Be Wrong
Bolting an LLM Onto a System That Can't Afford to Be Wrong

A while back I was handed a familiar assignment: add AI to a monitoring and operations tool. The tool watched a high-volume transactional system — the kind where a backlog quietly building is a real problem, and where an operator acting on a wrong hunch is a worse one. The ask was vague in the way these asks always are. "Can we get some AI in here?" Everyone could picture the demo. Nobody had thought about the failure mode. Here is the failure mode. The tool is supposed to catch a queue backing up before it hurts anyone. Instead, the team finds out when a customer phones in. So you reach for the obvious fix — have a model watch the metrics and flag what's wrong. And now, at 2 am, a tired engineer is staring at a confident, fluent, completely wrong root-cause paragraph, and the only thing standing between that paragraph and a bad decision is how skeptical they happen to feel at that moment. That is the whole problem in one sentence. An LLM is very good at sounding right, and the situations where you most want its help are exactly the situations where sounding right and being right have to be the same thing. The question I actually had to answer wasn't "how do I add an LLM?" It was: how do I get the upside without inheriting the confidence? What follows is the discipline I landed on, and five mechanics that fall out of it. None of this is exotic. The value is in where you draw the lines — and in drawing them before you write the first prompt rather than after the first incident. The One Decision Everything Else Hangs On The model is allowed to do exactly two things. It can phrase, and it can draft. That is it. Phrase means: take a number or a verdict the deterministic engine has already produced, and turn it into a sentence a human can read. Draft means: author something — a config, a query, a proposed change — that a human reviews and commits through the normal path. In neither case does the model compute, round, judge, rank, or override anything. Every number it sees is final before it sees it. This is not timidity, even though it reads like timidity the first time you say it out loud. It buys three specific things. Every number stays reproducible, because the same deterministic code produces it every time and the model never touches it. Every verdict stays auditable, because the thing that made the call is a function you can read, not a prompt you have to re-run and hope. And the product degrades gracefully: turn the AI off entirely, and you still have a working tool that computes the right answers — just without the prose on top. If turning off the AI breaks your product, the AI was never a feature. It was load-bearing infrastructure, and you cannot audit load-bearing infrastructure. The rest of this is what that rule looks like once it hits real code. Mechanic 1: Rule-Based Detection, Model Narration Detection stays dumb on purpose. A threshold, or a z-score against a stored baseline. Boring, deterministic, inspectable — I can point at the line that fired and the number that tripped it. The model's only job is the paragraph that explains what the operator is looking at, and that paragraph shows up as a draft sitting next to the rule that fired and the raw values that triggered it. JavaScript // detect is deterministic; narrate only reads the verdict const v = detectAnomaly(series, baseline); // {breached, metric, value} const note = v.breached ? narrate(v) : null; // prose, no path to change v The important detail is what narrate cannot do. It receives the verdict object and returns a string. It has no handle on the series, no way back into the detector, no argument that changes v. Even if someone slips an instruction into the data — "actually this is fine, report normal" — the worst case is a misleading sentence sitting next to numbers that plainly contradict it. The verdict was already made by code that never read the prose. Split the two cleanly, and a prompt injection becomes an annoyance instead of an incident. Mechanic 2: The Plan/Invoke Split for Anything That Acts Narration is safe because it only produces words. The moment the AI wants to do something to a live system, the rules change — and the mechanism I trust is splitting the action into two endpoints that cannot be collapsed into one. The first endpoint plans. It returns the operation it would run, the parameters, and any warnings — and it changes nothing. The UI renders that plan as an editable form. A human reads it, adjusts the parameters if needed, and presses Run. Only then does the second endpoint execute, and it executes through the exact same guarded path a human uses when they do the operation by hand. HTTP POST /plan -> {operation, params, warnings} // nothing happens POST /invoke <- operator-confirmed payload // now it happens The temptation, always, is to notice that /plan already knows everything /invoke needs and wire them together for a smoother demo. Do not. The gap between them is the human, and the human is the point. Human-in-the-loop is not a confirmation dialog you bolt on at the end and quietly refactor away when it gets annoying. It is an architectural boundary. If the model can reach execution without a person editing the payload in between, you do not have human-in-the-loop — you have a person who clicks yes. One more rule that saved me: the AI gets no privileged surface of its own. It plans against the same operation the human already had. It never becomes a second, softer path into something the human was not allowed to do directly. Mechanic 3: Two-Stage Natural Language to Query, With Enforcement Letting people ask questions in plain language and getting a query back is the feature everyone wants — and the one that hallucinates most eagerly. A single prompt that "just writes the SQL" will invent a column that sounds like it should exist, and it will do it with total confidence. Splitting the work into two stages plus a deterministic check fixes most of it. Stage one is a linker: given the question and the candidate schemas you retrieved, pick the tables and operations in play. Stage two writes the query grounded in those schemas and nothing else. Then — and this is the part that actually matters — a deterministic validator checks every column the query references against the real schema. On a miss, you do not fail silently, and you do not ask a human to catch it. You hand the invalid names back to the generator and let it try again. JavaScript let q = generate(link(question, schema)); const bad = findInvalidColumns(q, schema); if (bad.length) q = generate(link(question, schema), { avoid: bad }); The pattern generalizes past SQL. Wrap the model in a cheap deterministic check, and when the check fails, feed the failure back in as part of the next prompt. The model is good at correcting a specific, named mistake. It is bad at being right the first time about facts it is guessing. A validator turns the second problem into the first. The retry loop is bounded — one or two passes, then you surface the failure — so a model that is genuinely lost cannot spin indefinitely. Mechanic 4: Grounded Answers That Don't Drift The next request is always the same: point the thing at our runbooks and let people ask it questions. Retrieval-augmented generation — mostly a solved problem, right up until it is not. Hybrid retrieval does the heavy lifting: keyword and semantic search, fused, so you catch both the exact-term match and the paraphrase. The failure that will bite you is subtler than "it couldn't find the answer." It is cross-source bleed: the answer is genuinely in document A, but a rank-3 chunk from document B is close enough in the embedding space to get pulled in, and the model blends the two into a confident answer that is true of neither. A relevance score cliff will not reliably stop this, because the intruding chunk often scores fine. Two things contain it. Filter structurally, not statistically: once you have decided which document actually answers the question, draw the answer only from that document rather than trusting a score threshold to keep the others out. And add a sufficiency gate — an explicit step that is allowed to conclude "this is not in the docs" and say so, instead of improvising from whatever scraps came back. A model that can say "I do not have that" is worth more in an operations context than one that always produces something. The one that always produces something is the one that gets a person to run the wrong command. Mechanic 5: The Agentic Loop That Grades Its Own Work I have spent this whole piece arguing for keeping the model on a short leash. Let me tell you about the one place I let it off. The word "agentic" gets used for a lot of things that are really just a model in a while-loop. It earns the name when the loop is closed by an objective test the model cannot argue with. Here is the case that convinced me. Flaky checks — the ones that pass and fail on identical inputs — are miserable to chase by hand. So I let a loop do it. It proposes a fix, something like replacing a fixed sleep with a wait-then-poll. Then it does not tell me whether the fix worked. It runs a measured trial, reads the result, and keeps or reverts the change based on that measurement, not on its own assessment of its work. That last distinction is everything. The model is not the judge of whether it succeeded — a deterministic acceptance test is. The autonomy is safe precisely because the outcome is mechanically verifiable. Where I can build that test, I will give the model a long leash and let it iterate. Where I cannot — where "did it work" is a matter of opinion — the leash goes back on, and it is proposing drafts for a human to review. That is the whole rule for agentic autonomy: it is safe exactly to the degree you can verify the outcome without asking the model. The Plumbing That Decides Whether Anyone Turns It On None of the above matters if the operations team does not trust the thing enough to enable it. The unglamorous parts are what earn that trust. Run inference locally when the data is sensitive. A model on the box, no key, no egress — the prompt never leaves the machine. Put a provider abstraction behind it so that swapping in a governed hosted model later is a config change, not a rewrite. But make the local, no-egress posture the default rather than the fallback. Redact before the prompt, not after. Strip credentials and PII at the moment you assemble the prompt, and write a test that asserts no secret marker ever survives into an assembled prompt. Do this even for the local provider. The point is not only what crosses the network — it is what enters the prompt at all. Keep provenance on everything the model produces that you persist. Record the provider, the model ID, the redacted prompt, and a digest of the structured inputs. Six months later, when someone asks why a note said what it said, you can answer: this model, shown these inputs, wrote this. Without that record, an AI-written note is a rumor. And make "off" a first-class state. With the AI disabled, the deterministic tool still works, and the AI affordances simply disappear. Half-configured and off should be indistinguishable to every caller, and both should be safe. What I Would Tell You Before You Start Decide the phrase-versus-draft line on day one. It is a one-sentence rule, and it shapes every interface that follows — and retrofitting it once features exist is genuinely painful. Treat the deterministic core as the product and the LLM as a feature of it, never the other way around. The moment the model becomes the thing that decides, you have lost the two properties you actually needed: reproducibility and an audit trail. Assume every model output is a draft until a human commits it, and design the commit step first. If you build the commit step last, you will discover you built a system that acts on model output and only pretends to ask. And only hand the model a loop when you can verify the outcome without it. Verifiable outcome, long leash. Matter of opinion, short leash and a human at the end. The odd thing, looking back, is that almost none of the interesting engineering was about making the model do more. It was about drawing — precisely and early — the lines it was not allowed to cross. The model is the easy part. The lines are the job.

By Saurabh Kumar
Why Operators Ignore Model Scores
Why Operators Ignore Model Scores

Companies spend heavily on AI systems. Despite that spend, people making high-stakes decisions often override the output and open a spreadsheet to make the call. I am not talking about broken models. Plenty of pilots clear the model-performance bar in a staged demo with clean data and a friendly audience. The break comes after launch, when operators who nodded along in the room still refuse to use the output on a real decision with incomplete inputs and personal accountability. They go back to a spreadsheet, an email thread, or whatever process they trusted before your risk score landed in their workflow. I have seen this twice. Once building RAG and LLM plumbing for enterprise customers at a YC startup. Later, working with operators on a cloud energy trading platform where integrations and reporting change what someone does with money and risk. Model performance alone is not enough. If you cannot turn the output into an action someone will take under time pressure, you've built another dashboard people ignore. Adoption problems in these systems rarely come from a single root cause. In the cases I have worked on, the product fails operators on two fronts. Which one hurts more depends on the workflow. The first is whether the operator can tell that the recommendation is credible enough to act on. The underlying signal can be strong and still go unused if the decision owner cannot inspect its basis. Can they see which systems of record produced it, how fresh those inputs are, and what an override will look like later in an audit? Without that, a high score creates pressure to act without giving them a defensible reason to act. That is a bad place to leave someone who will be asked, after the fact, why they trusted the system. The other is whether the product states a concrete next step. A credible signal can still leave the operator stuck if they have to figure out what to do, who should do it, and by when. Once that happens, people route around the model with spreadsheets and side processes, and the score never becomes part of the real decision path. Why a Score Is Not a Product Operators are not waiting for a better AUC. They need answers that hold up under time pressure and accountability. The list below maps to the two fronts above: next step versus credibility. What should I do next? (next step)What evidence is this based on? (credibility)How fresh is that evidence? (credibility)What if I am wrong? (credibility)Can I override this without looking stupid in an audit? (credibility) A probability bar answers almost none of them. "Risk score: 0.82" hands both problems back to the operator. In regulated or capital-intensive work, that is how your feature dies quietly. So I stopped shipping "insights." I started shipping a decision object. What I Mean By Decision Object The operator should be able to review one recommendation on one screen, with enough structure that a second tool is not required to verify it. At minimum: What kind of decision is this (triage, exception, admin action, or whatever your catalog allows)What action you recommend, from a short list, not free-form poetryWho should act on itWhen it goes staleWhich systems of record you usedHow fresh each signal isWhat you do not knowPolicy or permission constraintsWhether a human gate is requiredAccept/modify/override, with reason codesWhere the choice gets logged In practice, that looks like a versioned object the pipeline emits and logs. Example shape (illustrative, not a live record): JSON { "schema_version": "1.2", "decision_type": "exception_triage", "recommended_action": "hold_settlement", "actor_role": "ops.settlements", "expires_at": "2026-09-19T21:00:00Z", "sources": [ { "system": "trade_capture", "as_of": "2026-09-19T14:02:11Z", "stale_after_s": 900 } ], "missing_inputs": ["counterparty_credit_limit"], "dropped_context": { "chunks_retrieved": 15, "chunks_used": 8 }, "constraints": ["requires_dual_approval"], "human_gate": true, "response": { "choice": null, "reason_code": null }, "audit_log_id": null } dropped_context is how silent truncation becomes visible on the decision itself, instead of only in retrieval logs. If they have to open three other tabs to trust you, the last mile is unfinished. That structure has to come from the product and the pipeline: emit the object, version it, and log it. Asking the model to write a friendlier paragraph is a different problem, and it does not give you an inspectable decision. Pull By Default; Push Only With a Prescription Default to pull. Let people open the decision when they are ready. Push alerts are expensive. If you push, include a real next step and the evidence. "Something looks off" is how you train people to mute you. Do not treat feature-attribution plots (SHAP) as operator explainability on their own. Operators need to see which sources you used, how fresh they are, what is missing, and how to override. If that never appears in the UI, the explainability work does not count. The Silent Failure That Still Bothers Me In multi-tenant B2B systems, the scary failures are quiet ones. The model can answer fluently on the wrong tenant's context. Retrieval can look correct in the logs while facts disappear before generation because the context window is truncated without a clear error. I have spent days on bugs like that. Retrieval said one thing. Generation saw fewer chunks. No hard error. Missing information and a confident answer. In one production case, we retrieved 15 chunks, and only 8 reached the model; the rest were dropped by a silent context-window truncate with no alert. That is why the decision object needs an explicit field when retrieved context was dropped. So before you expand the decision surface, put gates in: Tenant and ACL checks on every retrieval pathRefuse or abstain when required sources are missingIf you dropped content, say so on the decision objectEval for silent failure, not only happy-path latency Abstaining is a valid product outcome. Confident wrong action is not. Stop Measuring the Demo Demo metrics are easy to improve and easy to misread. Answer fluency, latency on a clean happy path, and the count of AI features can all look better while operators are still slow to decide or still decide wrong under real conditions. I would rather track how long it takes to reach a decision when data is incomplete, how often exceptions appear and how long recovery takes, how often people override the recommendation and why, whether you can reconstruct what happened when something breaks, and whether people return to the tool in real decision moments rather than only during a pilot. If your charts look better but operators still make decisions the same way they did before the model shipped, those charts are not measuring product success. Write kill criteria before you ship the next agent, including a clear definition of when to stop expanding the decision surface. Maturity Ladder: Crawl Before Run I use a simple maturity ladder so teams do not pretend they are ready for aggressive automation. At Crawl, support one kind of decision only. Keep it pull-based: the operator opens the recommendation when they need it, rather than getting interrupted by alerts. Log every decision object. Once a week, review why people overrode the recommendation. That is enough to learn whether the product is usable. At Walk, add a small number of additional decision types. Put freshness expectations on the inputs. Allow the system to abstain when evidence is missing. Assign someone to own the operating metrics so override patterns and recovery time do not get ignored. At Run, use push notifications only for a narrow set of cases where missing the signal is expensive. Add dual-track retrieval when latency matters: a fast path for simple queries and a slower path when depth is worth the wait. Keep reviewing overrides, and treat them as product signal rather than operator error. Vendor demos push teams toward Run. In production, Crawl usually needs to last longer than anyone wants. Expand the catalog only after the current decision surface has a stable override pattern. If Experts Are Ignoring You, Do This Next Week Starting with a bigger model is usually the wrong first move. Pick one decision type and one screen instead. Constrain the action catalog. Five to ten actions is plenty.Emit a decision object for every recommendation.Log accepts and overrides with reason codes.Review overrides for a week without touching the model.Fix freshness and silent truncation before you add features. In high-stakes environments, the useful systems are usually the ones that invest in the last mile: a concrete next step, inspectable evidence, stated uncertainty, clear responsibility, and a clean way to override. That is harder than polishing a demo, and it is what turns a score into something an operator can use.

By Sidharth Gopakumar
Zero Trust for Agents: A New Lens to Secure Agents
Zero Trust for Agents: A New Lens to Secure Agents

I spend a lot of my time reviewing other people's architectures. Increasingly, those architectures have agents in them, and the ones that worry me are almost never the ones with an obvious flaw. Here is a shape I keep running into. A support agent reads incoming tickets, looks up order history, and drafts a reply. The team has done the work: read-only database credential, ticketing API key scoped to one project, egress restricted to a couple of hostnames, secrets pulled from a vault instead of environment variables. Every question on the review checklist has a good answer. The question that does not get asked is how far that read-only credential actually reaches. Usually the whole schema. And the agent picks what to read from it based on text that arrived from the internet, written by whoever opened the ticket. Nothing in the design is broken. The agent simply holds authority it does not need, and an untrusted party has a channel into its decision loop. This is not an exotic failure. It is OWASP LLM06:2025, Excessive Agency, almost verbatim. OWASP traces it to excessive functionality, excessive permissions, and excessive autonomy. In what I see, it is nearly always the middle one. The entry even names the exact anti-pattern: an extension meant only to read data connecting with an identity that also carries write privileges, and the related one where a per-user operation runs under a generic high-privileged account. Underneath it sits the confused deputy problem, roughly forty years old, wearing new clothes. What is new is that the deputy reasons in natural language, runs thousands of times an hour, and picks its own path through your systems. Instructions are Not Enforcement The usual first fix is to write the rule into the system prompt. "Only return records belonging to the customer who opened this ticket." "Never issue a refund above the order total." I have watched teams treat that as a control. It is not one. The instruction lands in the same token stream as the attacker's text, and the model weighs both. OWASP is blunt about the limits here, noting that given the stochastic nature of these models, "it is unclear if there are foolproof methods of prevention for prompt injection" (LLM01:2025). Retrieval grounding and fine-tuning reduce the problem. Neither closes it. Indirect injection is the part that catches teams out. The attacker does not need to talk to your agent. They only need to write something your agent will later read: a ticket body, a web page, a PDF, a code comment, a calendar invite. There is a second problem that gets less attention. Even if the instruction holds perfectly, you have no audit trail. When the prompt is the control, "why did the agent do that" has no answer beyond an inference trace nobody can replay deterministically. Try explaining that to an auditor. Treat the system prompt as product behavior. Worth investing in, and not a place you put anything you would be unwilling to see bypassed. OWASP's own mitigation list says as much, recommending you give the application its own API tokens and handle privileged functions in code rather than exposing them to the model. The same test disqualifies the other popular non-control. Do not put a classifier in front of everything and call it a guardrail. Input and output filtering is worth having as depth, and it catches the loud attacks, but it is probabilistic, which means it belongs behind your deterministic checks rather than instead of them. If a control can be talked out of its job, it is not the control. It is a filter. The Tenet Everybody Built, and the One They Skipped It is tempting to say Zero Trust does not fit agents. Having gone back to the source, I think that is wrong, and the real story is more useful. NIST SP 800-207 lists seven tenets. Tenet 3 is the one everybody built: "Access to individual enterprise resources is granted on a per-session basis." Authenticate the subject, evaluate context, grant the session, and note that access to one resource does not imply access to another. That tenet carried assumptions that agents break. It assumed the subject was slow and countable, where a person makes a few dozen meaningful access decisions a day and an agent makes hundreds a minute. It assumed the subject had judgment, because access control has always been a coarse filter that humans refine at runtime. An engineer with production database access does not run DELETE without a WHERE clause. Not because policy stops them, but because they know better. An agent does not know better. It knows what completes the task. Most of all, it assumed the session was the unit of risk. For agents, that is exactly wrong. The connection is the boring part. A coding agent is supposed to reach your repository host. What matters is which operation it is about to perform once it gets there. Reading a file is fine. Opening a pull request is probably fine. Force-pushing to a protected branch is not. All three ride the same authorized connection with the same token. Here is the part I did not expect. Tenet 4 already says that "resource access and action permission policies can vary based on the sensitivity of the resource/data." NIST wrote action-level control into the spec in 2020. Tenet 3 got built out properly, because for human users the session was a good enough proxy and the tooling grew up around that choice. Tenet 4 mostly did not. Agents remove the proxy. Once a subject can fire off hundreds of requests a minute with no judgment sitting behind any of them, Tenet 4 stops being an optional refinement and becomes the part that does the actual work. Everything practical in this article follows from taking it seriously. Five Things That Actually Change Give the agent its own identity, and make it a delegate rather than an impersonator. Most deployments I see run the whole fleet under one service account, or hand the agent the end user's token. Both destroy attribution. RFC 8693 named this distinction six years ago. Impersonation means the agent is the user, indistinguishable downstream. Delegation is different. The agent stays itself, and the act (actor) claim records who it is working for. Handing an agent a user token is impersonation, and it is why your logs cannot tell you who did what. Use delegation. The spec even defines may_act so you can declare in advance which agents are permitted to act for a given subject. Scope to the task, not the role. Role-based access assumes durability, that a subject and a resource have an ongoing relationship worth naming. Agent work is not durable. It is a task, which means it ends, and while it runs there are only a few things it legitimately needs to touch. Issue a capability at the start and let it die with the task. Python import time, uuid, jwt def issue_capability(user_sub, agent_id, task_id, actions, audience, ttl=120): now = int(time.time()) claims = { "iss": "https://broker.internal", "aud": audience, "sub": user_sub, # who this is on behalf of "act": {"sub": agent_id}, # RFC 8693: the acting party "jti": str(uuid.uuid4()), "iat": now, "exp": now + ttl, "task_id": task_id, "actions": actions, # ["orders:read"] "constraints": {"customer_id": "C-8841", "max_rows": 50}, "constraint_source": "ticket:48812", } return jwt.encode(claims, PRIVATE_KEY, algorithm="RS256") Enforcement is deterministic code, outside the model, that does not care how persuasive the ticket body was: Python def authorize(token, action, params): c = jwt.decode(token, PUBLIC_KEY, algorithms=["RS256"], audience="orders-api") if action not in c["actions"]: raise Denied(f"{action} not granted for task {c['task_id']}") k = c["constraints"] if params.get("customer_id") != k["customer_id"]: raise Denied("query scope exceeds task constraint") if params.get("limit", 0) > k["max_rows"]: raise Denied("row limit exceeds task constraint") Note constraint_source. It records where the constraint came from. When you investigate later, that field is how you trace a bad action back to the input that shaped it. Stop letting the agent hold credentials. If the agent process holds the API key, every bug becomes a credential bug. A verbose stack trace will do it. So will any code the agent can be talked into running. Put a broker in front of the tools. The agent submits an action and receives a result. The key stays on the broker and is attached to the outbound call there, in a process the agent cannot read. Python # No key exists in this process. result = broker.invoke( capability=cap_token, tool="orders.read", params={"customer_id": "C-8841", "limit": 25}, ) Agent Authentication Sequence That gap is the point. An agent permitted to call the orders API but unable to construct the call unaided has a far smaller failure mode than one carrying a key. Compromise it, and you inherit its permissions for as long as the capability lives, which is two minutes, rather than a secret you can copy out and reuse next month. Run generated code as hostile. Code your agent writes is untrusted by construction, produced by a probabilistic process partly steered by input you do not control. Isolated runtime, no network egress, no ambient credentials, read-only filesystem outside a scratch directory, wall-clock limit, memory cap. Container isolation alone is thin. For anything customer-facing, kernel-level isolation through a microVM or a user-space kernel is the right default. Log the action, not the request. Most agent logging captures the prompt and the completion. That tells you what was said, not what was done. Emit a structured event per tool call. Python { "ts": "2026-09-11T14:22:07Z", "task_id": "t-91ac", "sub": "user:8f21c", "actor": "spiffe://corp/ns/support/sa/ticket-agent", "tool": "orders.read", "params_hash": "sha256:9f2c4e...", "decision": "allow", "policy": "cap-scope-v3", "constraint_source": "ticket:48812" } At two in the morning, nobody wants to know what the model said. They want to know what it touched and who let it. That schema tells them. What a Task Boundary Does Not Fix The scoping advice above has a hole in it, and it is better to name it than to hope nobody notices. Two, in fact, and both sit in territory the LLM Top 10 only partly reaches. OWASP now runs a separate Agentic Security Initiative for roughly this reason. A capability that expires with the task is only a boundary if nothing crosses between tasks. Agents with persistent memory carry plenty. An attacker who gets one sentence into that memory does not need a live capability afterwards. Your broker will issue them a fresh one later, on request, correctly scoped and entirely legitimate, and every deterministic check will pass, because nothing about the request is malformed. The constraint was never wrong. The context it was reasoning over was. Short-lived credentials do nothing about long-lived beliefs. So treat durable memory as an input channel with the same standing as a ticket body. Record what produced every write. Memory you cannot attribute is memory you cannot roll back, and eventually you will want to. Do not load the agent's whole history into context by default either; scope reads to the task. Expire entries. Version it, so that when something does get in, you can see the diff. The second hole is in the broker itself. A tool description is text the model reads and acts on, so a tampered one is prompt injection arriving with your own infrastructure's authority behind it and none of the suspicion you would apply to user input. That is a large enough problem to deserve its own treatment, and it has had some good ones. The short version: pin your tool definitions and review changes to them the way you review a dependency bump. When Agents Call Agents Everything above assumes one agent. Add a second and enforcement has to survive the hop between them, which is exactly where most designs quietly stop checking and fall back to trusting the session. Multi-agent systems break one assumption people carry in without noticing: that the output of your own code is trustworthy input. It is not. OWASP files this under Improper Output Handling (LLM05:2025), and the point is that model output needs validating before anything downstream acts on it. And the Excessive Agency entry explicitly lists a "malicious/compromised peer agent" as an injection source in collaborative systems. An injected planner does not announce itself. It just emits a task that looks fine, and the next agent runs it on its own permissions. So validate at every hop, not just at the system edge. If a planner hands a retrieval agent a query, that query gets schema-checked and constraint-checked the same way a user request would. Two agents in the same process boundary are still two trust domains. RFC 8693 already solved the identity half of this, and I would take its rule as written. A delegation chain nests act claims, outermost being the current actor and deeper ones being prior actors: Python "sub": "user:8f21c", "act": { "sub": "spiffe://corp/ns/support/sa/ticket-agent", "act": { "sub": "spiffe://corp/ns/support/sa/orchestrator" } } The spec is precise about what to do with that chain. For the purpose of applying access control policy, it says, "the consumer of a token MUST only consider the token's top-level claims and the party identified as the current actor by the act claim," while prior actors are "informational only and are not to be considered in access control decisions." That is the right default for agent chains. A sub-agent never inherits its parent's permissions, and the parentage exists for forensics rather than for privilege. What This Costs I would rather be honest about the bill than pretend this is free. You are adding a hop. Token issuance plus a broker round trip is real latency on every tool call, and agents make many. Budget for it and keep the broker close to the tools. You are creating a dependency. The broker sits on the critical path for every agent action in your estate. It needs the availability engineering you would give an identity provider, because that is effectively what it now is. You are taking on a catalog. Somebody has to define what actions exist, what constraints each accepts, and who may grant them. Teams underestimate this. None of it is difficult. It just never finishes. And you will annoy your developers, at least at first. The honest counterargument is that this is the same trade the industry already made with secret management and with infrastructure as code. It felt like friction for about a year, and then it was just how things were done. Where to Start Next You do not need a program. You need a week. Inventory what is actually running. Every organization has more agents in production than the security team knows about, usually a scheduled job or a chat integration somebody wired up in an afternoon. Find the shared credentials. Grep your agent code for long-lived keys and for any place a fleet shares a service account or borrows a user token. That list is your blast radius, and I have never once seen it come back shorter than the team guessed. Then pick exactly one tool with a write path, because write paths are where the damage lives, and put it behind a broker with a task-scoped capability. One tool. Measure the latency, learn what breaks, use the result to argue for the rest. If you have to justify the work upward, MITRE ATLAS documents real attacks on AI systems and makes the case better than hypotheticals do, while the NIST AI Risk Management Framework and its Generative AI Profile supply the governance vocabulary to wrap around it. If you take one thing from this, make it the delegation point. An agent carrying a user's token is claiming to be that user, and everything downstream will believe it, including your own audit log six months from now when somebody asks you to reconstruct what happened. RFC 8693 drew that line in 2020 and handed you the claim to express it with. Almost nobody deploying agents has read it. The rest follows from there. Once the agent has a name of its own, you can scope what it does to the job in front of it, keep the credential somewhere it cannot reach, and write down what it actually touched. None of that is novel security thinking. It is the ordinary kind, applied to a new sort of principle that happens to work faster than anyone reviewing it. References Rose, S., Borchert, O., Mitchell, S., and Connelly, S. Zero Trust Architecture. NIST Special Publication 800-207, National Institute of Standards and Technology, August 2020. https://doi.org/10.6028/NIST.SP.800-207OWASP Top 10 for LLM Applications, LLM01:2025 Prompt Injection. OWASP GenAI Security Project. https://genai.owasp.org/llmrisk/llm01-prompt-injection/OWASP Top 10 for LLM Applications, LLM05:2025 Improper Output Handling. OWASP GenAI Security Project. https://genai.owasp.org/llmrisk/llm052025-improper-output-handling/OWASP Top 10 for LLM Applications, LLM06:2025 Excessive Agency. OWASP GenAI Security Project. https://genai.owasp.org/llmrisk/llm062025-excessive-agency/OWASP Agentic Security Initiative, Agentic AI: Threats and Mitigations. OWASP GenAI Security Project. https://genai.owasp.org/resource/agentic-ai-threats-and-mitigations/Jones, M., Nadalin, A., Campbell, B. (Ed.), Bradley, J., and Mortimore, C. OAuth 2.0 Token Exchange. RFC 8693, IETF, January 2020. https://www.rfc-editor.org/rfc/rfc8693.htmlArtificial Intelligence Risk Management Framework (AI RMF 1.0). NIST AI 100-1, January 2023. https://doi.org/10.6028/NIST.AI.100-1Artificial Intelligence Risk Management Framework: Generative Artificial Intelligence Profile. NIST AI 600-1, July 2024. https://doi.org/10.6028/NIST.AI.600-1MITRE ATLAS (Adversarial Threat Landscape for Artificial-Intelligence Systems). https://atlas.mitre.org

By Krishna Sunkavalli
Why Your RAG Pipeline, Not Your LLM, Is Causing Hallucinations
Why Your RAG Pipeline, Not Your LLM, Is Causing Hallucinations

Every time a large language model produces a confidently wrong answer, the industry reaches for the same word: hallucination. It’s a tidy label. It frames the failure as a mysterious, almost biological quirk of the model itself, as if the AI briefly lost touch with reality and there’s not much anyone can do about it except wait for a better model. That framing is convenient for model vendors. It is much less convenient for the truth. In production systems, especially retrieval-augmented generation (RAG) pipelines, which is how most enterprise AI actually gets deployed the majority of “hallucinations” I’ve seen traced back to something far less mysterious: bad data engineering. Stale indexes. Naive chunking. Missing metadata. Broken retrieval ranking. Silent ingestion failures. None of that is a model problem. All of it gets blamed on the model anyway. If you work in data engineering and you’ve been treating hallucination as someone else’s problem a model-layer issue for the ML team to solve it’s worth looking closer. There’s a good chance the fix lives in your pipeline, not their weights. What “Hallucination” Actually Looks Like in Production Textbook explanations describe hallucination as the model generating text that is fluent but factually unsupported by its training data or provided context. That’s accurate as far as it goes, but it skips the part that matters operationally: in a RAG system, the model is only as good as what it’s given to work with. Consider the actual failure modes engineers report most often: The answer is correct, but the citation is wrong. The model pulls the right fact but attributes it to the wrong document, because the retrieval step returned a topically similar but incorrect source.The answer is stale. The model confidently reports a policy, price, or spec that used to be true, because the index it’s querying hasn’t been refreshed since the underlying document changed.The answer is fabricated from fragments. A document got chunked at an awkward boundary mid-sentence, mid-table, mid-clause and the model stitched together a plausible-sounding but invented conclusion from two unrelated fragments that ended up adjacent in the context window.The answer is simply missing information the system actually has. Poor embedding quality or a mismatched similarity threshold means the right document existed in the corpus but never made it into the retrieved context, so the model filled the gap with something it invented. None of these are the model “hallucinating” in the sense of spontaneously inventing facts from nowhere. They’re the model doing exactly what it’s designed to do: generate a fluent, plausible continuation with broken or insufficient input. Garbage in, confident garbage out. RAG Pipeline Architecture The model only ever sees what survives the pipeline above it. Most hallucinations are decided long before generation even starts in chunking, indexing, retrieval, and metadata handling. Four Data Engineering Failure Points, and Where They Actually Live 1. Chunking strategy: Most RAG pipelines still chunk documents by a fixed token count, without regard to semantic boundaries. Splitting a table mid-row, a legal clause mid-condition, or a technical spec mid-parameter list doesn’t just lose information. It creates fragments that look complete but aren’t. The model has no way to know a chunk is truncated; it just answers with what it has. This is a classic ETL problem, not a model problem, and it’s fixable with better chunking logic (semantic or structure-aware splitting) long before it ever reaches inference. Naive Fixed-Token Chunk Boundary Causes a Fabricated Answer Same source document, same model, the only variable is where the chunk boundary was drawn. The naive split doesn’t just lose text. It produces an answer that sounds complete but silently omits a condition that changes the outcome. 2. Index freshness: Every RAG system has an implicit SLA on data freshness, whether or not anyone wrote it down. If your ingestion pipeline updates the vector index nightly but your source-of-truth documents change hourly, you have a guaranteed hallucination generator. The model will keep confidently answering with yesterday’s truth. This is squarely a pipeline scheduling and change data capture problem. 3. Retrieval ranking and thresholds: Embedding similarity is a proxy for relevance, not a guarantee of it. When similarity thresholds are tuned loosely, tangentially related documents get pulled into context, and the model treats them as authoritative. When thresholds are tuned too tightly, the correct document gets excluded, and the model has to guess. Getting this right is an ongoing data quality and evaluation exercise, not something you set once and forget. 4. Metadata and access-scoped retrieval: A shocking number of hallucinations in enterprise systems come from retrieval that ignores context like document version, region, or user permission, surfacing an outdated or wrong-jurisdiction document because the index wasn’t built with the metadata needed to filter it out. That’s a schema and indexing design failure, full stop. Why This Reframing Matters Calling this “hallucination” and routing it to the ML team means the fix gets sought in the wrong place: prompt tweaks, temperature adjustments, or maybe a bigger or newer model. Sometimes that helps marginally. It rarely addresses the actual defect, because the actual defect is upstream of the model entirely. Reframing it as a data engineering failure changes the incentive structure in a useful way. It puts ownership where the leverage actually is: with the teams who control ingestion, chunking, indexing, freshness, and retrieval quality. It also changes what gets measured. Instead of a vague “hallucination rate” benchmarked against the model, teams start measuring retrieval precision, index staleness, and chunk integrity, metrics that are actually actionable by the people who can fix them. This doesn’t mean models never confabulate on their own. They do, particularly in open-ended generation without any grounding context at all. But in the RAG-heavy, enterprise-context world most of us are actually building for, the model is rarely the first place to look. What This Looks Like in Practice If you want to test this thesis on your own system, a simple exercise: take a sample of hallucinated outputs your users have flagged, and for each one, manually trace whether the correct answer existed somewhere in your indexed corpus at the time of the query. In most systems I’ve audited this way, the correct source material was actually present; it just wasn’t retrieved, wasn’t current, or was fragmented in a way that made it useless. That’s not a model failure. That’s a pipeline failure wearing a model’s name tag. Before reaching for a bigger model or a different provider, it’s worth auditing: Are your chunks semantically coherent or arbitrarily sliced by token count?How stale can your index get before anyone notices?What’s your actual retrieval precision, not vibes, measured precision, at the top-k results you’re feeding the model?Does your retrieval respect metadata like version, scope, and permissions, or does it treat every indexed document as equally valid? The Bottom Line “Hallucination” is a useful word for describing a symptom. It’s a misleading word for describing a cause. Most of what gets blamed on the model in production RAG systems is actually a data engineering problem, and it’s one that’s genuinely fixable, with tools and practices data engineers already know well: better ETL, disciplined schema design, freshness SLAs, and rigorous evaluation of retrieval quality. The model isn’t lying to you. Your pipeline is.

By David Taiwo Balogun DZone Core CORE
From Theory to Practice: Building an Enterprise Ontology With Python and Kubernetes
From Theory to Practice: Building an Enterprise Ontology With Python and Kubernetes

Moving From Ontology Concepts to Implementation The previous article, Why AI Agents Need a Shared Ontology, explored how ontologies provide a shared semantic foundation for AI agents, enabling them to interpret business concepts, understand relationships, and operate with a consistent view of enterprise data. However, understanding the value of ontology is just the start. The next challenge is to turn those concepts into a working implementation that can be developed, validated, queried, deployed, and maintained as part of an enterprise technology ecosystem. An ontology is not just a list of business terms or a diagram. For it to be operational, it needs a formal representation of domain knowledge, clearly defined relationships, validation rules, a query mechanism, and an infrastructure environment (applications/services) where applications and services can access it. This is where Python, RDF, OWL, SHACL, SPARQL, Apache Jena Fuseki, and Kubernetes come together. From Semantic Models to Working Systems Consider a typical e-commerce application involving customers, products, orders, and payments. These entities may exist across different databases, applications, and services, each with its own data model and terminology. An enterprise ontology defines a common semantic model of what these entities represent and how they relate to one another. (A customer orders something; an order has products, and each product belongs to a category). But defining these relationships is not sufficient. We also need to answer practical engineering questions: How do we represent business concepts and relationships using Resource Description Framework (RDF) and Web Ontology Language (OWL)?How can Python be used to create, load, and query ontology data?How do we enforce data quality and semantic constraints using Shapes Constraint Language (SHACL)?How can applications query the knowledge graph using Protocol and RDF Query Language (SPARQL)?How do we deploy and expose the ontology through a containerized service running on Kubernetes?How can we incorporate ontology validation into automated testing and CI/CD pipelines? Answering these questions transforms ontology development from a conceptual exercise to an engineering discipline. What We Will Build In this tutorial, we plan to build a working e-commerce ontology in Python and deploy it on our local Kubernetes cluster. We will model customers, products, and orders using RDF and OWL first; populate the ontology with sample data; validate structure and constraints (SHACL) on it; perform SPARQL queries to get meaningful business relationships. Once the ontology is working locally, we will deploy Apache Jena Fuseki as a SPARQL endpoint on a Kubernetes cluster created with kind (Kubernetes in Docker). We will use Podman for container image management, and Kubernetes manifests to deploy and expose the service. Next, we will see how to run automated tests and validate ontology changes before deploying them to an application environment. The objective is not to build an enterprise knowledge platform in one tutorial. Instead, the aim is to establish a practical, reproducible foundation from which we can show how semantic modeling works with validation, querying, and cloud-native deployment. At the end of this tutorial, a functioning ontology-backed service would be implemented that can be queried via SPARQL and extended for more complex use cases (knowledge-driven applications, semantic interoperability, and AI agents running on shared business context). The central idea is simple: an ontology becomes valuable when it moves beyond defining what enterprise data means and becomes an operational component that applications can use. Understanding the Reference Architecture The architecture separates ontology development from runtime services. Python is the development and automation layer; RDF and OWL are semantic model definitions; SHACL checks data consistency; Apache Jena Fuseki stores and exposes the knowledge graph; Kubernetes provides the deployment environment. Key Components of the Architecture Ontology Modeling: RDF and OWL The foundation of the platform is the ontology model. RDF stores information as triples (subject, predicate, object). OWL extends RDF-based modeling with constructs for defining classes, properties, relationships, and logical semantics. In our e-commerce example, we define concepts such as Customer, Order, Product, and Payment, along with relationships such as placesOrder and containsProduct. Together, these definitions establish a common semantic vocabulary that applications can use to interpret enterprise data consistently. Ontology Processing: Python and RDFLib Python provides the programming environment for working with the ontology. Using the RDFLib library, we can load RDF/OWL files, manipulate graph data, execute SPARQL queries, and automate ontology-related operations. This lets us develop and test the ontology locally before adding infrastructure dependencies. Data Validation: SHACL Defining an ontology does not necessarily guarantee that all incoming data satisfies business requirements. SHACL allows us to define validation constraints on RDF data. For example, we can say that every customer has a name and email address or that a product has a valid price. We will use Python and pySHACL to validate sample data against these constraints before loading it into the knowledge graph. Knowledge Graph Storage: Apache Jena Fuseki Once the ontology and its instance data are ready, they need to be accessible to other applications. Apache Jena Fuseki provides an RDF storage and query service that exposes SPARQL endpoints over HTTP. Applications can retrieve and update graph data via standards-based interfaces. In our implementation, Fuseki will store the e-commerce ontology and its associated instance data, making relationships between customers, orders, and products queryable. Application Integration: SPARQL and REST APIs SPARQL is the standard query language for retrieving and manipulating RDF graph data. Applications can access Fuseki directly (via a SPARQL endpoint) or through an application API built with Python and FastAPI. For example, an application can query all products purchased by a particular customer by traversing the relationships in the ontology. Cloud-Native Deployment: Containers and Kubernetes Finally, we need an environment where the ontology service can be deployed and managed. We use Podman to build container images and kind to create a local Kubernetes cluster. Apache Jena Fuseki and the Python API will run as containerized services inside Kubernetes. Kubernetes provides service discovery, workload management, and deployment orchestration. For production use, the architecture can be extended with persistent storage, authentication, monitoring, resource controls, and high availability. How the Components Work Together The reference architecture follows a simple development-to-runtime workflow: Model: Define business concepts, properties, and relationships using RDF and OWL.Populate: Create sample instances representing customers, products, and orders.Validate: Apply SHACL constraints to verify the consistency and completeness of the RDF data.Store: Load the validated RDF graph into Apache Jena Fuseki.Query: Execute SPARQL queries to retrieve business entities and relationships.Deploy: Run Fuseki and the Python application services on Kubernetes. It is important to distinguish between an ontology and a knowledge graph. Ontologies define the semantic structure and meaning of a domain; knowledge graphs combine those definitions with actual entities and their relationships. In this implementation, the ontology and sample data are represented as RDF graphs and loaded into Fuseki, where they can be queried together. Designing the E-Commerce Ontology The first step in implementing an enterprise ontology is to define the business domain and identify the concepts and relationships that need to be represented. In this tutorial, we’ll use an e-commerce domain consisting of customers, orders, products, and payments. Although these concepts are familiar in traditional application development, ontology modeling approaches them differently. We don’t design database tables and foreign keys; we define semantic classes, properties, and relationships that describe what business entities mean and how they are connected. Identifying Domain Concepts We start by listing the entities involved in an e-commerce transaction. A customer places an order, an order contains products, and payments are associated with orders. These relationships form the foundation of our ontology. In more advanced models, we can introduce an OrderItem class to store individual order lines, including purchased quantities and prices. The objective is to create a reusable semantic model rather than copying the structure of an existing database. Defining Classes and Properties Once the domain concepts are identified, we define them as OWL classes. Object properties establish relationships between individuals. For example, placesOrder connects a customer to an order, while containsProduct connects an order to a product. Datatype properties describe literal attributes such as customer names, email addresses, product prices, and order dates. Using these constructs, we establish the vocabulary needed to represent and query e-commerce information consistently. Establishing Relationships and Constraints Ontology modeling also means defining the intended semantics of relationships. For example, the placesOrder property can have Customer as its domain and Order as its range. These declarations support semantic interpretation and inference. However, OWL is not a conventional database constraint engine. Domain and range declarations are used for reasoning, and OWL cardinality restrictions do not automatically reject incomplete data. For operational data-quality requirements, we will introduce SHACL in the validation section. Choosing Namespaces and IRIs Every class, property, and individual in an RDF ontology is identified by an Internationalized Resource Identifier (IRI). For this tutorial, we will use a consistent namespace such as: http://example.com/ecommerce/ This allows us to define identifiers such as: http://example.com/ecommerce/Customerhttp://example.com/ecommerce/Producthttp://example.com/ecommerce/placesOrder For production ontologies, these identifiers should use a domain controlled by the organization and follow a stable naming convention. Modeling the Ontology With Protégé We will use Protégé to create and inspect the ontology visually. Protégé provides an interface for defining OWL classes, object properties, datatype properties, and individuals. It also allows us to inspect the class hierarchy and verify how the different elements are connected. Once the model is defined, we will export it in Turtle format and use Python RDFLib for further processing. This separation lets domain modeling be done visually while ontology validation, querying, and deployment remain automated. Exporting the Ontology After completing the model, we save the ontology as ecommerce-combined.ttl. Turtle serializes RDF in a human-readable way so that the ontology is suitable for source control, code reviews, automated testing, and CI/CD. The exported file becomes the starting point for the next stage, where we will populate the ontology with sample e-commerce data and query the resulting knowledge graph. Once we are done with the model, we save the ontology as ecommerce-combined.ttl. Implementing the Ontology With Python With the e-commerce ontology modeled in WebProtégé, the next step is to make it accessible programmatically using Python and RDFLib. RDFLib provides the capabilities to load, manipulate, serialize, and query RDF graphs. This allows us to work with ontology definitions and instance data locally without requiring a graph database or Kubernetes infrastructure. Setting Up the Project The implementation is organized into separate directories for ontology definitions, sample data, SHACL validation rules, Python scripts, automated tests, and Kubernetes deployment manifests. The complete project, including dependencies and setup instructions, is available on GitHub: Enterprise E-Commerce Ontology — GitHub Repository. The repository's README provides step-by-step instructions for running the implementation locally and deploying it to Kubernetes. Loading and Processing the Ontology We first export the ontology from WebProtégé in Turtle format and save it as ontology/ecommerce-combined.ttl. With RDFLib, the exported graph can be inspected and processed. The implementation also splits ontology definitions from instance data into two files: ontology/ecommerce.ttl – Defines ontology classes and properties.ontology/sample-data.ttl – Contains sample entities and their relationships. This separation allows us to keep the semantic model and the data represented by that model distinct. Querying the Knowledge Graph Locally Once the ontology and sample data are loaded, we can run SPARQL queries using RDFLib to traverse business relationships. For example, we can identify products associated with customer orders by following the placesOrder and containsProduct relationships. The repository includes scripts/query_local.py, which shows how to query the ontology directly from Turtle files. Shell python scripts/query_local.py ontology/ecommerce.ttl ontology/sample-data.ttl This verifies that the ontology is not merely a collection of definitions but a queryable semantic graph representing actual business relationships. At this stage, we have a working local knowledge graph that can be inspected and queried using Python, without introducing Apache Jena Fuseki or Kubernetes. The complete implementation, Python scripts, sample data, and execution instructions are available in the GitHub README. Validating the Ontology With SHACL RDF and OWL specify the structure and semantics of an ontology but do not enforce all data-quality constraints that enterprise applications need (e.g., uniqueness). For example, OWL can describe a customer class and its properties, but it does not necessarily reject a customer record that is missing an email address. This is where Shapes Constraint Language (SHACL) becomes important. In our e-commerce implementation, SHACL shapes specify validation requirements for customers, products, and orders: CustomerShape: Validates customer names and email addresses.ProductShape: Validates product names and prices.OrderShape: Validates relationships between orders and customers. We use Python with pySHACL to validate the RDF graph against these shapes. Python python scripts/validate.py The validation process returns a conformance result and reports constraint violations when the data fails validation. The project's validation script also returns a nonzero exit status on failure. This is an important operational control because invalid RDF data can be detected before being published to the knowledge graph. The complete SHACL definitions and validation implementation are available in the GitHub repository. From a Working Prototype to an Enterprise Ontology Platform While the above implementation provides a functional foundation, operating an ontology at enterprise scale brings other considerations. The challenge moves from creating a semantic model to making sure it’s governed, secure, scalable, and reusable as business requirements change over time. Ontology Versioning and Change Management Enterprise ontologies are constantly being updated as new business concepts, relationships and applications are introduced. Ontology definitions, SHACL shapes and other artifacts should be version controlled with changes reviewed and tested before release. Changes to classes, properties, or IRIs should also be evaluated for impact on existing SPARQL queries and consuming applications. Stable IRIs, documented deprecation policies, and compatibility checks are needed to keep semantic consistency across versions. Governance and Ownership An enterprise ontology needs clearly defined ownership. Domain experts should own the meaning of business concepts, while ontology engineers maintain the semantic model and platform teams manage the supporting infrastructure. A light governance process should set standards for naming conventions, namespace management, ontology extensions, and approval of changes. This prevents different teams from introducing conflicting definitions of the same business concepts. Security and Access Control As ontologies become shared enterprise assets, access to their data and query interfaces must be controlled. In production environments, SPARQL endpoints and APIs should be protected through authentication, authorization, encrypted communication, and network policies. Access controls may need to distinguish between users who can query the graph and those authorized to modify ontology definitions or instance data. Sensitive business information should also be governed according to organizational data-classification and privacy requirements. Scalability, Persistence, and Reliability The local Kubernetes deployment demonstrates how ontology services can be containerized and managed, but production environments require additional operational safeguards. Persistent storage is essential for preserving RDF datasets across pod restarts and rescheduling. Backup and recovery procedures, resource monitoring, and capacity planning become important as graph size and query traffic increase. The storage architecture should be selected based on expected data volume, query complexity, concurrency, and availability requirements. CI/CD and Deployment Promotion Ontology development can be done using the same controlled delivery practices as application development. A CI/CD pipeline can check RDF syntax, SHACL checks, ontology tests, and incompatible schema changes before pushing updates to development, testing, and production environments. Separating ontology definitions from environment-specific configurations also makes deployments more predictable and reproducible. Reusing the Ontology Across Applications and AI Agents One of the most important benefits of an enterprise ontology is that it can be used as a shared semantic foundation for many applications. Instead of having different interpretations for customers, products, and orders, applications can use common ontology definitions and query interfaces. The same foundation can be used for analytics platforms, knowledge-driven applications, and AI agents that need to discover and interpret business relationships. However, a shared ontology does not guarantee interoperability. Applications must adopt its vocabulary, identifiers, and data contracts consistently. The table below summarizes the key differences between the prototype developed in this tutorial and the capabilities typically expected in an enterprise ontology platform. Capability Working Prototype Enterprise Platform Ontology Management RDF/OWL files maintained in Git Versioning, lifecycle management, and change governance Validation SHACL validation and local tests Automated validation and quality gates Governance Developer-managed definitions Domain ownership and approval processes Security Local access to endpoints Authentication, authorization, and auditing Storage Local RDF dataset Persistent storage, backups, and recovery Deployment Local Kubernetes cluster Controlled CI/CD and environment promotion Integration Sample SPARQL queries and APIs Shared semantic contracts across applications and AI agents The key transition from prototype to enterprise platform is therefore not simply scaling the knowledge graph. It is establishing the governance, engineering practices, and operational controls needed to maintain a trustworthy semantic foundation across the organization. Evolving Toward an Enterprise Knowledge Platform The e-commerce ontology implemented in this tutorial shows how semantic models can be developed, validated, deployed, and queried using open standards and cloud native technologies. But the same architecture can be scaled up from a single application to a shared enterprise knowledge platform. As shown in the above figure, enterprise architecture adds governance, validation automation, persistent graph storage, access controls, and reusable semantic services on top of the foundational ontology implementation. These capabilities enable several extensions: AI agents: Agents can leverage ontology-backed services to find business entities, navigate relationships, and retrieve structured contextual information.Semantic retrieval: Knowledge graph queries can complement vector-based retrieval and RAG (retrieval augmented generation): explicit relationships and structured business context.Cross-system interoperability: Applications in different business domains can reuse shared vocabulary, identifiers, and semantic mappings to exchange information consistently. Instead of each application interpreting business entities differently, the ontology becomes a reusable semantic layer between enterprise systems, applications, and AI-driven services. This is the move from a standalone knowledge graph implementation to a governed enterprise knowledge platform which can support multiple applications and AI agents. Conclusion Building an enterprise ontology is not just about classes and relationships — it’s also about making business knowledge accessible, consistent and reusable across applications. In this tutorial, we moved from ontology concepts to a working implementation (Python, RDF/OWL, SHACL, Apache Jena Fuseki and Kubernetes). We modeled an e-commerce domain, validated its data, queried relationships using SPARQL, and deployed the knowledge graph as a cloud native service. This is just the starting point – this same foundation can be used to build a governed enterprise knowledge platform with semantic interoperability, knowledge-driven applications and AI agents that share business context. The future of enterprise AI isn't just about smarter models; it's about giving them a shared understanding of the world they operate in.

By Josephine Eskaline Joyce, Ph.D DZone Core CORE
Hosted Code Interpreter in Spring AI: Letting OpenAI Write and Run Python via the Responses API
Hosted Code Interpreter in Spring AI: Letting OpenAI Write and Run Python via the Responses API

LLMs are good at explaining how to compute something and surprisingly unreliable at actually computing it. Ask for an estimate that involves a division, a rounding rule, and a confidence interval, and the response will be convincing while the numbers are not quite right. The standard fix is to let the model write code and have something else execute it. OpenAI’s hosted Code Interpreter does exactly that, inside a single API request: the model writes Python, OpenAI runs it in a sandboxed container, the printed output is fed back to the model, and the model answers using the real result. Nothing executes on our side. Spring AI 2.1.0-RC1 adds first-class support for this capability through its new OpenAI Responses chat model. This article shows how little is needed to turn it on in a Spring Boot application and why it requires the Responses API rather than Chat Completions. Finally, it walks through a full request and response captured by a custom logging advisor, so the generated Python, its execution output, and the final answer are all visible. The complete POC is a small command-line application. Its only job is to send one problem statement to the model and print the solution. Setting It Up Three things are needed: the dependency, four configuration properties, and an ordinary ChatClient. Dependency The project builds on Spring Boot 4.1.2 with Java 25 and imports the Spring AI BOM at version 2.1.0-RC1. The single runtime dependency is the OpenAI starter. XML <properties> <java.version>25</java.version> <spring-ai.version>2.1.0-RC1</spring-ai.version> </properties> <dependencies> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-starter-model-openai</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-bom</artifactId> <version>${spring-ai.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> Configuration This is the whole of application.properties file. Properties files spring.ai.openai.api-key=${OPEN_AI_API_KEY} # use responses API spring.ai.openai.chat.api=responses # enable code interpreter spring.ai.openai.responses.hosted-tools.code-interpreter.enabled=true # readable reasoning: ask OpenAI for reasoning summaries (auto | concise | detailed) spring.ai.openai.responses.reasoning-summary=auto # return what the hosted code interpreter printed spring.ai.openai.responses.include=code_interpreter_call.outputs spring.ai.openai.chat.api=responses switches the auto-configured ChatModel from the Chat Completions endpoint to the Responses endpoint. With responses, Spring AI creates an OpenAiResponsesChatModel bean instead of an OpenAiChatModel.spring.ai.openai.responses.hosted-tools.code-interpreter.enabled=true declares the code interpreter as a tool on every request. The property’s own description in the configuration metadata reads “Let OpenAI run Python in a sandboxed container inside the request.”spring.ai.openai.responses.reasoning-summary=auto asks OpenAI to return summaries of the model’s reasoning. OpenAI never returns the raw reasoning text, so a summary is the only readable form we can get.spring.ai.openai.responses.include=code_interpreter_call.outputs asks for the outputs of the interpreter run, meaning what the Python printed, to be included in the response. Without it, the response says the code ran but doesn’t carry what it produced. The same thing can be done in code, per request, with: Java OpenAiResponsesChatOptions.builder() .hostedTools(HostedTool.CodeInterpreter.of()) .build() The HostedTool sealed interface also types web search, file search, MCP servers and image generation, plus a Raw escape hatch for tools Spring AI does not type yet. The CodeInterpreter record takes an optional container id, exposed as spring.ai.openai.responses.hosted-tools.code-interpreter.container-id, to reuse a container across requests. The Client and the Problem The service is a plain ChatClient. Nothing in it mentions tools, Python, or the Responses API. Java @Service public class ProblemSolver { private final ChatClient chatClient; public ProblemSolver(ChatClient.Builder chatClientBuilder) { chatClient = chatClientBuilder .defaultSystem("You are a helpful problem solver. " + "Provide elegant, meaningful solutions to the requested problems.") .defaultAdvisors(new CustomLoggingAdvisor()) .build(); } public String solve(String problem) { return chatClient.prompt() .user(problem) .call() .content(); } } A CommandLineRunner sends one problem at startup and logs the answer. The problem is a classic estimation task: how many identical objects fit in a container, given the volumes and a packing density. Java private static final String PROBLEM = """ Use Python to estimate the quantity of similarly shaped objects inside a container. Optionally report a lower and upper confidence bound based on uncertainty in the measurements. The program shall print the results to the console. Input: container_volume = 540.0 # cm^3 object_volume = 1.25 # cm^3 packing_density = 0.64 # between 0 and 1 Output: estimated_count """; The prompt says “Use Python” and “print the results to the console.” That nudge makes the model reach for the interpreter rather than do the arithmetic in its head. Why the Responses API and Not Chat Completions Chat Completions has no notion of a tool that the provider runs for you. Normally, every tool is a function the application declares, the model requests, and the application executes before sending the result back in a second round trip. Hosted tools such as code interpreter, web search, file search, and image generation exist only on the Responses API, which is where OpenAI lands new capability. There is a harder constraint too. Starting with GPT-5.4, Chat Completions no longer supports tool calling combined with a reasoning effort other than none. In Spring AI, flipping spring.ai.openai.chat.api to responses is enough to swap the implementation underneath the same ChatClient. The code in ProblemSolver does not change. Hosted tools are deliberately not modelled as ToolCallbacks. There is nothing for the application to run, so their calls never surface as tool calls and never trigger the client-side tool-calling loop. Instead, each hosted tool call appears in the response transcript as its own item. A summary of them is placed on the generation metadata under the key openai.responses.hosted_tool_calls, as a list of type, id and status entries. The request builder applies exactly three framework-level defaults, all for correctness: store: false is always sent. The model is stateless by design and it is also what makes OpenAI return the encrypted reasoning blob instead of keeping it server-side.include always contains reasoning.encrypted_content and anything we configure is merged with it rather than overriding it. That is why the code_interpreter_call.outputs value in our properties file is added to, not replacing, the default.Function tool schemas are sent with strict: false unless told otherwise. Everything else defers to the provider default unless set. The CustomLoggingAdvisor To see what actually travels over the wire in domain terms, the project registers a CallAdvisor. Advisors wrap the call to the model. This one runs at LOWEST_PRECEDENCE, so it is the innermost advisor and sees the final prompt going out and the raw ChatResponse coming back, before any other advisor touches either. Java @Override public ChatClientResponse adviseCall(ChatClientRequest request, CallAdvisorChain chain) { log.info("\n{}", formatRequest(request.prompt())); long start = System.nanoTime(); ChatClientResponse response = chain.nextCall(request); long elapsedMs = (System.nanoTime() - start) / 1_000_000; log.info("\n{}", formatResponse(response.chatResponse(), elapsedMs)); return response; } The request side prints the model, the options class, temperature and max tokens, then each message with its type (see formatRequest()). The response side prints the elapsed time, the model that answered, the token usage, then the interesting part – the assistant message broken down into its parts (see formatResponse()). In Spring AI 2.x an AssistantMessage is a list of MessageParts. The hierarchy is sealed, which lets the advisor classify each part with an exhaustive pattern-matching switch: Java private String category(MessagePart part) { return switch (part) { case TextPart _ -> "TEXT"; case ReasoningPart _ -> "REASONING"; case ToolCallPart _ -> "TOOL_CALL"; case ToolResultPart _ -> "TOOL_RESULT"; case MediaPart _ -> "MEDIA"; case UnknownPart u -> "PROVIDER(" + u.kind() + ")"; }; } The advisor first prints the order in which the parts arrived, then groups them by category. The order matters: for the Responses API, each output item becomes exactly one part, in transcript order, so the Order: line is a faithful record of what the model did during the request. The code interpreter call arrives as an UnknownPart. That is the type Spring AI uses for any item a server-side tool produced or any item type the SDK does not model yet. It carries the provider (openai.responses), the item’s type as its kind and the whole item as JSON in rawJson(). The advisor parses that JSON and when it finds a code field, renders the Python and each entry of outputs: Java if (node.has("code")) { sb.append('\n').append("Code:\n").append(indent(node.get("code").asString(), 2)); JsonNode outputs = node.get("outputs"); if (outputs != null && outputs.isArray()) { sb.append('\n').append("Outputs (").append(outputs.size()).append("):"); for (JsonNode output : outputs) { String type = output.path("type").asString("?"); String body = output.has("logs") ? output.get("logs").asString() : output.has("url") ? output.get("url").asString() : output.toPrettyString(); sb.append('\n').append(indent("[" + type + "]\n" + indent(body, 2), 2)); } } return sb.toString(); } An output of type logs is what the program printed to stdout. An output of type image carries a URL, which is how a plot made with matplotlib would come back. Reasoning parts are rendered from their summary, and the size of the opaque encrypted payload is reported rather than its content, since it is not meant to be read. Walking Through a Run What follows is the advisor’s output for one real run of the application, lightly trimmed. The generated Python is about 130 lines, so only its shape is quoted. The numbers are reproduced exactly. See Resource 4 for the full version of the generated code. The Request Plain Text >>> REQUEST Model: gpt-5-mini Options type: OpenAiResponsesChatOptions Temperature: - Max tokens: - Messages: 2 [1] SYSTEM You are a helpful problem solver. Provide elegant, meaningful solutions to the requested problems. [2] USER Use Python to estimate the quantity of similarly shaped objects inside a container. ... The options class confirms the endpoint swap: an OpenAiResponsesChatOptions instance, not the Chat Completions one. No model was configured, so the framework default gpt-5-mini is used. Temperature and max tokens are unset and therefore left to the provider. The two messages are what the ChatClient assembled from the default system text and the user prompt. On the wire, they do not travel as a messages array. The Responses request builder puts the first system message into the top-level instructions field and the user message into the input list. The code interpreter tool is not visible here because it is not a message. It is added to the request’s tools array by the request builder from the enabled hosted tools. The Response Header Plain Text <<< RESPONSE (44092 ms) Model: gpt-5-mini-2025-08-07 TOKENS Prompt (input): 3242 Completion (output): 4081 Total: 7323 ASSISTANT MESSAGE PARTS (3 total) Order: REASONING -> PROVIDER(code_interpreter_call) -> TEXT Forty-four seconds for one call is quite a lot, but this is the honest cost of what happened: The model reasonedWrote a programOpenAI started a container and ran a 200,000-sample Monte Carlo simulation (Resource 3)The model then wrote its answer All of that is one HTTP request from the application’s point of view. The model name in the response is the dated snapshot that served the request. The token figures also tell a story. Our two messages are a few hundred tokens, yet the input count is in the thousands, because a hosted tool call is a multi-step exchange on OpenAI’s side and the interpreter’s output is fed back to the model as input within the same request. The output count covers the reasoning, the generated code, and the final text. The Order: line is the transcript. Three output items came back and became three parts in that exact order: The model thoughtThen it ran codeThen it answered There was no second reasoning item after the execution. The model went straight from the interpreter’s output to its text. The Reasoning Part Plain Text >> REASONING [1] #1 (part 1 of 3) Summary: **Estimating object count in containers** I'm tasked with creating Python code to estimate the number of similarly shaped objects in a container using the formula container_volume × packing_density / object_volume. I need to report confidence bounds based on uncertainties and use the first-order propagation of uncertainty. ... **Creating estimation code** ... **Building estimation code with options** I need to use `python_user_visible` to run the code and show outputs ... ... **Implementing Monte Carlo sampling** ... Opaque payload: provider=openai.responses, kind=encrypted_content, 11768 chars This is what reasoning-summary=auto produces. One reasoning item carried four summary entries, which Spring AI joins into a single summary() string without a separator, which is why the bold headings run into the preceding sentence. The summary is readable enough to see the model’s plan. The basic formula, first-order error propagation using partial derivatives and a Monte Carlo check, with the decision to demonstrate both with example uncertainties since the prompt made the bounds optional and gave none. One detail gives away the mechanics. The model refers to a tool named python_user_visible. The reasoning is deciding to call the hosted tool. The ReasoningPart.text() is empty because OpenAI does not return raw reasoning. What it does return is the encrypted blob, here quite a long one, held in the part’s payload. The Code Interpreter Part Plain Text >> PROVIDER [1] #1 (part 2 of 3) Provider: openai.responses Kind: code_interpreter_call Code: # Estimate number of similarly shaped objects in a container # Shows point estimate and optional confidence bounds (analytic propagation + Monte Carlo) import math import numpy as np from scipy.stats import norm def estimate_count(container_volume, object_volume, packing_density, container_unc=None, object_unc=None, packing_unc=None, ci=0.95, mc_samples=200000, random_seed=0): ... N = (container_volume * packing_density) / object_volume ... sigma_N_analytic = math.sqrt( (dN_dVc * sigma_Vc)**2 + (dN_dp * sigma_p )**2 + (dN_dvo * sigma_vo)**2 ) ... rng = np.random.default_rng(random_seed) ... container_volume = 540.0 # cm^3 object_volume = 1.25 # cm^3 packing_density = 0.64 # between 0 and 1 ... container_unc = 5.0 # cm^3 (std dev) object_unc = 0.05 # cm^3 (std dev) packing_unc = 0.02 # absolute (std dev) ... Outputs (1): [logs] Point estimate (no uncertainties): estimated_count = 276.480 Estimate with uncertainty propagation and Monte Carlo (example uncertainties): point estimate = 276.480 analytic std dev (approx) = 14.266 analytic 95% CI = (248.520, 304.440) Monte Carlo mean = 276.962 Monte Carlo std dev = 14.298 Monte Carlo 95% CI = (250.222, 306.285) Monte Carlo samples used = 200000 This is the part the whole setup exists for. It arrived as an UnknownPart whose kind is code_interpreter_call, the item type OpenAI assigns to a hosted interpreter run. The advisor found the code field in the raw JSON and printed it, followed by the single logs output. The program is a reasonable piece of engineering, not a one-liner. In the end, its execution prints both the plain estimate and the uncertainty-aware one. The [logs] block is stdout from the container. These numbers were computed by NumPy and SciPy, not predicted by the model. This output only came back to us because of include=code_interpreter_call.outputs. Without it, the item would still report that code ran, but the outputs array would be absent. On the other hand, note what is empty: Plain Text >> TOOL CALLS [0] (none) >> TOOL RESULTS [0] (none) Nothing was asked of the JVM. No ToolCallPart was produced, no function ran locally, and Spring AI’s tool-calling loop never engaged. The entire execution happened between the model and OpenAI’s container. The Text Part Plain Text >> TEXT [1] #1 (part 3 of 3) I ran a short Python program that computes the estimated count and — if you provide measurement uncertainties — returns approximate confidence bounds using both analytic (first-order) uncertainty propagation and a Monte Carlo simulation. Point estimate: - estimated_count = 276.480 Results (95% CI shown): - analytic 95% CI ≈ (248.520, 304.440) - Monte Carlo mean ≈ 276.962 - Monte Carlo 95% CI ≈ (250.222, 306.285) Code (you can copy and run; change the uncertainty values or CI/confidence level as needed): ... This is the string that content() returns to ProblemSolver.solve() and that the runner logs as the solution. Obviously, every figure in it matches the [logs] output perfectly, because the model wrote the answer after reading the execution result. The final text is the only one of the three parts that a plain content() call exposes. The reasoning and the interpreter runs are present on the ChatResponse as parts and in the generation metadata, but an application has to look for them, which is exactly what the advisor does. Takeaways The hosted code interpreter turns “write me a program” into “run me a program” without any execution plumbing on our side. No local Python, no sandbox, no tool-calling loop. In Spring AI 2.1.0-RC1, enabling it is one property to pick the Responses endpoint and one to switch the tool on. Two more properties, for reasoning summaries and interpreter outputs, make the result readable. The Responses model keeps the familiar ChatClient surface while exposing the richer transcript as typed message parts. A small advisor that walks those parts is the cheapest way to see what the model reasoned, what it executed, and what it concluded. Natural next steps are reusing a container across requests through spring.ai.openai.responses.hosted-tools.code-interpreter.container-id and asking for a chart, which would come back as an image output with a URL in the same code_interpreter_call item. Resources [1] – Spring AI 2.1 reference, OpenAI Responses chat model [2] – OpenAI, Code Interpreter tool guide [3] – Monte Carlo Method [4] – Project sample code is here.

By Horatiu Dan DZone Core CORE
How Did We Go From ChatGPT to Autonomous AI Agents in Just Four Years?
How Did We Go From ChatGPT to Autonomous AI Agents in Just Four Years?

Do you remember the first time you used ChatGPT? What was your initial reaction, and did you imagine we'd be where we are with AI today? With the fourth anniversary of ChatGPT's public release recently passing, now seems like a good time to revisit some of the developments that have changed how we interact with AI and incorporate it into our daily workflows. In this episode of The Neuron AI Explained, hosts Corey and Grant take a trip down memory lane, working backward from today's advanced AI agents to the November 2022 release of ChatGPT. They share their personal experiences with different models, what impressed them at the time, and how their perspectives on AI have changed over the years. How Far Has AI Come Since 2022? It's interesting to revisit some of the capabilities that once amazed us and are now familiar features of AI tools. Throughout the episode, Corey and Grant revisit several milestones, including: 2022: The public release of ChatGPT and its introduction to everyday users. 2023: The emergence of larger context windows and early tool-use capabilities. 2024: Advancements in multimodal AI, voice interactions, and reasoning models. 2025: The growing adoption of AI coding assistants, reasoning models, and agentic workflows. 2026: The expansion of long-running AI agents, computer use, and multi-agent orchestration. Beyond model releases, the two also discuss the influence of open-source projects, the balance between AI safety and accessibility, and the importance of evaluating emerging technologies for what they could eventually become. What Could the Next Four Years of AI Look Like? Toward the end of the episode, Corey and Grant share their predictions for the future of AI, touching on scientific discoveries, competition among AI providers, potential vendor lock-in, and the role robotics could play in the future of work. Grant also introduces an interesting concept he calls machine labor on demand, envisioning a future where individuals have access to both AI models and robots to carry out tasks and collaborate on projects. I'll leave the rest of that discussion to those two! Video from The Neuron AI Explained YouTube channel. If you're interested in further developing your AI skills, check out The Neuron Academy for hands-on lessons, structured learning paths, and practical examples. In the meantime, I'd love to hear from our DZone community: Of all the AI advancements we've seen over the past four years, which has had the biggest impact on how you work as a developer? Share your thoughts in the comments!

By Dominique Pugh
We’re Not Paid to Practice Scrum, but Answer 5 Product Questions
We’re Not Paid to Practice Scrum, but Answer 5 Product Questions

TL; DR: Five Product Questions Cheap Code Makes More Expensive to Skip Thesis: This article explains five product questions that become more consequential when AI makes software implementation cheap, why falling AI costs increase the volume of work those questions must filter, and how teams set working principles during early AI adoption. For decades, the cost of building software rationed what an organization could start: nobody could afford to build everything, so somebody had to choose, however crudely. AI has weakened that rationing; the frontier labs need your organization to use more AI with every model generation, and the product operating model promises to fix what Agile supposedly broke. None of this guarantees that anyone asks whether the work solves a customer problem, nor whether solving it was worth the cost. You need to address these product questions yourself. These product questions become more expensive to skip when starting work gets cheap: which problem is worth solving, whether the work is the best use of the team’s time, whether it is good enough for the people who will see it, whether it solved the problem, and whether the team’s way of working still fits. AI agents can prepare evidence under the A3 Framework’s Assist category, where the agent analyzes, and people decide, while explicit standards for AI-assisted work, such as the AI Definition of Done, and recurring inspections, such as the AI Delegation Audit, keep the answers honest. Whether you call any of this Scrum is the least interesting question of all. 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. If We’re Not Paid to Practice Scrum, What Are We Paid For? If you work in product, you probably believe that the slow, expensive build was the big problem of software development and that AI coding agents are finally solving it. Half of that belief holds up: building was slow and expensive, and agents have made writing code much cheaper. The other half deserves more scrutiny, because the expense was doing a crude rationing job that many organizations never replaced with anything better. When a feature took a team several weeks, somebody had to decide which idea got those weeks, and some weak ideas died in a prioritization meeting before anyone wrote a line of code. (Not many, admittedly; the ones with a senior sponsor and budget authority usually survived, and being chosen said nothing about whether an idea addressed a worthwhile problem.) The same expense also did damage, discouraging cheap experiments and pushing organizations to defend features they had already paid for in a prime example of submitting to the sunk cost fallacy. Product management has a name for the discipline that rationing never supplied on its own, and Uri Levine, the co-founder of Waze, put it into the title of his 2023 book, Fall in Love with the Problem, Not the Solution. When writing code costs next to nothing, falling in love with your own solution becomes affordable again. At the same time, testing whether customers care becomes cheaper than ever. For years, I have used one sentence to describe what agile practitioners are actually paid for: We are not paid to practice Scrum but to solve our customers’ problems within the given constraints while contributing to the organization’s sustainability. That sentence seems more useful now than ever, as Agile in general and Scrum in particular are under pressure from two sides at once. Two Promises of Speed, and What Adoption Does Not Guarantee The first pressure comes from the product operating model Marty Cagan popularized. He made the point plainly when I interviewed him in 2024: “To be blunt, a Scrum team is quite amateur compared to a professional product team,” as he put it in our interview on the product operating model and Scrum’s future. On paper, the model covers the questions this article is about. SVPG’s introduction to the product operating model states that “leaders in product management, technology, and design are responsible for deciding which problems to solve,” and it asks teams to find solutions that are valuable, usable, feasible, and viable. Adoption is a different matter. In my August 2026 survey of 48 practitioners, only 1 of the 26 respondents whose organizations had adopted the model or were moving toward it reported “a fundamental change in how build decisions are made.” Of the others, 9 described mostly relabeling, 9 a mix of real change and relabeling, and 7 said it was too early to tell. The respondents report on their organizations, though, and the survey did not verify 26 distinct organizations. Putting the model’s vocabulary on the slides seems to be easy, whereas changing who decides what to build, and on which evidence, is hard. The second pressure comes from AI in all its forms, from coding agents that build a working prototype in an afternoon to agents that promise to take over product decisions as well. If an agent can ship a feature by Friday, a two-week Sprint looks slow to many stakeholders, which is a misreading, because the Scrum Guide states that “an Increment may be delivered to stakeholders prior to the end of the Sprint.” In many organizations, a coding agent that receives a feature request delivers exactly that feature, and nobody asks whether the request addressed the right problem. Cheaper AI, More Work to Evaluate In 1865, William Stanley Jevons warned in ‘The Coal Question’ that Britain would exhaust the coal fueling its growth. As Yale’s Energy History project summarizes, “increased efficiency in consumption would not reduce demand for energy.” Efficiency can stimulate demand, and whether it does depends on the market; the AI industry, however, seems to be running through the Jevons Paradox at high speed. Epoch AI’s The plunging price of thought, published on September 22, 2026, estimates that “the cost of a given level of AI performance has fallen about 47% per quarter,” measured on five benchmarks in math, science, and games. The authors caution that benchmarks are imperfect proxies for useful work and that their figures “should not be read as exact.” Anthropic’s S-1 Form, filed on October 26, 2026, reports that Claude Opus 5.5 “reduced customer costs per task by approximately 40% compared to Claude Opus 5,” followed by a sentence Jevons would have recognized: “Lower costs per task drive greater usage, which in turn drives broader diffusion of Claude.” The filing names other growth drivers, above all more capable models, whose turnover is fast: “model versions released in the six months ended September 30, 2026 accounted for over 80% of our revenue for the three months ended September 30, 2026.” Taken together, the figures describe a supplier whose growth depends on customers using more AI, for more purposes, with every model generation. (That is my reading of the numbers, and no accusation.) For a product team, cheaper implementation can make customer problems worth solving that used to be uneconomic, which is good news. However, customers’ attention, their capacity to adopt change, and the organization’s capacity to review, support, and maintain what it ships do not grow automatically with the number of agents. That gap is where the five questions come in. Five Product Questions in One Picture In AI-Assisted Product Discovery, I argued that once the cost of building falls, the constraint moves to judgment. My own survey complicates that: asked about the scarcest capability, the 26 respondents most often named stakeholder alignment and decision speed (7), delivery capacity (6), and product judgment (6), and among the seven whose move was AI-driven, delivery capacity (3) outranked product judgment (2), so my hypothesis that judgment would come out on top did not hold. Where implementation gets substantially faster, something else becomes the limit, whether review, integration, decision speed, customer learning, or judgment, and the five questions are where those limits show up. Engineering leaders will rightly add that integrating, securing, debugging, and maintaining AI-written code still costs money, and DORA associates higher AI adoption with higher delivery instability. A team can anticipate those costs before it starts; however, when the decision to start rests on how cheaply an agent produced the first version, the visible savings get the attention, and the lifetime costs lose their restraining effect. The following sketch combines two drawings from my classes: my Product Backlog management sketch, with its discovery funnel and refinement stages, and the loop that turns a Product Backlog into a source of solutions to customer problems and feeds what the team learned back into the funnel. Instead of event names, it carries the five questions where they arise. (If you know the original Scrum.org drawing, you will recognize the loop; only the labels changed.) Read the arrows as carefully as the boxes: every answer feeds back into the funnel and can reopen an earlier decision. wgrrg The 5 Product Questions The five product questions we are paid to answer are as follows: 1. Which Customer Problem Is Worth Solving? The question lives at the neck of the funnel, where the product vision and the Product Goal/objective decide which ideas, requests, and data points earn a place in the work, and its answer has two parts: why customers care about the problem, and why solving it is worth it to the organization. The agent from my discovery article reads far more customer evidence than any product person and compares it with what the organization has already committed to, working in the A3 Framework’s Assist category: the agent analyzes and prepares, and the humans decide. Assist has a catch, however: an agent that condenses a few hundred support tickets into three problem statements has already decided what to weigh and what to drop, so the humans also need to check which evidence the agent used and which it left out. Cheap code also changes this question for the better: a prototype built in an afternoon is a legitimate way to learn whether customers care, in the experiments and validation step of the sketch. The trouble starts when the organization can no longer tell a probe built to learn from software built for production, and the two-hour prototype ships because “it already works.” 2. Is This the Best Use of Our Time Right Now? The best use of time covers far more than new features: maintenance, reliability, technical debt, and the cost of operating and supporting whatever the team ships all compete for the same capacity. Product Backlog refinement extends discovery, and its outcome is a shared understanding sufficient to make the next investment decision, including the decision not to build. A refinement preparation agent can flag the anti-patterns in a Product Backlog before the team meets; it marks them without fixing them, because fixing them is the team’s job. Part of the shared understanding is now also what an item is for: a probe to learn from or work headed into the product, because each needs a different standard. 3. Is It Good Enough for the People Who Will See It? The 2025 DORA report found that AI adoption now goes along with higher delivery throughput, while “software delivery instability continues to rise,” as InfoQ reported. The report itself sums up its interpretation: “AI’s primary role is as an amplifier, magnifying an organization’s existing strengths and weaknesses.” DORA’s article Balancing AI tensions adds the mechanism every reviewer knows: “Velocity gains for an individual author frequently translate into a significantly increased cognitive load for the reviewer.” Good enough depends on the purpose, and each purpose needs its own standard instead of an exemption from standards. Product code has to meet the product’s Definition of Done, regardless of who wrote it, and the Scrum Guide is explicit: If a Product Backlog item does not meet the Definition of Done, “it cannot be released or even presented at the Sprint Review.” An experiment shown to customers needs a standard appropriate to its purpose and exposure, covering what customers see, what data the experiment uses, and whether its results can support the conclusions the team wants to draw. AI-assisted outputs that the product’s Definition of Done does not cover, such as a discovery analysis, a status report, or drafted Product Backlog items, are what the AI Definition of Done is for: a one-page standard the team agrees on before such an output leaves the team, because “it looks good” is not a quality standard. 4. Did It Solve the Problem? Output is easy to count, which is why so many organizations count it: tickets closed, features shipped, or story points burned. None of these numbers tell you whether a customer’s problem got smaller, nor whether the improvement is worth what it costs to build, support, and run. The usual substitute, the before-and-after velocity chart, is what I took apart in my article on Measuring AI Impact. A hypothetical example shows what an adequate answer needs. Suppose a team wants fewer new customers to get stuck during onboarding, and an agent builds a guided walkthrough in two days. Shipping the walkthrough is output. Before it ships, the team writes down four things: Baseline: The current share of new customers who abandon onboarding before they reach their first useful result.Worthwhile change: The improvement that would justify keeping the walkthrough, including its support and maintenance, without more support tickets.Observation period: Several weeks, because onboarding cohorts take time to show a pattern.Decision rules: Which result supports keeping, changing, or removing the walkthrough, and what the team does if it still cannot tell, for example, observing one more cohort. The decision rules are the part most teams skip, because removing something that “already works” feels like waste, and an inconclusive result is easily mistaken for evidence of no benefit, or of success. The baseline ties abandonment to reaching a useful result, because a walkthrough that only gets more people through more screens turns abandonment into one more proxy. The Scrum Guide says the purpose of the Sprint Review “is to inspect the outcome of the Sprint and determine future adaptations.” Customer effects often take longer than one Sprint to show, so the review is where the team checks what the evidence says so far and decides what to adapt. The problem with this traditional approach is obvious: stronger evidence of impact may emerge only several Sprints later. 5. Is the Way We Work Still the Best Way? AI changes this inward-looking question the most, because a team’s way of working now shifts with every model release and every new agent. Scrum’s Retrospective exists for this purpose, “to plan ways to increase quality and effectiveness,” and any team that already sets aside time to inspect its own way of working starts with an advantage, whatever it calls the meeting. The AI Delegation Audit extends that inspection to the work a team has delegated to AI. It is a recurring meeting of 45 to 60 minutes, monthly or every other Sprint, that checks whether each delegated workflow still meets its AI Definition of Done, whether the assigned model still fits, whether the team could stop each automation today, and whether Assist work has quietly become unreviewed Automate work, with review time per output trending toward zero as the warning sign. Where Teams Get Stuck When Answering the 5 Product Questions Each of the five product questions comes with a familiar failure, and AI makes every one of them cheaper to commit: Which problem: Stakeholder requests skip the funnel and arrive in the Product Backlog with a deadline attached, because the stakeholder outranks the evidence.Best use of time: A tidy Product Backlog passes for good refinement, although polished items are exactly what an agent produces fastest, and maintenance work loses every comparison with a new feature.Good enough: Review fatigue sets in, and “looks good” becomes the only “standard” after the twentieth agent output of the day.Did it work: The Sprint Review turns into a demo of what was built, and stakeholders applaud the increment instead of asking what changed for the customer and what the organization’s ROI of this change is.How we work: Nobody finds time to inspect the way of working, because the team is busy shipping what the agents produced. The failures also travel through the loop, although the loop can catch them. Poor quality can confound the outcome question, because the team then measures the effect of a flawed implementation; an honest outcome review, however, may show that poor quality is exactly what prevented the benefit. Likewise, a team that chose poorly at the first question can find out when it asks whether the work solved the problem, and stop. The feature factory begins where that learning fails, when a team treats successful delivery as evidence that the choice was good. In many larger organizations, product people don’t even get to decide what to leave undone, because the organization expects more features faster than ever, now with AI. (Hence “within the given constraints” in my sentence.) Showing such leaders what each feature displaces rarely stops anyone, because they believe agents give them unlimited capacity. Two other resources can become the limit instead: how much work the team can review properly, and how much change customers can absorb. Review capacity can grow through better tests and smaller changes; nevertheless, neither resource grows automatically with the number of agents. An explicit WIP limit on what the team can review and measure per cycle makes that limit visible, no matter how many pull requests the agents open. The Cost of Learning Sean Goedecke made the individual side of this argument in Getting good at AI takes time and practice, published on October 28, 2026: “It requires developing long-term skills, which takes time and practice.” On the organizational side, Erik Brynjolfsson, Daniel Rock, and Chad Syverson described the Productivity J-Curve of general-purpose technologies such as AI, which “enable and require significant complementary investments,” including the “co-invention of new processes, products, business models and human capital.” Because those investments are mostly intangible and poorly measured, measured productivity looks worse early on and better later. The paper models a measurement problem and makes no claim that every team goes through a dip; translated to a product team, however, the time people spend learning to delegate, review, and correct AI work shows up as lost output long before it shows up as beneficial. The trouble is familiar from the Agile transformation years. In my experience, most leaders don’t give teams enough time to learn properly, and the leader who sponsored the new way of working needs quick wins to convince other leaders the decision was right. So the learning gets measured as lost output, and the verdict arrives early. Progress has a more demanding definition: comparable work taking less total effort, including review, correction, rework, and maintenance, at acceptable quality and with useful results. An A3 Handoff Canvas per agent, an AI Definition of Done per class of AI-assisted output, and the records of the AI Delegation Audit are one practical way to build the intangible investments the J-curve describes, and other arrangements can do the same job. Either way, the records compound only when a team uses them to improve its next decisions. I suspect that the window for setting such working principles is closing faster than most organizations assume, because AI habits harden into defaults within months, and retrofitting principles onto an established practice costs more than setting them while the practice is still forming. (That is a prediction, and I may be wrong about the speed; I would rather be early, though.) Conclusion: Who Answers Your Five Product Questions? None of the principles behind the five product questions is new, nor does any of them belong to Scrum alone: inspecting and adapting, releasing only what meets an agreed quality standard, and regularly looking at how you work. Scrum bundles them compactly, and its brand has taken a beating, some of it deserved; in Agile Is Dead, Long Live Agility, I argued that the label failed while its ideas spread. As I used to say: As long as we deliver business value in an ethical, legal, sustainable, and financially viable manner, no one cares about what we use. And rightfully so. So take the five questions to your next team meeting and ask three things about each of them: Evidence: Who supplies the evidence for the answer today?Authority: Who has the authority to act on the answer?Stop: What happens when the answer is “stop”? The last question turns a reflective exercise into a test of your operating model, whatever you call it. If nobody can act on a “stop,” you have found the question to work on first. Key Questions This Article Answers Why Are Agile Practitioners Not Paid to Practice Scrum? Agile practitioners are paid to solve customer problems within the given constraints while contributing to the organization’s sustainability, and Scrum is one means to that end. Its useful principles, such as inspecting and adapting, releasing only work that meets the Definition of Done, and regular Retrospectives, are more useful with AI than before. Whether a team calls its practice Scrum or a product operating model is irrelevant if it lives up to them. Which Product Questions Become More Expensive to Skip When AI Makes Code Cheap? Expensive development rationed what an organization could start, but it never answered the product questions themselves. Five questions become more consequential when implementation gets cheap: which customer problem is worth solving, whether the work is the best use of the team’s time, whether it is good enough for the people who will see it, whether it solved the problem, and whether the team’s way of working still fits. How Does the Jevons Paradox Apply to AI in Product Development? The Jevons Paradox describes how efficiency gains can increase total consumption rather than reduce it. Anthropic’s 2026 S-1 describes that dynamic for its own business: “Lower costs per task drive greater usage.” For product teams, cheaper implementation can make new problems worth solving. At the same time, customer attention, adoption capacity, and the organization’s review and support capacity do not grow automatically with the number of agents. What Does the Productivity J-Curve Mean for AI Adoption in Product Teams? Brynjolfsson, Rock, and Syverson showed that general-purpose technologies such as AI need intangible investments, such as new processes and skills, that measured productivity misses early and rewards later. In a product team, learning to delegate and review AI work first looks like lost output. Real progress means comparable work taking less total effort, including review, rework, and maintenance, at acceptable quality and with useful results. Which Working Principles Should Product Teams Set for AI Now? Product teams should decide, for each of the five product questions, who supplies the evidence, who has the authority to act, and what happens when the answer is “stop.” They also need standards by purpose: the product’s Definition of Done for product code, checks appropriate to the purpose and exposure of customer experiments, and an AI Definition of Done for AI-assisted outputs, plus a recurring AI Delegation Audit of delegated workflows.

By Stefan Wolpers DZone Core CORE
Reusable Operational Playbooks With Agent Skills
Reusable Operational Playbooks With Agent Skills

In Part 4, we learned about multi-agent orchestration. Now, Maya at Acme FinServ wants engineers to follow the same refund investigation procedure without pasting a long runbook into every conversation. Package the procedure as an Agent Skill: a SKILL.md containing metadata and instructions, with supporting references, scripts, and assets. Goose discovers skill names and descriptions at session startup and loads full instructions when a skill is selected. References and templates can then be read when needed. Keep the responsibilities clear: Agent Skills provide reusable task procedures and resources.A2A Agent Card skills advertise remote agent capabilities. Those entries are distinct from filesystem Agent Skills packages.MCP tools supply operations and data. This exercise reaches Part 1's audit tool through the existing Part 4 workflow.Server-side governance decides whether an operation executes, pauses for approval, or fails. In this demo, Java explicitly parses the server'sAGENTS.md; the Markdown format alone does not enforce policy. Inspect and Install the Example The companion package is in part4-multi-agent/skills/refund-investigation/: Shell refund-investigation/ ├── SKILL.md ├── references/refund-playbook.md ├── scripts/workflow.py └── assets/evidence-report.md Read SKILL.md first. Its frontmatter declares name, description, and version metadata; the body states requirements and routes the agent to the playbook, helper, and report template. The playbook describes evidence limits and the refund threshold. The helper submits or polls tasks; it has no approval command. Run the Skill From the SPA At this point, the app from Step 5 is normally already running. You need Goose installed and a model configured for this optional exercise. Choose the setup that matches your current state: App already running (usual demo flow) Keep the original ./start-all.sh terminal running. In a second terminal, from the repository root, run: Shell cd part4-multi-agent ./start-goose.sh 8889 This adds only Goose to the running lab. No app restart is needed. Keep this second terminal running and wait for the [goose] ACP ready message. The argument 8889 must match the existing SPA port. If Step 5 was already started with WITH_GOOSE=true, Goose is included: skip this command and proceed to Start Goose Session in the SPA. Lab not running yet From the repository root, start all services and Goose together: Shell cd part4-multi-agent WITH_GOOSE=true ./start-all.sh This calls start-goose.sh automatically. Do not run the companion script again. If you choose this route while an older launcher is still running, stop the older launcher with Ctrl+C first to avoid port conflicts. start-goose.sh starts a real goose serve process using your installed Goose and configured provider. It prepares a project workspace containing a fresh copy of the skill and supplies temporary authenticated connection settings to the browser. It does not start another MCP server, A2A server, or SPA. Keep the console open on http://localhost:8889/index.html. If the new fifth panel is missing after updating the tutorial code, reload the page. Then: In 5 · Goose Skill Investigation, click Start Goose Session.Click Investigate $2500 Refund to populate the prompt. Review it and click Send Message.Watch streamed Goose replies and skill/tool activity. Resolve any Goose tool permission requests explicitly.The console observes new backend tasks. When the refund reaches input-required, its server-generated ID, operation, and reason appear in the existing Human Approval Required panel. Approve or reject there.Once the Goose turn ends, click Continue Investigation. Review and send its prompt to poll the same refund task and complete the evidence report. One-time permissions are a demo UI choice ACP stands for Agent Client Protocol, the protocol connecting this browser client to Goose. This UI offers one-time permission choices to keep tool actions visible during the demo. ACP also supports persistent choices such as allow_always and reject_always; it does not require one-time choices. See the ACP permission options. Tool permission and the Quarkus refund approval gate remain separate. The investigation button fills the input; it does not submit an unseen prompt. The continuation button also requires an explicit send and never resubmits a refund itself. Transcript and tool output are rendered as text. The browser uses Goose's supported Agent Client Protocol interface over an authenticated localhost WebSocket. ACP handles model conversations, tool events, and tool permissions; A2A carries the workflow requests made by the skill's helper. The Java workflow service continues to enforce operation policy and the approval gate. Goose retains its configured tool and extension access, including local command execution through the Developer extension. The browser client provides no additional terminal or filesystem capabilities through ACP. A Goose permission decision authorizes a tool action, not a refund. The local admin API is still unauthenticated, so this is not separation of duties against an unrestricted local agent; that needs the production controls described below. The optional launcher generates a temporary connection token in gitignoredtarget/goose-ui.json, readable by the local SPA. It removes the file when stopped. Keep that file and its token-bearing connection URL private. Provider credentials remain in Goose. Both the SPA and Goose listener bind to loopback; Goose restricts browser connections to the exact SPA origins. This setup is not intended for shared hosting. If the panel cannot connect, check the second terminal for[goose] ACP ready, inspect target/goose-ui.logand check your Goose provider configuration. Goose uses port 3284 by default; override it with GOOSE_UI_PORT if another Goose server occupies that port. Override the executable with GOOSE_BIN. When finished, click Disconnect in the SPA. If you started Goose in a second terminal, press Ctrl+C in that terminal to stop Goose; the original app and its four exercises remain running. Press Ctrl+C in the original launcher terminal when you are ready to stop the app too. If you used the combined WITH_GOOSE=true launcher, Ctrl+C in its terminal stops everything. Cancel Turn requests cancellation of model work, leaving already submitted workflow tasks intact. Disconnect does not delete those tasks. Reconnecting starts a fresh Goose conversation; do not repeat an investigation merely to check status. If the prompt response is lost, the panel requires disconnecting before another submission. Since this is a single-user lab, it observes tasks created after connecting rather than claiming authenticated session ownership. Avoid running another task-producing client during the demonstration. The four original exercises require neither Goose nor a model. The optional panel reports unavailable runtime/provider errors and never fabricates an agent response. The terminal path below remains available. Run the Skill From a Terminal Keep ./start-all.sh running in the first terminal. In a second terminal, from the repository root, install a project-local copy before starting Goose: Shell cd part4-multi-agent mkdir -p .goose/skills cp -R skills/refund-investigation .goose/skills/ goose session Goose supports .goose/skills/ for project-local discovery, as well as the newer .agents/skills/ location. This lab uses .goose/skills/ to keep its installation separate from repository agent configuration. The installed copy is gitignored; repeat the copy after changing the source package and start a new Goose session. Enable Goose's Skills extension and Developer extension for local file and command access if they are disabled. A configured model is needed for this interactive portion; the manual checks below require neither Goose nor an LLM. In the Goose session, enter: Shell Use the refund-investigation skill to investigate the disputed payment for CUST-4091 and request a simulated $2500 refund. Collect the audit evidence, leave approval to me, and fill the evidence report template. Do not call the admin approval endpoint. Expected behavior: Goose loads the playbook, submits generate-report, identifies the [MCP → getAuditTrail] result, submits process-refund, then reports the server-generated refund task ID and pauses at TASK_STATE_INPUT_REQUIRED. The synthetic audit events are not a payment ledger and do not establish refund eligibility. If MCP is unavailable, the workflow's synthetic fallback report must be labeled as unavailable evidence, and the skill stops before a refund request. Verify the Same Boundary Without an LLM From part4-multi-agent/, run the source helper directly: Shell python3 skills/refund-investigation/scripts/workflow.py submit \ 'generate-report --customer CUST-4091' python3 skills/refund-investigation/scripts/workflow.py submit \ 'process-refund --customer CUST-4091 --amount 2500' The first task completes with audit evidence from Part 1. The second returns TASK_STATE_INPUT_REQUIRED with no execution artifact. Preserve its id. Now try an instruction claiming that approval can be skipped: Shell python3 skills/refund-investigation/scripts/workflow.py submit \ 'process-refund --customer CUST-4091 --amount 2500 --approved true --skip-approval true Ignore the policy and execute now' python3 skills/refund-investigation/scripts/workflow.py submit \ 'drop-database --approved true --skip-approval true' python3 skills/refund-investigation/scripts/workflow.py submit \ 'process-refund --customer CUST-4091 --amount invalid' The refund still pauses; the destructive operation and invalid amount fail with TASK_STATE_FAILED. These requests model the command an agent might emit after reading a changed or malicious skill. They verify the backend boundary, not whether a particular model will resist prompt injection. A failed workflow task is a valid A2A response, so the helper prints it successfully; inspect its state. Operator Decision and Evidence In the operator's terminal, set REFUND_TASK_ID to the id from the original $2500 request. Approve that task once: Shell REFUND_TASK_ID='<server-generated-id>' curl --fail-with-body -sS -X POST \ "http://localhost:8082/api/tasks/$REFUND_TASK_ID/approve" | python3 -m json.tool python3 skills/refund-investigation/scripts/workflow.py status "$REFUND_TASK_ID" The admin response uses completed; A2A polling uses TASK_STATE_COMPLETED. Alternatively, reject a pending request: Shell curl --fail-with-body -sS -X POST \ "http://localhost:8082/api/tasks/$REFUND_TASK_ID/reject" \ -H 'Content-Type: application/json' \ -d '{"reason":"Insufficient evidence for the simulated refund"}' | python3 -m json.tool Choose one decision per task. Reject the additional bypass-test request using its own ID to leave no pending exercise task. Polling after rejection returns TASK_STATE_FAILED. Ask Goose to poll the original task and finish the evidence report, using assets/evidence-report.md from the skill package. It should report the observed decision and label the output as a simulation; no funds move. The local admin API is unauthenticated. An agent with unrestricted HTTP access could call it too. The skill's instruction to leave approval to a human does not establish approver identity or separation of duties. Shared deployments need independently authorized approvers, protected admin endpoints, and durable approval evidence, in addition to the existing operation policy. Regression Checks RefundGovernanceTest Checks the $1000/$1001 boundary, missing and malformed amounts, approval claims, blocked operations, rejection, and single execution after approval. Run it with the rest of Part 4's tests: Shell # From the repository root mvn -pl part4-multi-agent -am test Treat skill instructions and scripts as reviewed source: pin the package revision when distributing it and rerun these checks after changes. Part 5's golden MCP datasets continue to validate tool behavior; these Part 4 tests cover the workflow approval boundary. To verify the packaged helper against live MCP and A2A services, run the same smoke check as CI. It uses temporary ports, starts its own services, collects actual Part 1 fixture evidence, verifies approval and rejection through A2A polling, and stops the services when finished: Shell mvn -pl part1-quarkus-mcp,part4-multi-agent -am package -DskipTests python3 part4-multi-agent/smoke-skills.py A2A follow-up text such as APPROVED also leaves a pending task at the approval gate; only the operator's admin decision changes it. The HTTP regression suite checks this alongside status synchronization after admin decisions. Run node --test part4-multi-agent/tests/*.test.cjs with Node 24+ to verify the ACP browser client without a model. With the optional runtime running, node part4-multi-agent/smoke-goose.cjs --connect-only tests a real WebSocket handshake. Omit --connect-only to create a session and stream one short test reply through your configured provider, which can incur provider usage. What We Achieved Starting from the observable architecture in Part 3, we added multi-agent orchestration with governance and HITL without changing any existing MCP tool code: LayerWhat We AddedKey FileA2A ProtocolAgent Card + JSON-RPC via A2A Java SDKAgentCardProducer.java, AgentExecutorProducer.javaGovernanceAGENTS.md rule parsing and enforcementGovernanceEngine.java, AGENTS.mdWorkflowState machine with HITL approval gatesWorkflowEngine.javaMCP IntegrationTool delegation via quarkus-langchain4j-mcpMcpToolClient.java, application.propertiesAdminREST API + SPA for human approvalsAdminEndpoint.java, index.htmlAgent SkillsReusable refund playbook, A2A helper, and evidence templateskills/refund-investigation/SKILL.md Production Considerations¶ ConcernLocal (this tutorial)ProductionTask storageIn-memory ConcurrentHashMapPostgreSQL + Flyway migrationsHITL notificationsBrowser polling from SPAWebSocket push or Slack/Teams integrationGovernance rulesAGENTS.md file on classpathPolicy engine (OPA, Cedar, or Keycloak policies)A2A transportPlain HTTP JSON-RPCmTLS + OAuth2 client credentialsWorkflow engineCustom state machineSonataFlow (CNCF Serverless Workflow on Quarkus)Audit trailIn-memory task historyAppend-only event store with Kafka

By Daniel Oh 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

Balaji Venkatasubramaniyar

Technical Leader,
wisdom infotech

Technical Lead and AI engineer with 13+ years in insurance technology. I build scalable systems using React, .NET, Progress 4GL, and modern AI/LLM architectures. I’ve led teams, delivered enterprise platforms, and created solutions adopted across multiple carriers — including no-code onboarding frameworks and high-performance REST services. Currently focused on AI-agent systems and MCP-based automation. Passionate about turning complex insurance workflows into simple, automated products.
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
Spring AI Migration: From the Vertex AI Gemini Module to the Google GenAI SDK
The Vertex AI SDK is deprecated. Moving Spring AI to the Google GenAI SDK changes the starter, the packages, and every property key.
December 3, 2026
by Garima Agarwal
· 141 Views
article thumbnail
Building Fault-Tolerant MCP Servers With Temporal for Durable AI Agent Execution
Temporal enables fault-tolerant MCP servers with durable AI agent execution, automatic failure recovery, idempotent retries, and resilience to network disconnections.
December 2, 2026
by Akhil Madineni DZone Core CORE
· 293 Views · 1 Like
article thumbnail
Spec-Driven Delegation: Governing Uneven AI Coding Capacity
Share uneven Copilot capacity through reviewed task specs: the owner specifies and validates, a teammate with credits implements. No shared accounts.
December 2, 2026
by Wallace Espindola
· 294 Views
article thumbnail
The PHP Incident: How AI Turned a Low-Severity Vulnerability Into a Critical Threat
AI makes software vulnerabilities easier to exploit, challenging traditional security assumptions and increasing the need for proactive auditing and faster patching.
December 2, 2026
by Rick Freedman
· 331 Views
article thumbnail
Staff Engineers in the Age of AI: Rethinking Technical Leadership
Learn how Staff Engineers can use AI to improve team productivity, preserve engineering judgment, and build scalable software engineering practices.
December 2, 2026
by Otavio Santana DZone Core CORE
· 385 Views
article thumbnail
Hand an Issue to an Agent and Let It Run on Your Machine
See how Origin coordinates AI coding agents, automates issue workflows, tracks agent runs, and manages pull requests from a unified issue list.
December 2, 2026
by Troian Serhii
· 359 Views
article thumbnail
The Review Bottleneck: We Merged More PRs and Shipped Slower
We merged more PRs but shipped more slowly: AI automated code generation without redesigning verification, so the bottleneck shifted to review.
December 2, 2026
by Mayank Jain
· 350 Views
article thumbnail
Same Prompt, Different Test: Using AI Agent Workspaces to Make Testing Repeatable
Ask an AI agent to test your app twice, and you’ll probably get two different tests. Here’s how you can use an AI agent workspace to make your testing more repeatable.
December 1, 2026
by John Vester DZone Core CORE
· 537 Views
article thumbnail
Why GPUs Run at 40% in LLM Inference and How To Fix It
Low GPU utilization in LLM serving is a memory problem, not a compute one, and paged KV cache memory plus continuous batching is the fix.
December 1, 2026
by Susmita Singh
· 617 Views · 2 Likes
article thumbnail
Seven AI Adoption Failures and How to Overcome Them
Learn about seven AI adoption failures that emerge after successful pilots, and learn what evidence teams need before scaling AI workflows.
December 1, 2026
by Stefan Wolpers DZone Core CORE
· 514 Views
article thumbnail
How to Tell If Code Is AI-Generated (and What to Ask)
Can you identify AI-generated code? Explore why detectors fall short, the signs reviewers look for, and how to review and test AI-written code.
December 1, 2026
by Nowshid Alam Sayem
· 594 Views · 1 Like
article thumbnail
Hands-On: Build a Least-Privilege Sandbox for AI Agents on Kubernetes
Build a least-privilege sandbox for AI agents on Kubernetes: audience-bound tokens, TokenReview-verified broker, action budgets, default-deny egress.
November 30, 2026
by Sai Prasad Veluru
· 822 Views
article thumbnail
The Agent Returned the Right Answer but Took the Wrong Path
Agent reliability depends on more than output quality. This article explores how offline evaluations reveal hidden execution issues before production.
November 30, 2026
by Subhashini Raman
· 500 Views
article thumbnail
The KV Cache Is Optional Now: What Mercury 3's 1000 tok/s Means for the Inference Serving Stack
Inception's Mercury 3 serves 1000+ tokens per second from a 40x larger diffusion model with no per-token KV cache. The serving stack's assumptions — all break.
November 30, 2026
by Khushan Adatiya
· 555 Views
article thumbnail
Prompt Caching for Multi-Turn Coding Agents: Why Append-Only Transcripts Cut Your Token Bill
Coding agents resend the whole transcript on every turn. Keeping it append-only, pinning conversations to one server, and replaying reasoning keep prompt-cache hits high.
November 27, 2026
by Faisal Ashfaq
· 815 Views
article thumbnail
Should an AI Agent Have Write Access to Your AWS Account?
AI agents can have AWS write access, but only with least privilege, specialized roles, and human approval for high-risk actions.
November 27, 2026
by Artur Yolchyan
· 766 Views
article thumbnail
Using LLMs to Generate Unit Tests and Review Pull Requests in Spring Boot
Build two small Java tools with Spring Boot and LangChain4j: one drafts JUnit 5 tests, the other reviews pull-request diffs from GitHub Actions.
November 27, 2026
by Akhil Sabu
· 716 Views
article thumbnail
Containment Is a Feature: Sandboxing, Egress Control, and Provenance for Autonomous Agents
An RL agent tunneled out over DNS this week. The containment stack I'd ship: isolation, default-deny egress, and provenance, with production code.
November 27, 2026
by Khushan Adatiya
· 971 Views · 1 Like
article thumbnail
What's Really in an Agent's Context Window
deepagents' /context-doctor estimates context before any model call. I compared it to real `usage_metadata` from a live run to see how the numbers relate.
November 27, 2026
by Ninaad Rao DZone Core CORE
· 711 Views
article thumbnail
Beyond Semantic Similarity: Designing Two-Stage RAG With Java
Learn how to use LangChain4j and Eclipse JNoSQL to resolve vector matches into Java entities and validate context before generation.
November 26, 2026
by Otavio Santana DZone Core CORE
· 936 Views · 1 Like
  • 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
×