Spring AI 中的工具调用使 AI 模型能够与外部工具和服务交互,从而增强其功能。

概述

工具调用允许 AI 模型:

  • 执行外部函数
  • 访问外部服务
  • 执行复杂操作
  • 与现有系统集成

工具类型

函数工具

执行自定义函数和方法

API 工具

与外部 API 和服务交互

数据库工具

执行数据库操作

自定义工具

实现自定义工具功能

实现

基本工具定义

@Tool
public class CalculatorTool {
    @ToolMethod
    public double add(double a, double b) {
        return a + b;
    }

    @ToolMethod
    public double subtract(double a, double b) {
        return a - b;
    }
}

工具注册

@Configuration
public class ToolConfig {
    @Bean
    public ToolRegistry toolRegistry() {
        return new ToolRegistry()
            .register(new CalculatorTool())
            .register(new WeatherTool())
            .register(new DatabaseTool());
    }
}

在聊天中使用工具

@Service
public class ChatService {
    private final ChatClient chatClient;
    private final ToolRegistry toolRegistry;

    public ChatService(ChatClient chatClient, ToolRegistry toolRegistry) {
        this.chatClient = chatClient;
        this.toolRegistry = toolRegistry;
    }

    public String chat(String message) {
        return chatClient.generate(message, toolRegistry);
    }
}

工具类别

1. 函数工具

@Tool
public class MathTool {
    @ToolMethod
    public double calculate(String expression) {
        // 实现
    }
}

2. API 工具

@Tool
public class WeatherTool {
    @ToolMethod
    public Weather getWeather(String location) {
        // API 调用实现
    }
}

3. 数据库工具

@Tool
public class DatabaseTool {
    @ToolMethod
    public List<Record> query(String sql) {
        // 数据库查询实现
    }
}

配置属性

spring.ai.tools.enabled=true
spring.ai.tools.timeout=5000
spring.ai.tools.max-retries=3
spring.ai.tools.cache-enabled=true

最佳实践

实现工具调用时,请考虑以下最佳实践:

  • 错误处理:实现强大的错误处理
  • 安全性:验证输入并限制访问
  • 性能:优化工具执行
  • 监控:跟踪工具使用情况和性能
  • 文档:记录工具功能和用法

高级特性

自定义工具实现

@Component
public class CustomTool implements Tool {
    @Override
    public String getName() {
        return "custom-tool";
    }

    @Override
    public Object execute(Map<String, Object> parameters) {
        // 自定义实现
        return result;
    }
}

工具监控

监控工具使用情况和性能:

management.endpoints.web.exposure.include=tools
management.endpoint.tools.enabled=true

故障排除

常见问题和解决方案:

  1. 工具执行错误

    • 实现适当的错误处理
    • 添加重试机制
    • 记录详细的错误信息
  2. 性能问题

    • 优化工具实现
    • 实现缓存
    • 使用异步执行
  3. 安全问题

    • 验证输入
    • 实现访问控制
    • 监控工具使用情况

文档有误?请协助编辑

发现文档问题?点击此处直接在 GitHub 上编辑并提交 PR,帮助我们改进文档!