Interface ToolGuardrailService
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:
- the guardrails given to the builder (set on the
AiServicesbuilder; they apply to every tool) - the guardrails of the
ToolInputGuardrailsannotation of the class of the tool - 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
-
Nested Class Summary
Nested ClassesModifier and TypeInterfaceDescriptionstatic interfaceBuilds aToolGuardrailService.static interfaceIdentifies a tool to theToolGuardrailServicethat bound it (seebind(AiServiceTool)), as the key of theexecute*andhas*methods. -
Method Summary
Modifier and TypeMethodDescriptionbind(AiServiceTool tool) Binds a tool to this service: resolves the tool guardrails that apply to the tool, and returns the key to run them with.static ToolGuardrailService.BuilderCreates a builder ofToolGuardrailService.default GuardedToolExecutionexecuteGuardrails(ToolGuardrailService.ToolKey key, ToolExecutionRequest request, GuardrailRequestParams requestParams, Function<ToolExecutionRequest, ToolExecutionResult> tool) Executes a tool call through the tool guardrails of the tool: the input guardrails, thentool, then the output guardrails.default CompletableFuture<GuardedToolExecution> executeGuardrailsAsync(ToolGuardrailService.ToolKey key, ToolExecutionRequest request, GuardrailRequestParams requestParams, Function<ToolExecutionRequest, CompletableFuture<ToolExecutionResult>> tool) Non-blocking counterpart ofexecuteGuardrails(ToolKey, ToolExecutionRequest, GuardrailRequestParams, Function), with the same rules, for the asynchronous (CompletableFuture) and reactive (Flow.Publisher) AI service modes.Executes the input guardrails of the tool.Non-blocking counterpart ofexecuteInputGuardrails(ToolKey, ToolInputGuardrailRequest): nothing is thrown, a fatal failure, an invalid key or a request that does not match the key fails the returned future.Executes the output guardrails of the tool.Non-blocking counterpart ofexecuteOutputGuardrails(ToolKey, ToolOutputGuardrailRequest): nothing is thrown, a fatal failure, an invalid key or a request that does not match the key fails the returned future.booleanWhether the tool has input guardrails.booleanWhether the tool has output guardrails.The configuration of the input guardrails of the tools, which also sets the arguments rewrite note ofGuardedToolExecution.resultContentsForLlm(List).
-
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/ToolOutputGuardrailsannotations of a tool are read when its executor is aDefaultToolExecutor: 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
Methodfor a tool, passes the guardrails of the class and of the method of the tool as the guardrails of theAiServiceTool, and binds a tool whose executor is not aDefaultToolExecutor: no annotation is read then, and the chain of the tool is theAiServiceToolguardrails and the guardrails given to the builder (seeToolGuardrailServicefor 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.ToolKeythat identifies this tool to this service: pass it toexecuteInputGuardrails(ToolKey, ToolInputGuardrailRequest),executeOutputGuardrails(ToolKey, ToolOutputGuardrailRequest), their asynchronous variants,hasInputGuardrails(ToolKey)/hasOutputGuardrails(ToolKey)andexecuteGuardrails(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 nevernull. A tool without guardrails also gets a key, and running its guardrails returns a success. The default implementation rejects, with anIllegalArgumentException, anullkey 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 ofGuardedToolExecution.resultContentsForLlm(List).- Returns:
- The configuration, the default one if none was given, never
null.
-
executeInputGuardrails
ToolInputGuardrailResult executeInputGuardrails(ToolGuardrailService.ToolKey key, ToolInputGuardrailRequest request) Executes the input guardrails of the tool.- Parameters:
key- The keybind(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 failureIllegalArgumentException- 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
CompletableFuture<ToolInputGuardrailResult> executeInputGuardrailsAsync(ToolGuardrailService.ToolKey key, ToolInputGuardrailRequest request) Non-blocking counterpart ofexecuteInputGuardrails(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 keybind(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
ToolOutputGuardrailResult executeOutputGuardrails(ToolGuardrailService.ToolKey key, ToolOutputGuardrailRequest request) Executes the output guardrails of the tool.- Parameters:
key- The keybind(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 failureIllegalArgumentException- 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
CompletableFuture<ToolOutputGuardrailResult> executeOutputGuardrailsAsync(ToolGuardrailService.ToolKey key, ToolOutputGuardrailRequest request) Non-blocking counterpart ofexecuteOutputGuardrails(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 keybind(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
Whether the tool has input guardrails.- Parameters:
key- The keybind(AiServiceTool)returned for the tool. Must not be null.- Returns:
trueif at least one input guardrail applies to the tool.
-
hasOutputGuardrails
Whether the tool has output guardrails.- Parameters:
key- The keybind(AiServiceTool)returned for the tool. Must not be null.- Returns:
trueif at least one output guardrail applies to the tool.
-
executeGuardrails
default GuardedToolExecution executeGuardrails(ToolGuardrailService.ToolKey key, ToolExecutionRequest request, GuardrailRequestParams requestParams, Function<ToolExecutionRequest, ToolExecutionResult> tool) Executes a tool call through the tool guardrails of the tool: the input guardrails, thentool, then the output guardrails. It is the tool counterpart ofGuardrailService.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 throughGuardedToolExecution.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,
toolruns withrequest, and its result is returned as is. - An input guardrail that rewrites the arguments changes the request that
toolruns with, andGuardedToolExecution.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 rawToolExecutionResult.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
ToolInputGuardrailExceptionor aToolOutputGuardrailException. It is thrown outsidetool, so the error handling of the tool does not see it. An exception thrown bytoolpropagates as is. ThetoolExecutionRequest()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
ToolArgumentsExceptionthrown by an input guardrail, for example byToolInputGuardrailRequest.argumentsAsMap()for arguments that cannot be parsed, is not a guardrail failure:tooldoes 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 keybind(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 isnull, the key is one this service rejects (seebind(AiServiceTool)), or the key is not the key of the tool thatrequestcalls
- Without guardrails for the tool,
-
executeGuardrailsAsync
default CompletableFuture<GuardedToolExecution> executeGuardrailsAsync(ToolGuardrailService.ToolKey key, ToolExecutionRequest request, GuardrailRequestParams requestParams, Function<ToolExecutionRequest, CompletableFuture<ToolExecutionResult>> tool) Non-blocking counterpart ofexecuteGuardrails(ToolKey, ToolExecutionRequest, GuardrailRequestParams, Function), with the same rules, for the asynchronous (CompletableFuture) and reactive (Flow.Publisher) AI service modes. The guardrails run withexecuteInputGuardrailsAsync(ToolKey, ToolInputGuardrailRequest)andexecuteOutputGuardrailsAsync(ToolKey, ToolOutputGuardrailRequest), so a guardrail that overridesGuardrail.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 theToolArgumentsExceptionof an input guardrail), a failed future oftool, anullparameter, a key this service rejects and a key of another tool than the onerequestcalls all fail the returned future. Canceling the returned future cancels the guardrails or the tool in flight.Nothing moves to another thread here:
toolis 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 whosevalidateAsynccompletes on a thread of its own (an I/O thread, for example) therefore runstool, 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 intool, and moves back to it when the returned future completes.- Parameters:
key- The keybind(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
Creates a builder ofToolGuardrailService. If aToolGuardrailServiceBuilderFactoryis found byServiceLoader, 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.
-