Function Calling 机制

让 AI 能够调用外部工具 / Java 方法


什么是 Function Calling?

让大模型在回复时主动调用你定义的 Java 方法,而非仅生成文字。实现”AI Agent”能力的核心机制。


使用步骤

Step 1: 定义一个 Tool Function

1
2
3
4
5
6
7
8
9
@Component
public class WeatherTools {

@Tool(description = "查询城市的当前天气")
public String getWeather(@ToolParam("城市名称") String city) {
// 调用第三方天气 API
return "北京今天晴,26度";
}
}

Step 2: 注册到 ChatClient

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@RestController
public class AgentController {

private final ChatClient chatClient;

public AgentController(ChatClient.Builder builder, WeatherTools weatherTools) {
this.chatClient = builder
.defaultTools(weatherTools) // 注册工具
.build();
}

@GetMapping("/ai/agent")
public String agent(@RequestParam String question) {
return chatClient.prompt()
.user(question)
.call()
.content();
}
}

Step 3: 运行时流程

1
2
3
4
5
6
7
8
9
用户: "北京今天天气怎么样?"

LLM 判断需要调用 getWeather("北京")

Spring AI 执行 weatherTools.getWeather("北京")

将结果 "北京今天晴,26度" 传回 LLM

LLM 生成最终回复: "北京今天天气晴朗,温度26度"

@Tool 注解参数

参数说明
description工具描述,AI 根据它决定何时调用
name工具名(默认用方法名)

@ToolParam 注解

1
2
3
4
@Tool(description = "获取股票价格")
public double getStockPrice(
@ToolParam("股票代码,如 AAPL") String symbol
) { ... }

多工具协作

1
2
3
4
// 注册多个工具
ChatClient chatClient = builder
.defaultTools(weatherTools, newsTools, calculatorTools)
.build();

AI 会根据问题自行决定调用哪一个或多个。


流式调用中的 Function Calling

1
2
3
4
5
6
7
8
chatClient.prompt()
.user("帮我查天气并订阅")
.stream()
.subscribe(
chunk -> { /* 处理流式返回 */ },
error -> { /* 错误处理 */ },
() -> { /* 完成 */ }
);