Recent Posts
Archives

Posts Tagged ‘ToolCalling’

PostHeaderIcon [VoxxedDaysBucharest2026] Breaching LLM-Powered Applications: Brian Vermeer on Security and Privacy Challenges in AI Systems

Lecturer

Brian Vermeer is a Staff Developer Advocate at Snyk, where he focuses on developer security, DevSecOps practices, and emerging risks in modern application architectures. A recognized Java Champion and active community leader who co-leads the Netherlands Java User Group (NLJUG), Brian brings extensive experience in application security, secure coding, and helping organizations build more resilient systems. He frequently speaks at international conferences on topics ranging from traditional web vulnerabilities to the novel attack surfaces introduced by artificial intelligence and large language models.

Abstract

As organizations rapidly integrate Large Language Models into production applications, new categories of security and privacy vulnerabilities emerge alongside familiar web application risks. Brian Vermeer provides a compelling, demonstration-heavy exploration of these challenges through a fictional car rental application called “Really Good Rentals.” He demonstrates practical attack vectors such as prompt injection, RAG poisoning, memory manipulation, and tool abuse, while outlining layered mitigation strategies including input/output guardrails, scoped permissions, human-in-the-loop verification, and architectural defenses essential for building trustworthy LLM-powered systems.

The Allure and Inherent Risks of LLMs in Production Applications

Brian begins by drawing a relatable analogy: just as children enthusiastically misuse new toys in unexpected ways, developers often rush to incorporate powerful new technologies like LLMs without fully appreciating the expanded attack surface they create. While LLMs offer remarkable capabilities for natural language processing, code generation, and intelligent automation, they introduce significant risks when granted access to tools, user data, or execution privileges.

He presents a simplified architecture of a typical LLM-powered application, highlighting key components: user prompts, system instructions, conversation memory, retrieval-augmented generation (RAG) pipelines, and tool-calling mechanisms. Because LLMs are fundamentally stateless, the surrounding application bears responsibility for maintaining context, which creates multiple points where malicious actors can influence behavior through carefully crafted inputs.

Context Poisoning Through RAG and Memory Manipulation

A central demonstration revolves around the “Really Good Rentals” application. Brian shows how a seemingly innocuous file upload feature with inadequate path validation allows attackers to perform directory traversal and overwrite critical documents stored in the vector database, such as terms-of-service files. By injecting a modified cancellation policy containing trigger phrases like “vroom vroom,” the attacker can later invoke this policy through normal chat interactions, tricking the LLM into granting unauthorized credits or violating business rules.

This technique, termed RAG poisoning, illustrates how tainted retrieval sources can persistently influence model behavior across conversations. Similar vulnerabilities arise through traditional injection attacks in search functionality, where SQL injection not only extracts data but also poisons the conversation memory fed to the LLM on subsequent interactions. Brian emphasizes that classic web vulnerabilities gain dramatically amplified impact when they shape the context provided to powerful generative models.

Abusing Permissions, Tool Calling, and Advanced Prompt Injection

Brian demonstrates how overly broad tool permissions create dangerous scenarios. In older models like GPT-3.5, carefully crafted prompts could coerce the LLM into executing arbitrary SQL statements with destructive consequences. Even with more recent, safety-aligned models, insufficient scoping of available tools allows privilege escalation and unauthorized actions.

Advanced prompt injection techniques go beyond simple overrides. Multi-turn attacks gradually extract personally identifiable information by leveraging accumulated conversation memory. When combined with tool calling capabilities, especially with locally hosted models, attackers can trigger hallucinations that inadvertently expose sensitive data during operations such as account creation or data processing.

The presentation underscores that granting LLMs access to powerful tools without rigorous permission boundaries and validation is equivalent to giving untrusted code broad system access.

Mitigation Strategies and Architectural Defenses

