← 返回首页 📚 实战课程
📑 本篇章节导航 (共5章,点击直达)
本节目标核心知识面试模拟动手练习下一课预告

P3-04 - Function Calling深度实战

本节目标

1. Function Calling的完整执行链路是什么?

2. 怎么设计一个好的Tool?参数schema怎么定义?

3. 多个Tool同时可用时,模型怎么选择?

4. Tool调用失败怎么处理?重试还是降级?

5. 如何手写一个Tool注册框架(不依赖Spring AI内置机制)?

核心知识

一、Function Calling的本质


Function Calling ≠ 函数调用
Function Calling = 让大模型"决定"调用哪个函数,并提供参数

大模型本身不会执行任何代码。
它只是输出JSON格式的函数调用指令:
{
  "name": "getWeather",
  "arguments": {"city": "深圳", "date": "2026-05-31"}
}

然后由你的代码执行这个函数,把结果返回给模型。
模型再基于函数结果生成自然语言回复。

为什么需要这个?
  → 模型不知道实时数据(天气、库存、价格)
  → 模型不能执行操作(下单、发邮件、修改数据库)
  → Function Calling让模型"调用"你的系统API获取信息或执行操作

二、Spring AI中注册Tool的三种方式

方式1:@Bean函数注册(最基础)


@Configuration
public class ToolConfig {

    @Bean
    @Description("获取指定城市的当前天气信息")
    public Function<WeatherRequest, WeatherResponse> getWeather() {
        return request -> {
            // 实际调用天气API
            String url = "https://api.weather.com/v1?city=" + request.city();
            WeatherResponse response = restTemplate.getForObject(url, WeatherResponse.class);
            return response;
        };
    }

    public record WeatherRequest(String city) {}
    public record WeatherResponse(String city, double temperature, String condition) {}
}

方式2:@Tool注解(Spring AI 1.0推荐,你的AI定价系统用的就是类似方式)


@Component
public class PricingTools {

    @Tool(description = "查询指定航线的当前最低价")
    public String queryCurrentPrice(
        @ToolParam(description = "出发城市三字码") String departure,
        @ToolParam(description = "到达城市三字码") String arrival,
        @ToolParam(description = "出发日期,格式yyyy-MM-dd") String date
    ) {
        // 查询数据库或调用外部API
        FlightPrice price = priceRepository.findLowest(departure, arrival, date);
        return String.format("航线%s-%s %s最低价: %.0f元", departure, arrival, date, price.getAmount());
    }

    @Tool(description = "执行价格调整,将指定航线的价格设为新值")
    public String adjustPrice(
        @ToolParam(description = "航线ID") String routeId,
        @ToolParam(description = "新价格,单位元") double newPrice,
        @ToolParam(description = "调价原因") String reason
    ) {
        priceService.updatePrice(routeId, newPrice);
        auditLog.record("价格调整", routeId, newPrice, reason);
        return "价格调整成功: " + routeId + " → " + newPrice + "元";
    }
}

方式3:自定义AOP注册框架(你的@TdTool方式,面试加分)


// 自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TdTool {
    String description();
    String group() default "MANUAL";  // AUTO = 自动定价用, MANUAL = 对话用
}

// AOP自动注册
@Component
public class ToolRegistryProcessor implements ApplicationContextAware {

    private final Map<String, FunctionCallback> toolMap = new HashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext ctx) {
        // 扫描所有带 @TdTool 注解的方法
        for (String beanName : ctx.getBeanDefinitionNames()) {
            Object bean = ctx.getBean(beanName);
            for (Method method : bean.getClass().getDeclaredMethods()) {
                TdTool annotation = method.getAnnotation(TdTool.class);
                if (annotation != null) {
                    // 把方法包装成 FunctionCallback 注册
                    FunctionCallback callback = FunctionCallback.builder()
                        .function(method.getName(), (input) -> {
                            try {
                                return method.invoke(bean, parseArgs(input, method));
                            } catch (Exception e) {
                                return "工具调用失败: " + e.getMessage();
                            }
                        })
                        .description(annotation.description())
                        .build();
                    toolMap.put(method.getName(), callback);
                }
            }
        }
    }

    public List<FunctionCallback> getToolsByGroup(String group) {
        // 按group筛选工具
        return toolMap.values().stream()
            .filter(cb -> /* 按group过滤 */)
            .collect(Collectors.toList());
    }
}

三、Tool设计的7个原则


原则1:单一职责
  一个Tool只做一件事
  ✗ queryAndAdjustPrice(query, newPrice) → 做了两件事
  ✓ queryPrice(query) + adjustPrice(routeId, newPrice)

