Interface ToolGuardrailService


@Experimental public interface ToolGuardrailService
Executes the tool guardrails of the tools of an AI service: the ToolInputGuardrails, which validate or rewrite the arguments of a tool call before the tool runs, and the ToolOutputGuardrails, which validate or rewrite its result before the LLM sees it. It is the tool counterpart of GuardrailService.

Keys. The key of a tool is the ToolGuardrailService.ToolKey that bind(AiServiceTool) returns for it: it is only meaningful to the service that created it. A tool provided anew for every invocation (by a ToolProvider, for example an MCP server) is bound for every invocation. The key carries the specification and the source of the tool, so the guardrail requests are built from it.

Which guardrails run. The levels add up, as one chain, separately for input and output (within the class level and within the method level, the nearest declaration wins). The levels nest around the tool, with the guardrails given to the builder on the side of the LLM: they are the first to see the call of the LLM and the last to see the result it gets. The input guardrails run in this order:

  1. the guardrails given to the builder (set on the AiServices builder; they apply to every tool)
  2. the guardrails of the ToolInputGuardrails annotation of the class of the tool
  3. the guardrails of the annotation of the tool method, then the guardrails of the AiServiceTool

The output guardrails run the levels in the reverse order: the guardrails of the AiServiceTool, those of the ToolOutputGuardrails annotation of the tool method, then of its class, and the guardrails given to the builder last, so that they are the last to see the result before it goes to the LLM (the note of GuardedToolExecution.resultContentsForLlm(List) is added after them). Within a level, the guardrails keep the order they are given in, in both directions.

No level replaces another. This deliberately differs from the AI service guardrails of GuardrailService, where the builder replaces the annotations. A guardrail that applies to every tool can skip some tools by looking at ToolInputGuardrailRequest.toolName() or ToolInputGuardrailRequest.toolSource().

A guardrail class that is given at several levels (by annotations or *GuardrailClasses(..)) runs once, at its first position for input; for output, a guardrail class given to the builder runs once, at the position of the builder (last), and any other one at its first position. Guardrail instances only count as duplicates of themselves (the same object twice), since two instances of one class can be configured differently, and an instance and a class naming the same class both run.

Results. A non-fatal failure is returned as a failed result, never thrown, so that the caller can send it to the LLM as an error tool result. A fatal failure throws a ToolInputGuardrailException or a ToolOutputGuardrailException (the asynchronous methods fail their future with it). executeGuardrails(ToolKey, ToolExecutionRequest, GuardrailRequestParams, Function) runs a whole tool call through the guardrails and applies these rules, the way GuardrailService.executeGuardrails(Object, InputGuardrailRequest) does for the AI service guardrails; executeGuardrailsAsync(ToolKey, ToolExecutionRequest, GuardrailRequestParams, Function) is its non-blocking counterpart, for which the guardrails must implement Guardrail.validateAsync(GuardrailRequest).

Customizing. The default implementation finds the annotations of the classes of the tools through ClassMetadataProviderFactory, reads the annotations of the tool methods from the Method itself, and creates guardrails from their classes through ClassInstanceFactory, like the AI service guardrails. A framework can also replace the whole builder with a ToolGuardrailServiceBuilderFactory. An implementation must be thread-safe: one AI service runs many invocations at the same time, and the tools of one LLM response can run in parallel.

This interface is separate from GuardrailService: the two kinds of guardrails share their implementation, not a public contract.