Brian outlines a comprehensive defense-in-depth approach spanning multiple layers:

  • Input and Output Guardrails: Deploying dedicated LLM-as-a-Judge mechanisms that evaluate both incoming prompts and generated outputs for malicious content, policy violations, or harmful instructions. These guardrails act as critical safety nets.

  • Limited-Scope and Permission-Aware Tools: Designing tools with granular permissions, explicit user confirmation flows for sensitive operations, and runtime validation of actions against the authenticated user’s privileges.

  • Structured Outputs and Schema Enforcement: Using techniques that force models to produce responses conforming to predefined schemas, significantly reducing the potential for unexpected or harmful outputs.

  • Model Selection and Routing: Strategically routing sensitive operations to private, self-hosted models while reserving more powerful commercial models for less critical tasks.

  • Traditional Security Foundations: Maintaining rigorous input sanitization, dependency updates, secure file handling, and regular security scanning. Brian stresses that foundational web application security remains non-negotiable even in AI-enhanced systems.

Additional considerations include implementing rate limiting to prevent “denial of pocket money” attacks that exhaust token quotas through malicious prompting, as well as comprehensive auditing of all tool invocations and model interactions.

Broader Implications for Secure AI Development

The talk concludes with forward-looking guidance for organizations adopting LLM technologies. Brian encourages treating LLMs as powerful but inherently unpredictable components requiring the same rigorous engineering discipline applied to any critical system. Key principles include careful context management, strict permission boundaries, deterministic fallback mechanisms where possible, and continuous security education for development teams.

By sharing concrete attack demonstrations and corresponding defenses, Brian equips attendees with actionable insights to build more secure, privacy-preserving AI applications while continuing to harness their transformative potential.

Links:

PostHeaderIcon [PyDataGlobal2025] The Boringly Simple Loop Powering Generative AI Applications

Lecturer

Sebastian Wallkötter is an AI builder and open-source maintainer. He holds a doctorate in social robotics and computer science from Uppsala University and maintains the widely used image-processing library Image.io, which records tens of millions of monthly downloads. After working as a product manager for a data platform at a Scandinavian media company he relocated to Boston; his current focus is the architectural patterns that underlie contemporary generative-AI systems.

Abstract

Beneath the proliferation of generative-AI frameworks lies a single, almost trivial control structure: a nested pair of while loops. The outer “turn” loop accumulates conversation history; the inner “trace” loop repeatedly invokes a language model until it ceases to request tools. This article dissects that core loop, shows how its presence or absence yields completions, chat assistants, agents, and co-pilots, and then examines the complementary discipline of context engineering—the principled management of the information that enters the model’s window. Together these two ideas supply a first-principles map that allows practitioners to construct sophisticated systems without mandatory dependence on any particular framework.

The Core Loop and Its Four Constituents

Every language-model call is defined by four elements: the chosen model, a system prompt that supplies instructions, a history of prior messages, and a list of available tools. History itself is an ordered sequence of typed messages—user, thinking, tool-call, tool-result, and assistant—whose legal transitions are strictly constrained. A user message is followed by an assistant message (or by intermediate thinking and tool activity); tool calls are answered by tool results; the entire block may repeat.

When these constituents are assembled into application logic the resulting control flow is remarkably simple. After initial setup the program waits for a user message (the turn loop). Upon receipt it enters an inner loop that repeatedly calls the model, executes any requested tools, appends the tool results to history, and continues until the model finally emits an assistant message (the trace loop). That assistant message is returned to the user, history is retained, and the outer loop resumes. The pattern is deliberately boring; its power derives from the fact that nearly every generative application is a variation on these two loops.

Taxonomy of Applications Derived from the Loop

Absence of both loops yields ordinary completions—single-shot tasks such as sentiment classification or automated replies. Presence of the turn loop alone produces a chat assistant capable of multi-turn conversation but unable to act on the external world. Presence of the trace loop alone produces a classical agent that can call tools yet does not accumulate conversational history across independent invocations. Presence of both loops yields what may be termed a co-pilot: an interactive assistant that both converses and acts, typical of coding agents and desktop assistants.

