Class ToolService
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final recordThe results of a round of tool executions, keeping successful and failed tools together so the caller can compensate the tools that did succeed before failing the invocation with the tool error.static final recordA compensable tool that ran: the execution its compensating action gets, with the result of the tool as it ran (before its output guardrails, which may have redacted what the undo needs), and the execution its compensation events carry, with the guarded result (after the output guardrails, as in theToolExecutedEvent, and without the note of an input rewrite).static final recordstatic final record -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidafterToolExecution(Consumer<ToolExecution> afterToolExecution) applyToolHallucinationStrategy(ToolExecutionRequest toolRequest) voidTheToolArgumentsErrorHandlerfor the asynchronous AI Service modes (CompletableFuture, reactiveFlow.Publisher): a user-configured handler if present, otherwise the async default, which sends the parsing error to the LLM so it can retry with corrected arguments.TheToolExecutionErrorHandlerfor the asynchronous AI Service modes (CompletableFuture, reactiveFlow.Publisher): a user-configured handler if present, otherwise the async default, which fails the AI Service invocation (rather than hiding the error from the developer by sending it to the LLM).voidbeforeToolExecution(Consumer<BeforeToolExecution> beforeToolExecution) voidcollectCompensableRound(ToolExecutionRound.Outcome round, List<ToolService.CompensableToolExecution> compensableExecutions, InvocationContext invocationContext) AscollectCompensableRound(List, Map, List, InvocationContext), for a completedToolExecutionRoundwhose calls may have gone through tool guardrails, before it is passed tocompensateCollectedRoundAsync(ToolExecutionRound.Outcome, List, List, boolean, ChatMemory, List, InvocationContext, AiServiceListenerRegistrar, Consumer, Throwable).collectCompensableRound(List<ToolExecutionRequest> toolExecutionRequests, Map<ToolExecutionRequest, ToolExecutionResult> toolResults, List<ToolService.CompensableToolExecution> compensableExecutions, InvocationContext invocationContext) Records one completed round's successful compensable tool executions into the sharedaccumulatorand returns the first errored tool's name (ornull).combineToolResultsCollectingErrors(Map<ToolExecutionRequest, CompletableFuture<ToolExecutionResult>> futures) Combines a set of in-flight (possibly already-started) tool executions into a single future of their results, keyed and ordered by request.compensateCollectedRoundAsync(ToolExecutionRound.Outcome round, List<ToolExecutionResultMessage> resultMessages, List<ToolService.CompensableToolExecution> compensableExecutions, boolean anyToolErrored, @Nullable ChatMemory chatMemory, @Nullable List<ChatMessage> messages, InvocationContext invocationContext, AiServiceListenerRegistrar listenerRegistrar, @Nullable Consumer<AiServiceStreamingEvent.ToolCompensatedEvent> streamEventEmitter, @Nullable Throwable invocationError) Non-blocking counterpart ofcompensateIfNeeded(List, Map, List, List, boolean, ChatMemory, List, InvocationContext, AiServiceListenerRegistrar), used by theCompletableFutureand reactive modes, for a completedToolExecutionRoundwhose compensable tools were already collected withcollectCompensableRound(ToolExecutionRound.Outcome, List, InvocationContext).voidcompensateIfNeeded(ToolExecutionRound.Outcome round, List<ToolExecutionResultMessage> resultMessages, @Nullable List<ToolService.CompensableToolExecution> compensableExecutions, boolean anyToolErrored, @Nullable ChatMemory chatMemory, @Nullable List<ChatMessage> messages, InvocationContext invocationContext, AiServiceListenerRegistrar listenerRegistrar) AscompensateIfNeeded(List, Map, List, List, boolean, ChatMemory, List, InvocationContext, AiServiceListenerRegistrar), for a completedToolExecutionRound, whose calls may have gone through tool guardrails: whether a tool is compensable, and the result its compensating action gets, are the ones of the tool as it ran, and the reason of theToolCompensatedEvents tells whether a tool guardrail made the step fail.voidcompensateIfNeeded(List<ToolExecutionRequest> toolExecutionRequests, Map<ToolExecutionRequest, ToolExecutionResult> toolResults, List<ToolExecutionResultMessage> resultMessages, List<ToolService.CompensableToolExecution> compensableExecutions, boolean anyToolErrored, ChatMemory chatMemory, List<ChatMessage> messages, InvocationContext invocationContext, AiServiceListenerRegistrar listenerRegistrar) Synchronous tool compensation, used by the synchronous /TokenStreammodes.voidcompensateOnCancellation(ToolExecutionRound.Outcome currentRound, @Nullable List<ToolExecutionRequest> unsavedRequests, @Nullable List<ToolService.CompensableToolExecution> compensableExecutions, @Nullable ChatMemory chatMemory, InvocationContext invocationContext, AiServiceListenerRegistrar listenerRegistrar) Blocking counterpart ofcompensateOnCancellationAsync(ToolExecutionRound.Outcome, List, List, ChatMemory, List, InvocationContext, AiServiceListenerRegistrar), used by theTokenStreammode, which uses the chat memory synchronously: rolls back, on cancellation, every compensable tool that had already executed successfully, across all rounds, on the calling thread.compensateOnCancellationAsync(@Nullable ToolExecutionRound.Outcome currentRound, @Nullable List<ToolExecutionRequest> unsavedRequests, @Nullable List<ToolService.CompensableToolExecution> compensableExecutions, @Nullable ChatMemory chatMemory, @Nullable List<ChatMessage> messages, InvocationContext invocationContext, AiServiceListenerRegistrar listenerRegistrar) Rolls back, on cancellation, every compensable tool that had already executed successfully - across all rounds - implementing the "drain the round, then roll back" contract for the asynchronous and reactive modes.voidcompensateOnToolErrors(boolean compensateOnToolErrors) createContext(InvocationContext invocationContext, UserMessage userMessage, List<ChatMessage> messages) createContext(InvocationContext invocationContext, UserMessage userMessage, List<ChatMessage> messages, GuardrailRequestParams guardrailRequestParams) Creates the context of an AI service invocation, carrying the invocation'sGuardrailRequestParams, which the tool guardrails receive in their requests.Resolves theExecutorthat the asynchronous AI Service modes run tools on: the one set viaexecuteToolsConcurrently(Executor)/executeToolsConcurrently(), or the default virtual-thread executor when none was set.executeInferenceAndToolsLoop(AiServiceContext context, Object memoryId, ChatResponse chatResponse, ChatRequestParameters parameters, List<ChatMessage> messages, ChatMemory chatMemory, InvocationContext invocationContext, ToolServiceContext toolServiceContext, boolean isReturnTypeResult) executeInferenceAndToolsLoop(AiServiceContext context, Object memoryId, ChatResponse chatResponse, ChatRequestParameters parameters, List<ChatMessage> messages, ChatMemory chatMemory, InvocationContext invocationContext, ToolServiceContext toolServiceContext, Function<ChatRequest, ChatResponse> chatModelInvoker) executeInferenceAndToolsLoopAsync(AiServiceContext context, Object memoryId, ChatResponse chatResponse, ChatRequestParameters parameters, List<ChatMessage> messages, ChatMemory chatMemory, InvocationContext invocationContext, ToolServiceContext toolServiceContext, CompletableFuture<?> cancellation) executeInferenceAndToolsLoopAsync(AiServiceContext context, Object memoryId, ChatResponse chatResponse, ChatRequestParameters parameters, List<ChatMessage> messages, ChatMemory chatMemory, InvocationContext invocationContext, ToolServiceContext toolServiceContext, CompletableFuture<?> cancellation, Function<ChatRequest, CompletableFuture<ChatResponse>> chatModelInvoker) AsexecuteInferenceAndToolsLoopAsync(AiServiceContext, Object, ChatResponse, ChatRequestParameters, List, ChatMemory, InvocationContext, ToolServiceContext, CompletableFuture), but with a caller-supplied asynchronous model invoker.executeTool(InvocationContext invocationContext, Map<String, ToolExecutor> toolExecutors, ToolExecutionRequest toolRequest, Consumer<BeforeToolExecution> externalBeforeToolExecution, Consumer<ToolExecution> externalAfterToolExecution) Deprecated.It cannot apply the tool guardrails of every tool.voidvoidexecuteToolsConcurrently(Executor executor) static ToolExecutionResultexecuteWithErrorHandling(ToolExecutionRequest toolRequest, ToolExecutor toolExecutor, InvocationContext invocationContext, ToolArgumentsErrorHandler argumentsErrorHandler, ToolExecutionErrorHandler executionErrorHandler) voidexecutor()static List<AiServiceTool> Scans the given object for@Tool-annotated methods and returns a list ofAiServiceTools.static voidfireToolExecutedEventsOfFailedRound(InvocationContext invocationContext, List<ToolExecutionRequest> toolRequests, Map<ToolExecutionRequest, ToolExecutionResult> results, Map<ToolExecutionRequest, Throwable> errors, AiServiceListenerRegistrar listenerRegistrar) Fires aToolExecutedEventfor each tool of a round that has terminated, in the order the tools were requested, before a tool error that fails the invocation is rethrown: the tools that returned a result, and the tools whose error is rethrown (withToolExecutedEvent.isError()true).voidhallucinatedToolNameStrategy(Function<ToolExecutionRequest, ToolExecutionResultMessage> toolHallucinationStrategy) booleanLets code that builds AI Services, such as a framework integration, tell whether the defaultToolArgumentsErrorHandleris used, for example to warn about it.booleanLets code that builds AI Services, such as a framework integration, tell whether the defaultToolExecutionErrorHandleris used, for example to warn about it.booleanisImmediateTool(String toolName) Deprecated.usereturnBehavior(String)insteadintDeprecated.UsemaxToolCallingRoundTrips()instead.voidmaxSequentialToolsInvocations(int maxSequentialToolsInvocations) Deprecated.UsemaxToolCallingRoundTrips(int)instead.intvoidmaxToolCallingRoundTrips(int maxToolCallingRoundTrips) Creates the accumulator thecompensableExecutionsare collected into across tool-calling rounds, ornullwhen compensation is disabled.voidonCompensableToolExecution(BiConsumer<ToolExecution, Consumer<ToolExecution>> onCompensableToolExecution) voidonToolExecutionError(Consumer<InvocationContext> onToolExecutionError) persistToolResultsAndResolveMessages(AiServiceContext context, @Nullable ChatMemory chatMemory, List<ChatMessage> accumulator, List<ToolExecutionResultMessage> resultMessages, InvocationContext invocationContext, Runnable onSaved) LikepersistToolResultsAndResolveMessages(AiServiceContext, ChatMemory, List, List, InvocationContext), and runsonSavedas soon as the result messages are saved, before the messages are read back, so that a caller knows that they are saved even when reading the messages back fails.persistToolResultsAndResolveMessages(AiServiceContext context, ChatMemory chatMemory, List<ChatMessage> accumulator, List<ToolExecutionResultMessage> resultMessages, InvocationContext invocationContext) Persists the tool-result messages and resolves the messages to send in the next request — the memory-touching counterpart toprocessToolResults(AiServiceContext, List, Map, List, InvocationContext, ToolServiceContext), kept out of that shared bookkeeping so that each AI Service mode can perform the memory I/O on the appropriate thread (synchronously for the sync/TokenStreammodes, composed for theCompletableFuture/reactive modes).persistToolResultsAndResolveMessagesSync(AiServiceContext context, ChatMemory chatMemory, List<ChatMessage> accumulator, List<ToolExecutionResultMessage> resultMessages, InvocationContext invocationContext) Blocking counterpart ofpersistToolResultsAndResolveMessages(AiServiceContext, ChatMemory, List, List, InvocationContext)for the synchronous andTokenStreamAI Service modes, which use the synchronousChatMemorymethods (so a memory backed by a blocking store that only implements the synchronous methods keeps working).prepareNextChatRequest(AiServiceContext context, Object memoryId, List<ChatMessage> messages, InvocationContext invocationContext, ToolServiceContext toolServiceContext, Map<ToolExecutionRequest, ToolExecutionResult> toolResults, ChatRequestParameters parameters) Builds the next round'sChatRequest, shared by every AI Service mode: given the already-resolvedmessagesto send (seeresolveMessagesForNextRequest(List, AiServiceContext, InvocationContext)), it refreshes dynamic tool providers, folds in any tools found by tool search, overrides the tool specifications on the carried-forwardparameters, applies the chat-request transformer, and fires theAiServiceRequestIssuedEvent.processToolResults(AiServiceContext context, ToolExecutionRound.Outcome round, List<ToolExecution> toolExecutions, InvocationContext invocationContext, ToolServiceContext toolServiceContext) AsprocessToolResults(AiServiceContext, List, Map, List, InvocationContext, ToolServiceContext), for a completedToolExecutionRound, whose calls may have gone through tool guardrails: a compensable tool is exposed for cross-agent compensation when it ran successfully, whatever its output guardrails made of the result, and with the result it ran with.processToolResults(AiServiceContext context, List<ToolExecutionRequest> toolExecutionRequests, Map<ToolExecutionRequest, ToolExecutionResult> toolResults, List<ToolExecution> toolExecutions, InvocationContext invocationContext, ToolServiceContext toolServiceContext) Per-round bookkeeping shared by every AI Service mode (sync,CompletableFuture,TokenStream, reactiveFlow.Publisher): for each executed tool it records aToolExecution, fires theToolExecutedEvent, collects the tool-result message (in request order), and accumulatesanyToolErrored+ the per-toolReturnBehaviors.static ToolServiceContextrefreshDynamicProviders(ToolServiceContext toolServiceContext, List<ChatMessage> messages, InvocationContext invocationContext) Re-evaluates dynamic tool providers and returns an updatedToolServiceContextwith any newly provided tool specifications and executors.static List<ChatMessage> resolveMessagesForNextRequest(List<ChatMessage> memoryMessages, AiServiceContext context, InvocationContext invocationContext) Resolves the messages to send in the next request from the current memory view, honoringstoreRetrievedContentInChatMemory(whenfalse, the last user message is replaced with the original, un-augmented one so retrieved content is not persisted across rounds).returnBehavior(String toolName) Returns the effectiveReturnBehaviorfor the given tool, as configured on this service.static booleanshouldReturnImmediately(boolean anyToolErrored, List<ReturnBehavior> returnBehaviors) startRound(ToolServiceContext toolServiceContext, InvocationContext invocationContext, AiServiceListenerRegistrar listenerRegistrar) Starts a round of tool execution: the tool calls of one model response.startRound(ToolServiceContext toolServiceContext, InvocationContext invocationContext, AiServiceListenerRegistrar listenerRegistrar, CompletableFuture<?> cancellation) AsstartRound(ToolServiceContext, InvocationContext, AiServiceListenerRegistrar), for a round that stops whencancellationis canceled: no tool is started any more, and a call whose input guardrails are in flight is canceled.startTool(ToolExecutionRequest toolRequest, Map<String, ToolExecutor> toolExecutors, InvocationContext invocationContext, Consumer<BeforeToolExecution> externalBeforeToolExecution, Consumer<ToolExecution> externalAfterToolExecution, Executor executor) Deprecated.It cannot apply the tool guardrails of every tool.The service that executes the tool guardrails, if one was set.voidtoolGuardrailService(ToolGuardrailService toolGuardrailService) Sets the service that executes the tool guardrails, and binds every tool registered so far to it (the tools registered later are bound when they are registered, and the tools ofToolProviders when they are provided).Deprecated.usetoolProviders()insteadvoidtoolProvider(ToolProvider toolProvider) voidtoolProviders(Collection<ToolProvider> toolProviders) voidtools(Collection<Object> objectsWithTools) voidtools(List<AiServiceTool> tools) voidtools(Map<ToolSpecification, ToolExecutor> tools) voidtools(Map<ToolSpecification, ToolExecutor> tools, Set<String> immediateReturnToolNames) voidtoolSearchStrategy(ToolSearchStrategy toolSearchStrategy)
-
Constructor Details
-
ToolService
public ToolService()
-
-
Method Details
-
hallucinatedToolNameStrategy
public void hallucinatedToolNameStrategy(Function<ToolExecutionRequest, ToolExecutionResultMessage> toolHallucinationStrategy) -
toolProvider
-
toolProviders
- Since:
- 1.12.0
-
tools
-
tools
-
tools
-
tools
- Since:
- 1.14.0
-
toolGuardrailService
Sets the service that executes the tool guardrails, and binds every tool registered so far to it (the tools registered later are bound when they are registered, and the tools ofToolProviders when they are provided).null, the default, means that tool guardrails are not executed. Setting the service that is already set changes nothing: the tools keep their keys.- Since:
- 1.25.0
-
toolGuardrailService
The service that executes the tool guardrails, if one was set.- Since:
- 1.25.0
-
findTools
Scans the given object for@Tool-annotated methods and returns a list ofAiServiceTools.- Parameters:
objectWithTools- an object containing@Tool-annotated methods- Returns:
- list of resolved tools
- Throws:
IllegalConfigurationException- if the object has no@Tool-annotated methods- Since:
- 1.13.0
-
compensateOnToolErrors
public void compensateOnToolErrors(boolean compensateOnToolErrors) -
executeToolsConcurrently
public void executeToolsConcurrently()- Since:
- 1.4.0
-
executeToolsConcurrently
- Since:
- 1.4.0
-
effectiveToolExecutor
Resolves theExecutorthat the asynchronous AI Service modes run tools on: the one set viaexecuteToolsConcurrently(Executor)/executeToolsConcurrently(), or the default virtual-thread executor when none was set. Nevernull, so async tools are always offloaded and never block the model-response thread. Pass a single-threaded executor to run them serially.- Since:
- 1.20.0
-
maxToolCallingRoundTrips
public void maxToolCallingRoundTrips(int maxToolCallingRoundTrips) -
maxToolCallingRoundTrips
public int maxToolCallingRoundTrips() -
maxSequentialToolsInvocations
@Deprecated(since="1.15.0") public void maxSequentialToolsInvocations(int maxSequentialToolsInvocations) Deprecated.UsemaxToolCallingRoundTrips(int)instead. -
maxSequentialToolsInvocations
Deprecated.UsemaxToolCallingRoundTrips()instead. -
beforeToolExecution
- Since:
- 1.11.0
-
beforeToolExecution
- Since:
- 1.17.0
-
afterToolExecution
- Since:
- 1.11.0
-
afterToolExecution
- Since:
- 1.17.0
-
onCompensableToolExecution
public void onCompensableToolExecution(BiConsumer<ToolExecution, Consumer<ToolExecution>> onCompensableToolExecution) -
onToolExecutionError
-
argumentsErrorHandler
- Since:
- 1.4.0
-
argumentsErrorHandler
- Since:
- 1.4.0
-
hasExplicitArgumentsErrorHandler
public boolean hasExplicitArgumentsErrorHandler()Lets code that builds AI Services, such as a framework integration, tell whether the defaultToolArgumentsErrorHandleris used, for example to warn about it.- Returns:
trueif aToolArgumentsErrorHandlerwas configured explicitly,falseif the default one is used.- Since:
- 1.21.0
-
executionErrorHandler
- Since:
- 1.4.0
-
executionErrorHandler
- Since:
- 1.4.0
-
hasExplicitExecutionErrorHandler
public boolean hasExplicitExecutionErrorHandler()Lets code that builds AI Services, such as a framework integration, tell whether the defaultToolExecutionErrorHandleris used, for example to warn about it.- Returns:
trueif aToolExecutionErrorHandlerwas configured explicitly,falseif the default one is used.- Since:
- 1.21.0
-
asyncArgumentsErrorHandler
TheToolArgumentsErrorHandlerfor the asynchronous AI Service modes (CompletableFuture, reactiveFlow.Publisher): a user-configured handler if present, otherwise the async default, which sends the parsing error to the LLM so it can retry with corrected arguments.- Since:
- 1.20.0
-
asyncExecutionErrorHandler
TheToolExecutionErrorHandlerfor the asynchronous AI Service modes (CompletableFuture, reactiveFlow.Publisher): a user-configured handler if present, otherwise the async default, which fails the AI Service invocation (rather than hiding the error from the developer by sending it to the LLM).- Since:
- 1.20.0
-
toolSearchStrategy
- Since:
- 1.12.0
-
createContext
public ToolServiceContext createContext(InvocationContext invocationContext, UserMessage userMessage, List<ChatMessage> messages) -
createContext
public ToolServiceContext createContext(InvocationContext invocationContext, UserMessage userMessage, List<ChatMessage> messages, GuardrailRequestParams guardrailRequestParams) Creates the context of an AI service invocation, carrying the invocation'sGuardrailRequestParams, which the tool guardrails receive in their requests. A context without tools (so, without tool guardrails) is returned as is.- Since:
- 1.25.0
-
executeInferenceAndToolsLoop
public ToolServiceResult executeInferenceAndToolsLoop(AiServiceContext context, Object memoryId, ChatResponse chatResponse, ChatRequestParameters parameters, List<ChatMessage> messages, ChatMemory chatMemory, InvocationContext invocationContext, ToolServiceContext toolServiceContext, boolean isReturnTypeResult) -
executeInferenceAndToolsLoop
public ToolServiceResult executeInferenceAndToolsLoop(AiServiceContext context, Object memoryId, ChatResponse chatResponse, ChatRequestParameters parameters, List<ChatMessage> messages, ChatMemory chatMemory, InvocationContext invocationContext, ToolServiceContext toolServiceContext, Function<ChatRequest, ChatResponse> chatModelInvoker) -
executeInferenceAndToolsLoopAsync
public CompletableFuture<ToolServiceResult> executeInferenceAndToolsLoopAsync(AiServiceContext context, Object memoryId, ChatResponse chatResponse, ChatRequestParameters parameters, List<ChatMessage> messages, ChatMemory chatMemory, InvocationContext invocationContext, ToolServiceContext toolServiceContext, CompletableFuture<?> cancellation) Non-blocking counterpart ofexecuteInferenceAndToolsLoop(AiServiceContext, Object, ChatResponse, ChatRequestParameters, List, ChatMemory, InvocationContext, ToolServiceContext, boolean).Re-invokes the model via
ChatModel.chatAsync(ChatRequest)and composes tool executions without blocking: no thread waits while a model response is in flight. When tools are configured to execute concurrently, their results are composed (not joined) as well. When no tool executor is configured, tools run on the thread that delivered the model response.The
cancellationfuture lets the caller stop the loop: once it is cancelled, no further model call or tool execution is initiated, and any in-flight model call is cancelled. A tool execution that has already started is not interrupted — it runs to completion and its result is simply discarded (Java cannot safely interrupt arbitrary tool code; this is a deliberate best-effort contract).- Since:
- 1.20.0
-
executeInferenceAndToolsLoopAsync
public CompletableFuture<ToolServiceResult> executeInferenceAndToolsLoopAsync(AiServiceContext context, Object memoryId, ChatResponse chatResponse, ChatRequestParameters parameters, List<ChatMessage> messages, ChatMemory chatMemory, InvocationContext invocationContext, ToolServiceContext toolServiceContext, CompletableFuture<?> cancellation, Function<ChatRequest, CompletableFuture<ChatResponse>> chatModelInvoker) AsexecuteInferenceAndToolsLoopAsync(AiServiceContext, Object, ChatResponse, ChatRequestParameters, List, ChatMemory, InvocationContext, ToolServiceContext, CompletableFuture), but with a caller-supplied asynchronous model invoker. Lets a streaming-only AI Service drive the same loop by bridging itsStreamingChatModelto aCompletableFuture<ChatResponse>, instead of requiring aChatModel.- Since:
- 1.20.0
-
processToolResults
public ToolService.ToolResultsOutcome processToolResults(AiServiceContext context, List<ToolExecutionRequest> toolExecutionRequests, Map<ToolExecutionRequest, ToolExecutionResult> toolResults, List<ToolExecution> toolExecutions, InvocationContext invocationContext, ToolServiceContext toolServiceContext) Per-round bookkeeping shared by every AI Service mode (sync,CompletableFuture,TokenStream, reactiveFlow.Publisher): for each executed tool it records aToolExecution, fires theToolExecutedEvent, collects the tool-result message (in request order), and accumulatesanyToolErrored+ the per-toolReturnBehaviors. This bookkeeping is intentionally free of memory I/O — persisting the collected result messages (synchronously or composed) is left to each mode viapersistToolResultsAndResolveMessages(AiServiceContext, ChatMemory, List, List, InvocationContext)/persistToolResultsAndResolveMessagesSync(AiServiceContext, ChatMemory, List, List, InvocationContext), so memory work happens on the appropriate thread. The tool execution itself and the delivery of intermediate responses are likewise left to each mode.- Since:
- 1.20.0
-
processToolResults
public ToolService.ToolResultsOutcome processToolResults(AiServiceContext context, ToolExecutionRound.Outcome round, List<ToolExecution> toolExecutions, InvocationContext invocationContext, ToolServiceContext toolServiceContext) AsprocessToolResults(AiServiceContext, List, Map, List, InvocationContext, ToolServiceContext), for a completedToolExecutionRound, whose calls may have gone through tool guardrails: a compensable tool is exposed for cross-agent compensation when it ran successfully, whatever its output guardrails made of the result, and with the result it ran with.- Parameters:
round- the completed round: its calls as they were executed, and their results- Since:
- 1.25.0
-
persistToolResultsAndResolveMessages
public CompletionStage<List<ChatMessage>> persistToolResultsAndResolveMessages(AiServiceContext context, ChatMemory chatMemory, List<ChatMessage> accumulator, List<ToolExecutionResultMessage> resultMessages, InvocationContext invocationContext) Persists the tool-result messages and resolves the messages to send in the next request — the memory-touching counterpart toprocessToolResults(AiServiceContext, List, Map, List, InvocationContext, ToolServiceContext), kept out of that shared bookkeeping so that each AI Service mode can perform the memory I/O on the appropriate thread (synchronously for the sync/TokenStreammodes, composed for theCompletableFuture/reactive modes).When
chatMemoryisnull, the result messages are appended toaccumulatorand that list is returned. When present, each result message is added to memory (sequentially, never concurrently, so the underlying read-modify-write stays ordered) and the resolved memory view is returned.- Since:
- 1.20.0
-
persistToolResultsAndResolveMessages
public CompletionStage<List<ChatMessage>> persistToolResultsAndResolveMessages(AiServiceContext context, @Nullable ChatMemory chatMemory, List<ChatMessage> accumulator, List<ToolExecutionResultMessage> resultMessages, InvocationContext invocationContext, Runnable onSaved) LikepersistToolResultsAndResolveMessages(AiServiceContext, ChatMemory, List, List, InvocationContext), and runsonSavedas soon as the result messages are saved, before the messages are read back, so that a caller knows that they are saved even when reading the messages back fails.- Parameters:
chatMemory- the chat memory, ornullwhen the AI Service has noneonSaved- run once the result messages are saved; not run when saving them fails- Since:
- 1.25.0
-
persistToolResultsAndResolveMessagesSync
public List<ChatMessage> persistToolResultsAndResolveMessagesSync(AiServiceContext context, ChatMemory chatMemory, List<ChatMessage> accumulator, List<ToolExecutionResultMessage> resultMessages, InvocationContext invocationContext) Blocking counterpart ofpersistToolResultsAndResolveMessages(AiServiceContext, ChatMemory, List, List, InvocationContext)for the synchronous andTokenStreamAI Service modes, which use the synchronousChatMemorymethods (so a memory backed by a blocking store that only implements the synchronous methods keeps working).- Since:
- 1.20.0
-
resolveMessagesForNextRequest
public static List<ChatMessage> resolveMessagesForNextRequest(List<ChatMessage> memoryMessages, AiServiceContext context, InvocationContext invocationContext) Resolves the messages to send in the next request from the current memory view, honoringstoreRetrievedContentInChatMemory(whenfalse, the last user message is replaced with the original, un-augmented one so retrieved content is not persisted across rounds).- Since:
- 1.20.0
-
prepareNextChatRequest
public ToolService.NextChatRequest prepareNextChatRequest(AiServiceContext context, Object memoryId, List<ChatMessage> messages, InvocationContext invocationContext, ToolServiceContext toolServiceContext, Map<ToolExecutionRequest, ToolExecutionResult> toolResults, ChatRequestParameters parameters) Builds the next round'sChatRequest, shared by every AI Service mode: given the already-resolvedmessagesto send (seeresolveMessagesForNextRequest(List, AiServiceContext, InvocationContext)), it refreshes dynamic tool providers, folds in any tools found by tool search, overrides the tool specifications on the carried-forwardparameters, applies the chat-request transformer, and fires theAiServiceRequestIssuedEvent. Reading the messages from memory is left to each mode (synchronously or composed) so this method performs no memory I/O. Each mode supplies how the returned request is actually dispatched.- Since:
- 1.20.0
-
compensateIfNeeded
public void compensateIfNeeded(List<ToolExecutionRequest> toolExecutionRequests, Map<ToolExecutionRequest, ToolExecutionResult> toolResults, List<ToolExecutionResultMessage> resultMessages, List<ToolService.CompensableToolExecution> compensableExecutions, boolean anyToolErrored, ChatMemory chatMemory, List<ChatMessage> messages, InvocationContext invocationContext, AiServiceListenerRegistrar listenerRegistrar) Synchronous tool compensation, used by the synchronous /TokenStreammodes. Collects this round's successful compensable tools (accumulated across rounds) and, if any tool in this round errored, rolls them all back — running their compensating actions, then rewriting the chat memory (synchronously) and this round'sresultMessagesin place — before the result messages are persisted. A compensating action that returns aCompletableFutureis awaited. A compensating action that fails is logged, and the result of its tool says that the rollback failed. AToolCompensatedEventis fired for each rolled-back tool once the chat memory is rewritten, also when rewriting it fails, and that failure is then thrown. Returns immediately when compensation is disabled.- Since:
- 1.20.0
-
compensateIfNeeded
public void compensateIfNeeded(ToolExecutionRound.Outcome round, List<ToolExecutionResultMessage> resultMessages, @Nullable List<ToolService.CompensableToolExecution> compensableExecutions, boolean anyToolErrored, @Nullable ChatMemory chatMemory, @Nullable List<ChatMessage> messages, InvocationContext invocationContext, AiServiceListenerRegistrar listenerRegistrar) AscompensateIfNeeded(List, Map, List, List, boolean, ChatMemory, List, InvocationContext, AiServiceListenerRegistrar), for a completedToolExecutionRound, whose calls may have gone through tool guardrails: whether a tool is compensable, and the result its compensating action gets, are the ones of the tool as it ran, and the reason of theToolCompensatedEvents tells whether a tool guardrail made the step fail.- Parameters:
round- the completed round- Since:
- 1.25.0
-
compensateCollectedRoundAsync
public CompletableFuture<Void> compensateCollectedRoundAsync(ToolExecutionRound.Outcome round, List<ToolExecutionResultMessage> resultMessages, List<ToolService.CompensableToolExecution> compensableExecutions, boolean anyToolErrored, @Nullable ChatMemory chatMemory, @Nullable List<ChatMessage> messages, InvocationContext invocationContext, AiServiceListenerRegistrar listenerRegistrar, @Nullable Consumer<AiServiceStreamingEvent.ToolCompensatedEvent> streamEventEmitter, @Nullable Throwable invocationError) Non-blocking counterpart ofcompensateIfNeeded(List, Map, List, List, boolean, ChatMemory, List, InvocationContext, AiServiceListenerRegistrar), used by theCompletableFutureand reactive modes, for a completedToolExecutionRoundwhose compensable tools were already collected withcollectCompensableRound(ToolExecutionRound.Outcome, List, InvocationContext). The compensating actions and the chat-memory rewrite run without blocking the model-delivery thread: a compensating action that performs blocking I/O should return aCompletableFuture, and the rewrite usesChatMemory.setAsync(List). This round'sresultMessagesare rewritten once the compensating actions have run, so they must be read after the returned future completes. A compensating action that fails is logged, and the result of its tool says that the rollback failed; its error is also added as suppressed toinvocationError, and the events relayed into the event stream carry it (AiServiceStreamingEvent.ToolCompensatedEvent.compensationError()). The events are fired once the chat memory is rewritten, also when rewriting it fails; the returned future then fails with that failure.Whether a tool is compensable, and the result its compensating action gets, are the ones of the tool as it ran, and the reason of the
ToolCompensatedEvents tells whether a tool guardrail made the step fail.- Parameters:
round- the completed roundchatMemory- the chat memory, ornullwhen the AI Service has nonemessages- the messages of the invocation, rewritten whenchatMemoryisnull; may benullwhen there is a chat memorystreamEventEmitter- receives an event per rolled-back tool to relay into the event stream, ornullwhen there is no event streaminvocationError- the error that fails the invocation after the rollback, ornullwhen the invocation goes on (the tool error is sent to the LLM)- Since:
- 1.25.0
-
compensateOnCancellationAsync
public CompletableFuture<Void> compensateOnCancellationAsync(@Nullable ToolExecutionRound.Outcome currentRound, @Nullable List<ToolExecutionRequest> unsavedRequests, @Nullable List<ToolService.CompensableToolExecution> compensableExecutions, @Nullable ChatMemory chatMemory, @Nullable List<ChatMessage> messages, InvocationContext invocationContext, AiServiceListenerRegistrar listenerRegistrar) Rolls back, on cancellation, every compensable tool that had already executed successfully - across all rounds - implementing the "drain the round, then roll back" contract for the asynchronous and reactive modes. If the current (drained) round is supplied, its successful compensable tools are recorded first so they roll back together with those accumulated from earlier rounds; passnullas the current round when it was already collected, so that a round is never collected twice. Runs the compensating actions, rewrites the results of the rolled-back tools in the chat memory, except those ofunsavedRequests, clears the accumulator, and then fires aToolCompensatedEventper rolled-back tool (reasonCompensationReason.INVOCATION_CANCELLED), also when rewriting the chat memory fails. Nothing is relayed into the event stream of the reactive mode, as it delivers nothing after a cancellation. A no-op when compensation is disabled or nothing is pending.The calls of the round may have gone through tool guardrails: a tool that ran successfully is rolled back whatever its output guardrails made of the result.
- Parameters:
currentRound- the drained round, ornullwhen there is none or it was already collectedunsavedRequests- the requests of the round whose results are not in the chat memory, ornullwhen all results are saved therecompensableExecutions- the compensable tools collected across rounds, ornullwhen compensation is disabledchatMemory- the chat memory, ornullwhen the AI Service has nonemessages- the messages of the invocation, rewritten whenchatMemoryisnull; may benullwhen there is a chat memory- Since:
- 1.25.0
-
compensateOnCancellation
public void compensateOnCancellation(ToolExecutionRound.Outcome currentRound, @Nullable List<ToolExecutionRequest> unsavedRequests, @Nullable List<ToolService.CompensableToolExecution> compensableExecutions, @Nullable ChatMemory chatMemory, InvocationContext invocationContext, AiServiceListenerRegistrar listenerRegistrar) Blocking counterpart ofcompensateOnCancellationAsync(ToolExecutionRound.Outcome, List, List, ChatMemory, List, InvocationContext, AiServiceListenerRegistrar), used by theTokenStreammode, which uses the chat memory synchronously: rolls back, on cancellation, every compensable tool that had already executed successfully, across all rounds, on the calling thread. The compensating actions run in reverse order (one that returns aCompletableFutureis waited for), the results of the rolled-back tools are rewritten in the chat memory with its blocking methods, except those ofunsavedRequests, and then aToolCompensatedEventis fired per rolled-back tool (reasonCompensationReason.INVOCATION_CANCELLED), also when rewriting the chat memory fails, and that failure is then thrown. A no-op when compensation is disabled or nothing is pending.- Parameters:
currentRound- the drained round, ornullwhen there is none or it was already collectedunsavedRequests- the requests of the cancelled round whose results are not in the chat memory, ornullwhen all its results are saved therecompensableExecutions- the compensable tools collected across rounds, ornullwhen compensation is disabledchatMemory- the chat memory, ornullwhen the AI Service has none- Since:
- 1.25.0
-
collectCompensableRound
public String collectCompensableRound(List<ToolExecutionRequest> toolExecutionRequests, Map<ToolExecutionRequest, ToolExecutionResult> toolResults, List<ToolService.CompensableToolExecution> compensableExecutions, InvocationContext invocationContext) Records one completed round's successful compensable tool executions into the sharedaccumulatorand returns the first errored tool's name (ornull). The caller MUST hold the monitor ofaccumulatoracross this call together with whatever "round is complete" handoff it performs (e.g. clearing the inflight round), so that a concurrent cancellation - which reads that handoff and snapshots the accumulator under the same monitor - observes this round's tools as present once it sees the round released. Used by the reactive streaming path; the result messages are derived the same way as the cancellation path (toResultMessage(ToolExecutionRequest, ToolExecutionResult)).- Since:
- 1.20.0
-
collectCompensableRound
public void collectCompensableRound(ToolExecutionRound.Outcome round, List<ToolService.CompensableToolExecution> compensableExecutions, InvocationContext invocationContext) AscollectCompensableRound(List, Map, List, InvocationContext), for a completedToolExecutionRoundwhose calls may have gone through tool guardrails, before it is passed tocompensateCollectedRoundAsync(ToolExecutionRound.Outcome, List, List, boolean, ChatMemory, List, InvocationContext, AiServiceListenerRegistrar, Consumer, Throwable).- Parameters:
round- the completed round- Since:
- 1.25.0
-
newCompensableExecutionsAccumulator
Creates the accumulator thecompensableExecutionsare collected into across tool-calling rounds, ornullwhen compensation is disabled.- Since:
- 1.20.0
-
shouldReturnImmediately
public static boolean shouldReturnImmediately(boolean anyToolErrored, List<ReturnBehavior> returnBehaviors) -
refreshDynamicProviders
public static ToolServiceContext refreshDynamicProviders(ToolServiceContext toolServiceContext, List<ChatMessage> messages, InvocationContext invocationContext) Re-evaluates dynamic tool providers and returns an updatedToolServiceContextwith any newly provided tool specifications and executors.Non-dynamic providers are not re-called — their tools remain unchanged. Tools returned by dynamic providers are only added, never removed: once a tool is present in the context, it stays for the remainder of the AI service invocation.
- Since:
- 1.13.0
-
startRound
public ToolExecutionRound startRound(ToolServiceContext toolServiceContext, InvocationContext invocationContext, AiServiceListenerRegistrar listenerRegistrar) Starts a round of tool execution: the tool calls of one model response. The round is the only way to execute them through the tool guardrails:ToolExecutionRound.executeTool(ToolExecutionRequest, Consumer, Consumer)/ToolExecutionRound.startTool(ToolExecutionRequest, Consumer, Consumer, Executor)execute a call, andToolExecutionRound.complete(List)/ToolExecutionRound.completeAsync(List)report the round.The round applies the tool guardrails of the tool guardrail service of
toolServiceContext: a tool that the context has a key for runs the guardrails of its key, and a tool without a key is bound on demand, so it gets at least the guardrails that apply to every tool. A context without a tool guardrail service gets the one of this service, if it has one: the tools registered on this service keep their keys, and the other tools are bound on demand. Create the context withcreateContext(InvocationContext, UserMessage, List, GuardrailRequestParams), which binds the tools of this service and of its tool providers, and carries the parameters the tool guardrails get.- Parameters:
toolServiceContext- the context of the tools of the invocation;nullfor a round without toolslistenerRegistrar- the registrar of the invocation, for the events of the round; may benull
-
startRound
public ToolExecutionRound startRound(ToolServiceContext toolServiceContext, InvocationContext invocationContext, AiServiceListenerRegistrar listenerRegistrar, CompletableFuture<?> cancellation) AsstartRound(ToolServiceContext, InvocationContext, AiServiceListenerRegistrar), for a round that stops whencancellationis canceled: no tool is started any more, and a call whose input guardrails are in flight is canceled. A tool that has started is not interrupted: its call is canceled when the tool ends, so that output guardrails in flight do not hold up the rollback.- Parameters:
cancellation- canceled when the invocation is canceled; may benull
-
startTool
@Deprecated(since="1.25.0") public CompletableFuture<ToolExecutionResult> startTool(ToolExecutionRequest toolRequest, Map<String, ToolExecutor> toolExecutors, InvocationContext invocationContext, Consumer<BeforeToolExecution> externalBeforeToolExecution, Consumer<ToolExecution> externalAfterToolExecution, Executor executor) Deprecated.It cannot apply the tool guardrails of every tool. UsestartRound(ToolServiceContext, InvocationContext, AiServiceListenerRegistrar)andToolExecutionRound.startTool(ToolExecutionRequest, Consumer, Consumer, Executor)instead, which apply them.Initiates a single tool execution on the givenexecutor, returning a future of its result, so that concurrent tools overlap each other and the tail of the model stream.It applies the tool guardrails of the tools registered on this service. A tool that is not registered, such as a tool of a
ToolProvider, gets the tool guardrails that apply to every tool (and the ones on its method, for aDefaultToolExecutor), but not the ones set on itsAiServiceTool, which are not known here. The tool guardrails get no listener registrar, so their events are not delivered. When theexecutorrejects the tool, the returned future fails with the rejection.- Since:
- 1.20.0
-
combineToolResultsCollectingErrors
public static CompletableFuture<ToolService.CombinedToolResults> combineToolResultsCollectingErrors(Map<ToolExecutionRequest, CompletableFuture<ToolExecutionResult>> futures) Combines a set of in-flight (possibly already-started) tool executions into a single future of their results, keyed and ordered by request. Unlike a short-circuiting combine, it does not stop on the first tool failure: it waits for all tool executions to settle and returns every result (a failed tool becomes an error result), together with the first failure in request order. This lets the asynchronous AI Service modes, whose defaultToolExecutionErrorHandlerrethrows execution errors, still run the compensating actions of the tools that succeeded before failing the invocation with the tool error. The given map's iteration order determines the result order, so pass aLinkedHashMapin request order.- Since:
- 1.20.0
-
fireToolExecutedEventsOfFailedRound
public static void fireToolExecutedEventsOfFailedRound(InvocationContext invocationContext, List<ToolExecutionRequest> toolRequests, Map<ToolExecutionRequest, ToolExecutionResult> results, Map<ToolExecutionRequest, Throwable> errors, AiServiceListenerRegistrar listenerRegistrar) Fires aToolExecutedEventfor each tool of a round that has terminated, in the order the tools were requested, before a tool error that fails the invocation is rethrown: the tools that returned a result, and the tools whose error is rethrown (withToolExecutedEvent.isError()true). If a listener throws, the remaining events are not fired and the listener's exception is added as suppressed to the first tool error, which is the one the caller rethrows. -
executeTool
@Deprecated(since="1.25.0") public ToolExecutionResult executeTool(InvocationContext invocationContext, Map<String, ToolExecutor> toolExecutors, ToolExecutionRequest toolRequest, Consumer<BeforeToolExecution> externalBeforeToolExecution, Consumer<ToolExecution> externalAfterToolExecution) Deprecated.It cannot apply the tool guardrails of every tool. UsestartRound(ToolServiceContext, InvocationContext, AiServiceListenerRegistrar)andToolExecutionRound.executeTool(ToolExecutionRequest, Consumer, Consumer)instead, which apply them.Executes a tool, blocking.It applies the tool guardrails of the tools registered on this service. A tool that is not registered, such as a tool of a
ToolProvider, gets the tool guardrails that apply to every tool (and the ones on its method, for aDefaultToolExecutor), but not the ones set on itsAiServiceTool, which are not known here. The tool guardrails get no listener registrar, so their events are not delivered. -
executeWithErrorHandling
public static ToolExecutionResult executeWithErrorHandling(ToolExecutionRequest toolRequest, ToolExecutor toolExecutor, InvocationContext invocationContext, ToolArgumentsErrorHandler argumentsErrorHandler, ToolExecutionErrorHandler executionErrorHandler) -
applyToolHallucinationStrategy
-
toolSpecifications
-
toolExecutors
-
executor
- Since:
- 1.4.0
-
toolProviders
- Since:
- 1.12.0
-
toolProvider
Deprecated.usetoolProviders()instead -
returnBehavior
Returns the effectiveReturnBehaviorfor the given tool, as configured on this service. Unknown tools and tools without an explicit behavior default toReturnBehavior.TO_LLM.- Since:
- 1.14.0
-
isImmediateTool
Deprecated.usereturnBehavior(String)instead
-