Since:
1.25.0
  • Method Details

    • bind

      Binds a tool to this service: resolves the tool guardrails that apply to the tool, and returns the key to run them with.

      The ToolInputGuardrails / ToolOutputGuardrails annotations of a tool are read when its executor is a DefaultToolExecutor: those of its method, and those of the class hierarchy of the object the method is invoked on (for a JDK dynamic proxy, which only implements interfaces, of the class that declares the method). Any other tool gets no annotation.

      A framework that runs its own tool loop, and has no Method for a tool, passes the guardrails of the class and of the method of the tool as the guardrails of the AiServiceTool, and binds a tool whose executor is not a DefaultToolExecutor: no annotation is read then, and the chain of the tool is the AiServiceTool guardrails and the guardrails given to the builder (see ToolGuardrailService for the order). For input, it passes the class guardrails before the method guardrails, and for output the method guardrails before the class guardrails. Guardrail instances only count as duplicates of themselves, so it leaves out the guardrails it already gave to the builder. It binds every tool once, and binds again a tool whose guardrails change: a key keeps the guardrails the tool had when it was bound.

      Parameters:
      tool - The tool. Must not be null.
      Returns:
      The ToolGuardrailService.ToolKey that identifies this tool to this service: pass it to executeInputGuardrails(ToolKey, ToolInputGuardrailRequest), executeOutputGuardrails(ToolKey, ToolOutputGuardrailRequest), their asynchronous variants, hasInputGuardrails(ToolKey) / hasOutputGuardrails(ToolKey) and executeGuardrails(ToolKey, ToolExecutionRequest, GuardrailRequestParams, Function). It carries the specification and the source of the tool, is only meaningful to the service that returned it, and is never null. A tool without guardrails also gets a key, and running its guardrails returns a success. The default implementation rejects, with an IllegalArgumentException, a null key and any key it did not return itself, including a key of another service built the same way.
    • toolInputGuardrailsConfig

      ToolInputGuardrailsConfig toolInputGuardrailsConfig()
      The configuration of the input guardrails of the tools, which also sets the arguments rewrite note of GuardedToolExecution.resultContentsForLlm(List).
      Returns:
      The configuration, the default one if none was given, never null.
    • executeInputGuardrails

      Executes the input guardrails of the tool.
      Parameters:
      key - The key bind(AiServiceTool) returned for the tool. Must not be null.
      request - The request to validate. Must not be null, and must carry the tool name, the specification and the source of the key.
      Returns:
      The result, a success if the tool has no input guardrails. A non-fatal failure is returned, not thrown.
      Throws:
      ToolInputGuardrailException - for a fatal failure
      IllegalArgumentException - if the key was not returned by this service, or the request does not carry the tool name, the specification and the source of the key
    • executeInputGuardrailsAsync

      Non-blocking counterpart of executeInputGuardrails(ToolKey, ToolInputGuardrailRequest): nothing is thrown, a fatal failure, an invalid key or a request that does not match the key fails the returned future.
      Parameters:
      key - The key bind(AiServiceTool) returned for the tool. Must not be null.
      request - The request to validate. Must not be null, and must carry the tool name, the specification and the source of the key.
      Returns:
      A future of the result.
    • executeOutputGuardrails

      Executes the output guardrails of the tool.
      Parameters:
      key - The key bind(AiServiceTool) returned for the tool. Must not be null.
      request - The request to validate. Must not be null, and must carry the tool name, the specification and the source of the key.
      Returns:
      The result, a success if the tool has no output guardrails. A non-fatal failure is returned, not thrown.
      Throws:
      ToolOutputGuardrailException - for a fatal failure
      IllegalArgumentException - if the key was not returned by this service, or the request does not carry the tool name, the specification and the source of the key
    • executeOutputGuardrailsAsync

      Non-blocking counterpart of executeOutputGuardrails(ToolKey, ToolOutputGuardrailRequest): nothing is thrown, a fatal failure, an invalid key or a request that does not match the key fails the returned future.
      Parameters:
      key - The key bind(AiServiceTool) returned for the tool. Must not be null.
      request - The request to validate. Must not be null, and must carry the tool name, the specification and the source of the key.
      Returns:
      A future of the result.
    • hasInputGuardrails

      boolean hasInputGuardrails(ToolGuardrailService.ToolKey key)
      Whether the tool has input guardrails.
      Parameters:
      key - The key bind(AiServiceTool) returned for the tool. Must not be null.
      Returns:
      true if at least one input guardrail applies to the tool.
    • hasOutputGuardrails

      boolean hasOutputGuardrails(ToolGuardrailService.ToolKey key)
      Whether the tool has output guardrails.
      Parameters:
      key - The key bind(AiServiceTool) returned for the tool. Must not be null.
      Returns:
      true if at least one output guardrail applies to the tool.
    • executeGuardrails

      Executes a tool call through the tool guardrails of the tool: the input guardrails, then tool, then the output guardrails. It is the tool counterpart of GuardrailService.executeGuardrails(Object, InputGuardrailRequest): it builds the guardrail requests and turns the guardrail results into the request the tool runs with and the result to send to the LLM. One thing is left to the caller: the contents of the result it sends to the LLM, and the text that replaces the result when the call is rolled back, go through GuardedToolExecution.resultContentsForLlm(List), which adds the note that tells the LLM that an input guardrail changed the arguments of its call.
      • Without guardrails for the tool, tool runs with request, and its result is returned as is.
      • An input guardrail that rewrites the arguments changes the request that tool runs with, and GuardedToolExecution.request().
      • A non-fatal input failure does not run tool: the result is an error result whose text is the failure message, verbatim, and the request carries the arguments as the guardrails that ran before the failure left them.
      • The output guardrails also run on an error result of tool. A rewrite replaces the contents and the error flag of the result, keeps its attributes, and drops its raw ToolExecutionResult.result(), which no longer matches what the LLM sees. A non-fatal output failure replaces the result with an error result whose text is the failure message, verbatim.
      • A fatal failure throws a ToolInputGuardrailException or a ToolOutputGuardrailException. It is thrown outside tool, so the error handling of the tool does not see it. An exception thrown by tool propagates as is. The toolExecutionRequest() of the exception gives the call it stopped: for the input stage with the arguments as the guardrails before the failure left them, for the output stage as the tool ran with it.
      • A ToolArgumentsException thrown by an input guardrail, for example by ToolInputGuardrailRequest.argumentsAsMap() for arguments that cannot be parsed, is not a guardrail failure: tool does not run, and the exception is thrown as is, so that the caller handles it like an arguments error of the tool.
      Parameters:
      key - The key bind(AiServiceTool) returned for the tool. It also gives the specification and the source of the tool to the guardrail requests. Must not be null.
      request - The tool call of the LLM. Must not be null.
      requestParams - The parameters of the guardrail requests: those of the AI service invocation, so the tool guardrails see the same context as the AI service guardrails and their events reach the listeners of the invocation. Must not be null.
      tool - Executes the tool for the request it is given (the call, or the call as the input guardrails rewrote it) and returns its result. Must not be null.
      Returns:
      The request as the input guardrails left it, and the result to send to the LLM.
      Throws:
      IllegalArgumentException - if a parameter is null, the key is one this service rejects (see bind(AiServiceTool)), or the key is not the key of the tool that request calls
    • executeGuardrailsAsync

      Non-blocking counterpart of executeGuardrails(ToolKey, ToolExecutionRequest, GuardrailRequestParams, Function), with the same rules, for the asynchronous (CompletableFuture) and reactive (Flow.Publisher) AI service modes. The guardrails run with executeInputGuardrailsAsync(ToolKey, ToolInputGuardrailRequest) and executeOutputGuardrailsAsync(ToolKey, ToolOutputGuardrailRequest), so a guardrail that overrides Guardrail.validateAsync(GuardrailRequest) does not block the calling thread.

      Nothing is thrown from this method: a fatal guardrail failure, an exception thrown by a guardrail or by tool (including the ToolArgumentsException of an input guardrail), a failed future of tool, a null parameter, a key this service rejects and a key of another tool than the one request calls all fail the returned future. Canceling the returned future cancels the guardrails or the tool in flight.

      Nothing moves to another thread here: tool is called on the thread that completes the input guardrails (the calling thread when the tool has none, or when they complete at once), and the returned future completes on the thread that completes the last stage. A guardrail whose validateAsync completes on a thread of its own (an I/O thread, for example) therefore runs tool, and what the caller chains to the returned future, on that thread: a caller that must run the tool on its own executor starts it there in tool, and moves back to it when the returned future completes.

      Parameters:
      key - The key bind(AiServiceTool) returned for the tool. It also gives the specification and the source of the tool to the guardrail requests. Must not be null.
      request - The tool call of the LLM. Must not be null.
      requestParams - The parameters of the guardrail requests: those of the AI service invocation. Must not be null.
      tool - Starts the tool for the request it is given (the call, or the call as the input guardrails rewrote it) and returns the future of its result. Must not be null.
      Returns:
      A future of the request as the input guardrails left it and of the result to send to the LLM.
    • builder

      static ToolGuardrailService.Builder builder(Class<?> aiServiceClass)
      Creates a builder of ToolGuardrailService. If a ToolGuardrailServiceBuilderFactory is found by ServiceLoader, the first one found provides the builder; otherwise the default builder is used.
      Parameters:
      aiServiceClass - The class of the AI service whose tools are guarded. Must not be null.
      Returns:
      The builder.