Because completions and pure agents possess clear start and end points they can themselves be wrapped as tools. An agent that calls other agents as tools is the elementary building block of multi-agent systems. Two dominant organizational patterns emerge. Workflows simply daisy-chain agents; a supervisor agent treats subordinate agents as ordinary tools and remains unaware of their internal structure. Reflection (an actor-critic arrangement) improves output quality by iteratively critiquing and revising intermediate results. All of these configurations remain intelligible once the underlying turn and trace loops are understood.

Context Engineering: Programming the Window

Context engineering is the disciplined practice of deciding what information enters the model’s context window so that the system remains reliable without unnecessary cost. Language models care primarily about the immediate next action—which tool to invoke or which assistant message to emit. Any material that does not contribute to that decision is surplus.

A practical system prompt therefore contains two principal sections: an ordered list of instructions and a compact knowledge base organized by descriptive headings. Tools are supplied separately, commonly via the Model Context Protocol. Contrary to frequent advice against “mega-prompts,” contemporary models tolerate surprisingly large static contexts; a window of one to two hundred thousand tokens is roughly the length of a short novel and is often sufficient for an entire application. Premature fragmentation should therefore be resisted until empirical evidence of degradation appears.

When static prompts eventually become untenable, four failure modes—collectively the “deadly sins”—signal the need for lazy loading. Context overload occurs when a long trace of prior tool calls teaches the model to repeat the same action indefinitely. Context poisoning arises when the window contains stale or incomplete information about the external world. Useless data appears when instructions or tools irrelevant to the current task remain visible and are erroneously followed. Inconsistency arises when contradictory facts coexist and occasionally trigger erratic behavior. Each of these pathologies is silent; the model simply begins to fail without raising an exception.

Lazy loading restores reliability by injecting material only at the moments it becomes necessary: at agent initialization for known constants, after the user message for information deducible from the request, and during tool execution for previously unknown dependencies. Retrieval-augmented generation, skills, sub-agents, and memory are simply named strategies for performing that lazy loading—of knowledge, of instructions, of tools, and of personalization data, respectively.

Implications for Design and Standardization

Understanding the core loop and the principles of context engineering liberates practitioners from framework lock-in. Systems can be constructed directly against model APIs, instrumented with ordinary logging, and evolved by the gradual introduction of retrieval, skills, or multi-agent coordination only when required. Standardization efforts such as the Model Context Protocol are valuable insofar as they lower the cost of experimentation, yet the field remains young; excessive early standardization risks freezing patterns that have not yet been fully explored. The most robust path is therefore to master the simple loop, manage context with deliberate frugality, and introduce complexity only when measurement demonstrates its necessity.

Links:

PostHeaderIcon [VoxxedDaysAmsterdam2026] Building AI Agents on the JVM: A Practical Exploration with Koog in Kotlin

Lecturer
Anton Arhipov is a Developer Advocate at JetBrains, where he engages with developers and shares insights on Kotlin, IntelliJ IDEA, and related technologies. He frequently speaks at conferences and contributes to JetBrains initiatives around AI tooling and agent frameworks.

Abstract
Anton Arhipov’s session at Voxxed Days Amsterdam 2026 introduces the construction of AI agents directly on the JVM using Koog, a lightweight Kotlin-native framework developed at JetBrains. Rather than relying on Python-based solutions, the talk demonstrates building tool-using LLM agents in Kotlin, emphasizing seamless integration with existing JVM products and domain models. Through live coding and detailed examination of core concepts—including communication with language models, tool registration, interaction loops, and the distinctive graph-based strategy DSL—participants gain insight into creating robust, reproducible agent workflows. The presentation culminates in a coding agent example that generates, compiles, and tests small programs, highlighting both opportunities and challenges when working with local and remote LLMs.

