Tool Calling 基础
约 634 字大约 2 分钟
布欧-Lewyon
2026-05-15
首页 › Spring AI › Tool / Function Calling
什么是 Tool Calling
Tool Calling(Function Calling)让 AI 模型可以调用外部函数来获取实时数据或执行操作。AI 模型决定何时调用哪个函数,Spring AI 负责注册和执行。
@Tool 注解
@Component
public class OrderTools {
@Tool(name = "query_order", description = "Query order status by customer name")
public String queryOrder(String customerName) {
// 实际业务中调用数据库
return """
客户: %s
订单号: ORD-2026-001
状态: 已发货
物流单号: SF123456
""".formatted(customerName);
}
}注册 Tool 到 ChatClient
@Configuration
public class AIConfig {
@Bean
public ChatClient chatClient(ChatClient.Builder builder, OrderTools orderTools) {
return builder
.defaultSystem("You are a helpful customer service assistant")
.tools(orderTools) // 注册 Tool
.build();
}
}测试 Tool Calling
@RestController
public class CustomerServiceController {
private final ChatClient chatClient;
@GetMapping("/cs")
public String customerService(@RequestParam String message) {
return chatClient.call(message);
}
}curl "http://localhost:8080/cs?message=查询张三的订单"
# 张三的订单(ORD-2026-001)当前状态为:已发货,物流单号 SF123456Tool 参数和返回
@Component
public class ProductTools {
@Tool(name = "get_product_price", description = "Get the current price of a product")
public ProductPrice getProductPrice(
@ToolParam(description = "Product SKU code") String sku) {
// 查询数据库返回结构化结果
return new ProductPrice(sku, new BigDecimal("199.00"), "CNY");
}
}@ToolParam 为参数提供描述,帮助 AI 模型理解参数含义。
public record ProductPrice(String sku, BigDecimal price, String currency) {}
// AI 调用时的日志
// Calling tool: get_product_price with args: {"sku":"MBP-2025"}
// Tool returned: ProductPrice[sku=MBP-2025, price=199.00, currency=CNY]多个 Tool 协作
@Component
public class DateTimeTools {
@Tool(name = "get_current_datetime", description = "Get the current date and time")
public String getCurrentDateTime() {
return LocalDateTime.now().toString();
}
@Tool(name = "calculate_days_between", description = "Calculate days between two dates")
public long calculateDaysBetween(
@ToolParam(description = "Start date (yyyy-MM-dd)") String start,
@ToolParam(description = "End date (yyyy-MM-dd)") String end) {
return ChronoUnit.DAYS.between(LocalDate.parse(start), LocalDate.parse(end));
}
}ToolCallback 手动注册
@Bean
public ToolCallback weatherTool() {
return ToolCallback.builder()
.name("get_weather")
.description("Get current weather for a city")
.inputType(String.class)
.toolFunction(city -> {
// 调用天气 API
WeatherResponse weather = weatherService.getWeather((String) city);
return "City: %s, Temperature: %s°C, Condition: %s".formatted(
weather.city(), weather.temperature(), weather.condition());
})
.build();
}小结
- Tool Calling 让 AI 能调用 Java 方法获取数据或执行操作,是构建 AI 应用的关键能力。
@Tool(name, description)注册 Tool,AI 根据 description 决定调用哪个 Tool。@ToolParam(description)为参数提供描述。- Tool 方法可以返回 String 或复杂对象(自动转 JSON)。
- 多个 Tool 可同时注册,AI 按需选择。
ToolCallback.builder()支持手动构建 Tool。
上一节:实体抽取实战 下一节:数据库与 API Tool 实战