原则2:参数要具体
  @ToolParam(description = "出发城市三字码,如SZX")  ← 好的描述
  @ToolParam(description = "出发地")                  ← 太模糊

原则3:返回结构化文本
  返回String但用固定格式,让模型好解析
  "航线SZX-PEK 2026-06-01 最低价: 580元, 当前库存: 12张"
  而不是返回一个对象(模型不一定能解析)

原则4:幂等性
  查询类Tool天然幂等
  修改类Tool要考虑重复调用的影响(加去重Token或乐观锁)

原则5:超时处理
  Tool调用可能很慢(外部API),设置超时
  使用CompletableFuture.supplyAsync + orTimeout

原则6:错误返回
  不要抛异常,返回错误信息字符串
  "查询失败: 航班数据接口超时,请稍后重试"

原则7:审计日志
  所有Tool调用都记录日志(谁调的、参数是什么、结果是什么)
  特别是修改类操作

四、多Tool编排 — 模型怎么选择


当你注册了10个Tool时,模型怎么知道该调用哪个?

答案是:模型根据Tool的description和参数schema做判断。
所以description的准确性直接决定模型的选择准确率。

常见问题:
1. 多个Tool描述相似 → 模型可能选错
   解决:明确描述适用场景
   ✗ "查询价格" 和 "查询库存" → 太像
   ✓ "查询航班机票售价(调用前先查库存确认有票)"
     "查询航班剩余座位数(仅查库存不查价格)"

2. 模型选了不该调的Tool → 加前置校验
   在Tool执行前检查参数合法性

3. 模型想同时调多个Tool → Spring AI支持并行Tool调用
   模型返回多个tool_calls → 依次执行 → 结果一起返回

五、Tool调用失败的降级策略


@Component
public class ResilientToolExecutor {

    private final RestTemplate restTemplate;
    private final MeterRegistry meterRegistry;

    /**
     * 带降级的Tool执行器
     */
    public String executeWithFallback(String toolName, Map<String, Object> args,
                                       Supplier<String> primaryAction,
                                       Supplier<String> fallbackAction) {
        try {
            String result = primaryAction.get();
            meterRegistry.counter("tool.call.success", "tool", toolName).increment();
            return result;
        } catch (Exception e) {
            meterRegistry.counter("tool.call.failure", "tool", toolName).increment();
            if (fallbackAction != null) {
                String fallbackResult = fallbackAction.get();
                return fallbackResult + "(注意:主数据源不可用,返回的是缓存数据)";
            }
            return "抱歉," + toolName + "暂时不可用,请稍后重试";
        }
    }
}

// 使用示例:
@Tool(description = "查询航班价格")
public String queryPrice(String departure, String arrival, String date) {
    return executor.executeWithFallback(
        "queryPrice",
        Map.of("dep", departure, "arr", arrival, "date", date),
        () -> flightApi.getPrice(departure, arrival, date),  // 主:调外部API
        () -> redisCache.getPrice(departure, arrival, date)   // 备:查Redis缓存
    );
}

面试模拟

Q1: "你们有多少个Tool?怎么管理Tool的?"

"定价系统有8个Tool,分两组:
AUTO组(4个)给自动定价管道用:数据收集、利润计算、价格调整、MQ执行
MANUAL组(4个)给对话管道用:数据查询、配置修改、心跳检测、规则更新

>

管理方式是用自定义@TdTool注解 + AOP自动注册。启动时扫描所有带注解的方法,
按group分类注册到ChatClient。这样新增Tool只需要写一个方法加个注解,不用改配置。

>

遇到的问题是Tool多了以后模型有时会选错,后来优化了每个Tool的description,
把适用场景写得更明确,准确率从70%提到了95%。"

Q2: "Tool调用超时怎么处理?"

"三层处理:
1. 外部API调用设3秒超时(RestTemplate设置readTimeout)
2. 超时后降级到Redis缓存数据(可能有延迟但至少有数据)
3. 如果缓存也没有,返回'暂时无法查询',不会阻塞整个对话流程

>

关键是Tool调用不能影响主流程——用CompletableFuture做异步,超时就放弃走降级。"

动手练习

练习1:手写3个Tool函数

1. 一个查询Tool(查数据库)

2. 一个计算Tool(做数学运算)

3. 一个外部API Tool(调用公开API)

练习2:实现Tool调用的错误处理

1. 模拟外部API超时

2. 验证降级策略是否生效

3. 记录Tool调用日志

下一课预告

P3-05将深入Agent设计模式:ReAct、Plan-Execute、Multi-Agent。