Why Build AI Agents on the JVM? Context and Motivations

The emergence of large language models has spurred interest in autonomous AI agents capable of tool use and iterative reasoning. While Python has historically dominated this space, Anton argues that language choice should serve the embedding context. For JVM-based products such as IntelliJ IDEA, TeamCity, or YouTrack, implementing agents in Python introduces significant overhead: external process management, serialization costs, and duplication of domain models. A native JVM solution reuses existing infrastructure, types, and libraries, improving efficiency and maintainability.

Koog originated from internal JetBrains efforts to embed agents into their tools. The framework’s tech lead documented the transition from Python to Kotlin, sparking discussions around perceived “skill issues” versus genuine architectural advantages. Anton stresses that the decision prioritizes integration over language fashion.

Fundamentals of Agent Architecture and the Interaction Loop

At a high level, an AI agent comprises an environment, a strategy (or “brain”), model providers, and user interaction. The workflow begins with a user request. The agent forwards a prompt to an LLM via a prompt executor (supporting OpenAI, Google, Ollama, and others). The model may respond with:

  • An assistant message (plain text, terminating the loop), or
  • A tool call, prompting the agent to invoke registered tools, feed results back to the LLM, and iterate until an assistant message appears.

This forms the agentic loop. Koog models agents as simple classes with a tools registry, configurable strategy, prompt, model selection, iteration limits, and a prompt executor. Predefined models and capability checks (e.g., tool calling support) simplify setup.

Anton demonstrates a basic happy-path agent that writes a Kotlin program (initially a “Hello World,” later a Snake game using Java Swing). Early iterations reveal the need for tools: file system operations, shell execution via Gradle, and careful prompting to enforce compilation and verification steps. Live runs expose humorous LLM behaviors, such as generating wrapper files or hallucinating results, underscoring the importance of robust system prompts, validation, and verification.

Tool Integration, Local Models, and Observed Challenges

Tools in Koog can be registered via a registry or supplied as annotated functions with descriptions for better LLM guidance. The session explores interactions with local models (e.g., small Mistral variants via Ollama) versus remote APIs. Local models offer speed and privacy but exhibit unreliability in tool calling—hallucinating results, ignoring descriptions, or fabricating outputs when tool results appear implausible (such as unrealistic temperature values in Kelvin).

Examples illustrate how insufficient tool descriptors or conflicting instructions lead to unexpected behavior. Anton shows cases where models call tools multiple times, reject their own outputs, or produce inconsistent results across runs, even with identical prompts. These observations highlight that reliable tool calling remains critical for effective agents and often requires significant prompt engineering and workflow safeguards.

The Strategy DSL: Graph-Based Control for Determinism and Reproducibility

A standout feature of Koog is its strategy DSL, which models agent behavior as a reproducible graph rather than a purely LLM-driven loop. The default strategy handles basic LLM calls and tool invocation, but custom strategies allow sophisticated workflows.

Nodes represent actions (e.g., calling the LLM, processing tool results), while edges use predicates or conditions (e.g., “if tool call, proceed to execution node”). Graphs support sequencing, branching, and chaining multiple strategies—such as enforcing a planning stage before implementation and verification. Type safety in Kotlin ensures nodes and edges compose correctly, with the compiler assisting in workflow construction.

Anton walks through building a simple parsing-and-increment graph, then extends the concept to more realistic scenarios involving structured outputs for plans. By validating plans against domain models and potentially generating dynamic sub-strategies, developers introduce determinism into otherwise stochastic LLM processes. Structured outputs improve reliability when deserializing LLM responses into typed objects like plan items.

This graph approach distinguishes Koog from many other frameworks, enabling complex, auditable, and testable agent logic while leveraging Kotlin’s strengths.

Live Coding a Coding Agent and Practical Takeaways

