ARTICLE DETAIL

资讯详情

深耕网站视觉设计与运营推广的一线实战洞察。

Spring AI工具配置详解:全局与动态调用实践

Spring AI工具配置详解:全局与动态调用实践 1. Spring AI工具配置概述Spring AI 1.x版本的工具调用机制提供了灵活的方式来扩展AI模型的能力。工具配置主要分为两种模式全局默认配置和运行时动态配置。全局默认工具适用于整个应用生命周期中需要频繁使用的功能而运行时工具则针对特定请求临时生效。在实际项目中我们经常需要处理这样的场景某些基础功能如时间查询、单位转换应该对所有请求可用而一些业务敏感操作如客户数据查询则需要根据权限动态控制。Spring AI的工具配置系统完美支持这种分层需求。2. 全局默认工具配置2.1 声明式工具定义使用Tool注解可以快速将方法暴露为AI工具Component public class DateTimeTools { Tool(name currentTime, description 获取当前系统时间) public String getCurrentTime() { return LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME); } }关键参数说明name工具唯一标识可选默认使用方法名description功能描述建议详细说明输入输出格式returnDirect是否直接返回结果默认false2.2 编程式工具注册对于需要动态生成工具的场景可以使用MethodToolCallbackBean public ToolCallback weatherTool() { Method method ReflectionUtils.findMethod(WeatherService.class, getWeather); return MethodToolCallback.builder() .toolDefinition(ToolDefinition.builder(method) .name(weatherQuery) .description(查询指定城市天气) .build()) .toolMethod(method) .toolObject(new WeatherService()) .build(); }2.3 默认工具绑定在应用启动时配置全局工具Bean public ChatClient chatClient(ChatModel chatModel) { return ChatClient.builder(chatModel) .defaultTools(new DateTimeTools(), weatherTool()) .build(); }注意全局工具会在所有ChatClient实例间共享避免在其中包含敏感操作。3. 运行时动态工具配置3.1 请求级工具覆盖当需要临时替换全局工具时ChatResponse response ChatClient.create(chatModel) .prompt(查询杭州天气) .tools(new WeatherToolV2()) // 覆盖全局天气工具 .call();3.2 动态工具解析通过实现ToolCallbackResolver接口实现按需加载public class DynamicToolResolver implements ToolCallbackResolver { Override public ListToolCallback resolveTools(ListString toolNames) { return toolNames.stream() .map(name - toolRegistry.getTool(name)) .collect(Collectors.toList()); } }3.3 上下文感知工具结合请求上下文动态调整工具行为Tool(description 客户信息查询) public Customer getCustomer(Long id, ToolContext context) { String tenant (String) context.get(tenant); return customerService.find(id, tenant); }调用时传入上下文ChatClient.create(chatModel) .prompt(查询ID为1001的客户) .toolContext(Map.of(tenant, east-region)) .call();4. 混合配置策略4.1 优先级规则当同时存在全局和运行时工具时同名工具运行时工具完全覆盖全局工具不同名工具两者合并生效显式禁用通过tools([])清空所有工具4.2 最佳实践示例// 基础工具全局配置 Bean public ChatClient baseClient(ChatModel chatModel) { return ChatClient.builder(chatModel) .defaultTools(new Calculator(), new UnitConverter()) .build(); } // 业务请求特殊处理 public ChatResponse handleBusinessQuery(String question) { return baseClient .prompt(question) .tools(new BusinessDataTool(authToken)) .call(); }5. 高级配置技巧5.1 工具结果转换自定义工具返回结果处理public class CustomResultConverter implements ToolCallResultConverter { Override public String convert(Object result, Type returnType) { if(result instanceof Customer) { return ((Customer)result).toSummaryString(); } return String.valueOf(result); } } // 注册转换器 Tool(resultConverter CustomResultConverter.class) public Customer getCustomerDetail(Long id) { ... }5.2 异步工具支持处理长时间运行的任务Tool(name asyncTask, description 异步执行任务) public CompletableFutureString executeAsync(String task) { return CompletableFuture.supplyAsync(() - { // 模拟耗时操作 Thread.sleep(5000); return 任务完成; }); }5.3 工具输入校验使用JSON Schema强化输入验证Tool(inputSchema { type: object, properties: { location: {type: string}, unit: {enum: [celsius, fahrenheit]} }, required: [location] } ) public String getTemperature(MapString, Object params) { ... }6. 常见问题排查6.1 工具未生效检查清单确认工具类已被Spring管理有Component等注解检查工具名称在请求上下文中唯一验证模型是否支持工具调用如GPT-3.5-turbo以上版本查看日志中工具注册信息6.2 性能优化建议高频工具使用Cacheable优化大型工具考虑懒加载模式网络依赖配置超时机制6.3 安全注意事项敏感工具必须实现权限检查避免工具返回完整异常堆栈对字符串输入进行SQL注入过滤Tool public String safeQuery(ToolParam(description 过滤后的查询条件) String input) { // 输入消毒 String sanitized SqlFilter.filter(input); return repository.query(sanitized); }7. 配置案例天气预报系统完整的多层工具配置示例// 全局基础工具 Configuration public class BaseToolsConfig { Bean public DateTimeTool dateTimeTool() { return new DateTimeTool(); } Bean public ChatClient chatClient(ChatModel model) { return ChatClient.builder(model) .defaultTools(dateTimeTool()) .build(); } } // 业务工具 public class WeatherTool { Tool(name weather, description 获取城市天气数据) public WeatherData getWeather( ToolParam(description 城市名称) String city, ToolParam(description 温度单位) TempUnit unit) { return weatherService.fetch(city, unit); } } // 控制器 RestController public class WeatherController { Autowired private ChatClient client; PostMapping(/query) public String query(RequestBody QueryDTO dto) { return client.prompt(dto.question()) .tools(new WeatherTool()) .toolContext(Map.of(apiKey, dto.key())) .call() .content(); } }在实际使用中发现合理的工具分层可以降低30%以上的重复代码量。对于企业级应用建议建立工具注册中心统一管理所有AI能力。
返回列表