Interface AsyncToolCallback
- All Superinterfaces:
StateAwareToolCallback,org.springframework.ai.tool.ToolCallback
- All Known Subinterfaces:
CancellableAsyncToolCallback
- All Known Implementing Classes:
AsyncToolCallbackAdapter
Interface for asynchronous tool callbacks.
Extends StateAwareToolCallback to support state injection.
Tools implementing this interface can perform long-running operations
without blocking the main execution thread. The callAsync(java.lang.String, org.springframework.ai.chat.model.ToolContext) method
returns a CompletableFuture that completes when the operation finishes.
Example usage:
public class LongRunningTool implements AsyncToolCallback {
@Override
public ToolDefinition getToolDefinition() {
return ToolDefinition.builder()
.name("longRunningTool")
.description("A tool that performs long-running operations")
.build();
}
@Override
public CompletableFuture<String> callAsync(String arguments, ToolContext context) {
return CompletableFuture.supplyAsync(() -> {
// Long-running operation
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Processing interrupted", e);
}
return "result";
});
}
@Override
public Duration getTimeout() {
return Duration.ofMinutes(10);
}
}
- Since:
- 1.0.0
- Author:
- disaster
- See Also:
-
Field Summary
Fields inherited from interface org.springframework.ai.tool.ToolCallback
logger -
Method Summary
Methods inherited from interface org.springframework.ai.tool.ToolCallback
call, getToolDefinition, getToolMetadata
-
Method Details
-
callAsync
CompletableFuture<String> callAsync(String arguments, org.springframework.ai.chat.model.ToolContext context) Asynchronously executes the tool with the given arguments.- Parameters:
arguments- the tool arguments as JSON stringcontext- the tool execution context- Returns:
- a CompletableFuture that will complete with the result string
-
call
Synchronous fallback implementation. Blocks until the async operation completes.This method unwraps
CompletionExceptionto expose the original exception, making error handling more intuitive for callers.- Specified by:
callin interfaceorg.springframework.ai.tool.ToolCallback- Parameters:
arguments- the tool arguments as JSON stringcontext- the tool execution context- Returns:
- the result string
- Throws:
RuntimeException- if the async operation failsToolCancelledException- if the operation was cancelled
-
isAsync
default boolean isAsync()Returns whether this tool executes asynchronously.- Returns:
- true (always async for this interface)
-
getTimeout
Returns the timeout duration for this tool execution.- Returns:
- the timeout duration, defaults to 5 minutes
-