The session features extensive live exploration, including attempts to generate a Snake game with requirements for Gradle, specific versions, compilation verification, and no mistakes. Successes and failures illustrate real-world agentic challenges: hallucinated tool calls, skipped verification steps, and the need for precise instructions. Anton shares that even with “make no mistakes” in the prompt, outcomes vary across models and runs.

The talk concludes with a repository of examples and reiterates Koog’s multi-platform nature, adapter support for various model providers, and the power of the strategy DSL. While 45 minutes cannot cover advanced topics, the presentation equips attendees with foundational knowledge to experiment with building JVM-native agents.

Code Sample: Basic Agent Setup in Koog (Kotlin)

val executor = OpenAI.promptExecutor { /* config */ }
val agent = Agent {
    promptExecutor = executor
    systemPrompt = "You are a helpful Kotlin developer..."
    model = OpenAIModels.GPT_4O
    tools = toolRegistry { 
        include(FileSystemProvider())
        include(ShellExecutor())
    }
}

agent.run("Write a Kotlin program to print Hello World")

Code Sample: Simple Strategy Graph

val strategy = strategy<String, Int> {
    start forwardingTo parseNode forwardingTo incrementNode
}

val parseNode = node { input: String -> input.toInt() }
val incrementNode = node { input: Int -> input + 1 }

These examples capture the framework’s emphasis on readability and type-safe composition.

In summary, Anton Arhipov provides a grounded, pragmatic overview of constructing AI agents on the JVM. Koog enables developers to harness LLM capabilities within familiar Kotlin and JVM ecosystems, with the strategy DSL offering a powerful mechanism for controlling complexity. While challenges with model reliability persist—especially locally—the framework’s design promotes integration, reproducibility, and incremental improvement of agentic systems.

Links:

PostHeaderIcon [VoxxedDaysBucharest2026] Breaching LLM-Powered Applications: Brian Vermeer on Security and Privacy Challenges in AI Systems

Lecturer

Brian Vermeer is a Staff Developer Advocate at Snyk, where he focuses on developer security, DevSecOps practices, and emerging risks in modern application architectures. A recognized Java Champion and active community leader who co-leads the Netherlands Java User Group (NLJUG), Brian brings extensive experience in application security, secure coding, and helping organizations build more resilient systems. He frequently speaks at international conferences on topics ranging from traditional web vulnerabilities to the novel attack surfaces introduced by artificial intelligence and large language models.

Abstract

As organizations rapidly integrate Large Language Models into production applications, new categories of security and privacy vulnerabilities emerge alongside familiar web application risks. Brian Vermeer provides a compelling, demonstration-heavy exploration of these challenges through a fictional car rental application called “Really Good Rentals.” He demonstrates practical attack vectors such as prompt injection, RAG poisoning, memory manipulation, and tool abuse, while outlining layered mitigation strategies including input/output guardrails, scoped permissions, human-in-the-loop verification, and architectural defenses essential for building trustworthy LLM-powered systems.

The Allure and Inherent Risks of LLMs in Production Applications

Brian begins by drawing a relatable analogy: just as children enthusiastically misuse new toys in unexpected ways, developers often rush to incorporate powerful new technologies like LLMs without fully appreciating the expanded attack surface they create. While LLMs offer remarkable capabilities for natural language processing, code generation, and intelligent automation, they introduce significant risks when granted access to tools, user data, or execution privileges.

He presents a simplified architecture of a typical LLM-powered application, highlighting key components: user prompts, system instructions, conversation memory, retrieval-augmented generation (RAG) pipelines, and tool-calling mechanisms. Because LLMs are fundamentally stateless, the surrounding application bears responsibility for maintaining context, which creates multiple points where malicious actors can influence behavior through carefully crafted inputs.

Context Poisoning Through RAG and Memory Manipulation

A central demonstration revolves around the “Really Good Rentals” application. Brian shows how a seemingly innocuous file upload feature with inadequate path validation allows attackers to perform directory traversal and overwrite critical documents stored in the vector database, such as terms-of-service files. By injecting a modified cancellation policy containing trigger phrases like “vroom vroom,” the attacker can later invoke this policy through normal chat interactions, tricking the LLM into granting unauthorized credits or violating business rules.

This technique, termed RAG poisoning, illustrates how tainted retrieval sources can persistently influence model behavior across conversations. Similar vulnerabilities arise through traditional injection attacks in search functionality, where SQL injection not only extracts data but also poisons the conversation memory fed to the LLM on subsequent interactions. Brian emphasizes that classic web vulnerabilities gain dramatically amplified impact when they shape the context provided to powerful generative models.

Abusing Permissions, Tool Calling, and Advanced Prompt Injection

Brian demonstrates how overly broad tool permissions create dangerous scenarios. In older models like GPT-3.5, carefully crafted prompts could coerce the LLM into executing arbitrary SQL statements with destructive consequences. Even with more recent, safety-aligned models, insufficient scoping of available tools allows privilege escalation and unauthorized actions.

Advanced prompt injection techniques go beyond simple overrides. Multi-turn attacks gradually extract personally identifiable information by leveraging accumulated conversation memory. When combined with tool calling capabilities, especially with locally hosted models, attackers can trigger hallucinations that inadvertently expose sensitive data during operations such as account creation or data processing.

The presentation underscores that granting LLMs access to powerful tools without rigorous permission boundaries and validation is equivalent to giving untrusted code broad system access.

Mitigation Strategies and Architectural Defenses

Brian outlines a comprehensive defense-in-depth approach spanning multiple layers:

  • Input and Output Guardrails: Deploying dedicated LLM-as-a-Judge mechanisms that evaluate both incoming prompts and generated outputs for malicious content, policy violations, or harmful instructions. These guardrails act as critical safety nets.

  • Limited-Scope and Permission-Aware Tools: Designing tools with granular permissions, explicit user confirmation flows for sensitive operations, and runtime validation of actions against the authenticated user’s privileges.

  • Structured Outputs and Schema Enforcement: Using techniques that force models to produce responses conforming to predefined schemas, significantly reducing the potential for unexpected or harmful outputs.

  • Model Selection and Routing: Strategically routing sensitive operations to private, self-hosted models while reserving more powerful commercial models for less critical tasks.

  • Traditional Security Foundations: Maintaining rigorous input sanitization, dependency updates, secure file handling, and regular security scanning. Brian stresses that foundational web application security remains non-negotiable even in AI-enhanced systems.

Additional considerations include implementing rate limiting to prevent “denial of pocket money” attacks that exhaust token quotas through malicious prompting, as well as comprehensive auditing of all tool invocations and model interactions.

Broader Implications for Secure AI Development

The talk concludes with forward-looking guidance for organizations adopting LLM technologies. Brian encourages treating LLMs as powerful but inherently unpredictable components requiring the same rigorous engineering discipline applied to any critical system. Key principles include careful context management, strict permission boundaries, deterministic fallback mechanisms where possible, and continuous security education for development teams.

By sharing concrete attack demonstrations and corresponding defenses, Brian equips attendees with actionable insights to build more secure, privacy-preserving AI applications while continuing to harness their transformative potential.

Links:

PostHeaderIcon [SpringIO2025] Real-World AI Patterns with Spring AI and Vaadin by Marcus Hellberg / Thomas Vitale

Lecturer

Marcus Hellberg is the Vice President of AI Research at Vaadin, a company specializing in tools for Java developers to build web applications. As a Java Champion with nearly 20 years of experience in Java and web development, he focuses on integrating AI capabilities into Java ecosystems. Thomas Vitale is a software engineer at Systematic, a Danish software company, with expertise in cloud-native solutions, Java, and AI. He is the author of “Cloud Native Spring in Action” and an upcoming book on developer experience on Kubernetes, and serves as a CNCF Ambassador.

Abstract

This article examines practical patterns for incorporating artificial intelligence into Java applications using Spring AI and Vaadin, transitioning from experimental to production-ready implementations. It analyzes techniques for memory management, guardrails, multimodality, retrieval-augmented generation, tool calling, and agents, with implications for security, user experience, and system integration. Insights emphasize robust, observable AI workflows in on-premises or cloud environments.

Memory Management and Streaming in AI Interactions

Integrating large language models (LLMs) into applications requires addressing their stateless nature, where each interaction lacks inherent context from prior exchanges. Spring AI provides advisors—interceptor-like mechanisms—to augment prompts with conversation history, enabling short-term memory. For instance, a MessageChatMemoryAdvisor retains the last N messages, ensuring continuity without manual tracking.

This pattern enhances user interactions in chat-based interfaces, built here with Vaadin’s component model for server-side Java UIs. A vertical layout hosts message lists and inputs, injecting a ChatClientBuilder to construct clients with advisors. Basic interactions involve prompting the model and appending responses, but for realism, streaming via reactive fluxes improves responsiveness, subscribing to token streams and updating UI progressively.

Code illustration:

ChatClient chatClient = builder.build();
messageInput.addSubmitListener(submitEvent -> {
    String message = submitEvent.getMessage();
    MessageItem userItem = messageList.addMessage("You", message);
    chatClient.stream(new Prompt(message))
        .subscribe(response -> {
            userItem.append(response.getResult().getOutput().getContent());
        });
});

Streaming suits verbose responses, reducing perceived latency, while observability integrations (e.g., OpenTelemetry) trace interactions for debugging nondeterministic behaviors.

Guardrails for Security and Validation

AI workflows must mitigate risks like sensitive data leaks or invalid outputs. Input guardrails intercept prompts, using on-premises models to check for compliance with policies, blocking unauthorized queries (e.g., personal information). Output guardrails validate responses, reprompting for corrections if deserialization fails.

Advisors enable this: a default advisor with a local chat model filters inputs/outputs. For example, querying an address might be blocked if flagged, preventing cloud exposure. This ensures determinism in structured outputs, converting unstructured text to Java objects via JSON instructions.

Implications include privacy preservation in regulated sectors and integration with Spring Security for role-based tool access.

Multimodality and Retrieval-Augmented Generation

LLMs extend beyond text through multimodality, processing images, audio, or videos. Spring AI’s entity methods augment prompts for structured extraction, e.g., parsing attendee details from images into tables for programmatic use.

Retrieval-augmented generation (RAG) combats hallucinations by embedding external data as vectors in stores like PostgreSQL. A RetrievalAugmentationAdvisor retrieves relevant documents via similarity search, augmenting prompts. Customizations allow empty contexts for fallback to model knowledge.

Example:

VectorStore vectorStore = // PostgreSQL vector store
DocumentRetriever retriever = new VectorStoreDocumentRetriever(vectorStore);
RetrievalAugmentationAdvisor advisor = RetrievalAugmentationAdvisor.builder()
    .documentRetriever(retriever)
    .queryAugmentor(QueryAugmentor.contextual().allowEmptyContext(true))
    .build();

This pattern grounds responses in proprietary data, with thresholds controlling retrieval scope.

Tool Calling, Agents, and Dynamic Integrations

Tool calling empowers LLMs as agents, invoking external functions for tasks like database queries. Annotations describe tools, passed to clients for dynamic selection. For products, a service might expose query/update methods:

@Tool(description = "Fetch products from database")
public List<Product> getProducts(@P(description = "Category filter") String category) {
    // Database query
}

Agents orchestrate tools, potentially via Model Context Protocol for external services. Demonstrations include theme generation from screenshots, editing CSS via file system tools, highlighting nondeterminism and the need for safeguards.

In conclusion, these patterns enable production AI, emphasizing modularity, security, and observability for robust Java applications.

Links: