函数调用 API
本页面描述了旧版本的 Function Calling API,该版本已被弃用,并计划在下一个版本中移除。当前版本可在 Tool Calling 获取。更多信息请参阅 迁移指南。
AI 模型中的功能支持集成,允许模型请求执行客户端功能,从而根据需要动态访问必要信息或执行任务。
Spring AI 目前支持以下 AI 模型的工具/函数调用:
-
Anthropic Claude: 请参考 Anthropic Claude 工具/函数调用。
-
Azure OpenAI: 请参考 Azure OpenAI 工具/函数调用。
-
Amazon Bedrock Converse: 请参考 Amazon Bedrock Converse 工具/函数调用。
-
Google VertexAI Gemini: 请参考 Vertex AI Gemini 工具/函数调用。
-
Groq: 请参考 Groq 工具/函数调用。
-
Mistral AI: 请参考 Mistral AI 工具/函数调用。
-
Ollama: 请参考 Ollama 工具/函数调用
-
OpenAI: 请参考 OpenAI 工具/函数调用。
你可以将自定义的 Java 函数注册到 ChatClient
中,并让 AI 模型智能地选择输出一个包含参数的 JSON 对象,以调用一个或多个已注册的函数。这使你可以将 LLM 的能力与外部工具和 API 连接起来。AI 模型经过训练,能够检测何时应该调用函数,并返回符合函数签名的 JSON 响应。
API 并不会直接调用函数;相反,模型会生成 JSON,你可以用它在代码中调用函数,并将结果返回给模型以完成对话。
Spring AI 提供了灵活且用户友好的方式来注册和调用自定义函数。通常,自定义函数需要提供一个函数 name
、description
和函数调用 signature
(作为 JSON schema),以便模型知道函数期望的参数。description
帮助模型理解何时调用该函数。
作为一名开发者,你需要实现一个函数,该函数接收从 AI 模型发送的函数调用参数,并将结果返回给模型。你的函数可以进一步调用其他第三方服务以提供结果。
Spring AI 使这一过程变得非常简单,只需定义一个返回 java.util.Function
的 @Bean
定义,并在调用 ChatClient
时将 bean 名称作为选项提供,或者在提示请求中动态注册该函数即可。
在底层,Spring 将你的 POJO(函数)用适当的适配器代码包装起来,使其能够与 AI 模型进行交互,从而省去了编写繁琐样板代码的麻烦。底层基础设施的基础是 FunctionCallback.java 接口及其配套的 Builder 工具类,它们简化了 Java 回调函数的实现和注册过程。
工作原理
假设我们希望 AI 模型响应它没有的信息,例如某个给定位置的当前温度。
我们可以向 AI 模型提供关于我们自己的函数的元数据,这些元数据可以在模型处理你的提示时用于检索相关信息。
例如,在处理一个提示时,如果 AI 模型确定需要某个地点的温度信息,它将启动一个服务器端生成的请求/响应交互。AI 模型不会直接返回最终响应消息,而是返回一个特殊的 Tool Call 请求,提供函数名称和参数(以 JSON 格式)。客户端的责任是处理此消息,执行指定的函数,并将响应作为 Tool Response 消息返回给 AI 模型。
Spring AI 极大地简化了支持函数调用所需的代码编写。它为你代理了函数调用的对话。你只需将你的函数定义作为一个 @Bean
提供,然后在你的提示选项中提供函数的 bean 名称,或者直接将函数作为参数传递到你的提示请求选项中。
你也可以在你的提示中引用多个函数 bean 名称。
示例用例
让我们定义一个简单的用例,作为解释函数调用工作原理的示例。我们将创建一个通过调用我们自己的函数来回答问题的聊天机器人。为了支持聊天机器人的响应,我们将注册一个我们自己的函数,该函数接收一个位置并返回该位置的当前天气。
当模型需要回答诸如 "波士顿的天气如何?"
这样的问题时,AI 模型将调用客户端,并将位置值作为参数传递给函数。这种类似于 RPC 的数据以 JSON 格式传递。
我们的函数调用了一些基于 SaaS 的天气服务 API,并将天气响应返回给模型以完成对话。在这个示例中,我们将使用一个名为 MockWeatherService
的简单实现,该实现硬编码了不同地点的温度。
以下 MockWeatherService
类表示天气服务 API:
- Java
- Kotlin
public class MockWeatherService implements Function<Request, Response> {
public enum Unit { C, F }
public record Request(String location, Unit unit) {}
public record Response(double temp, Unit unit) {}
public Response apply(Request request) {
return new Response(30.0, Unit.C);
}
}
class MockWeatherService : Function1<Request, Response> {
override fun invoke(request: Request) = Response(30.0, Unit.C)
}
enum class Unit { C, F }
data class Request(val location: String, val unit: Unit) {}
data class Response(val temp: Double, val unit: Unit) {}
服务器端注册
函数作为 Beans
Spring AI 提供了多种方式将自定义函数注册为 Spring 上下文中的 bean。
我们首先描述最符合 POJO 的选项。
普通函数
在这种方法中,你可以在应用程序上下文中定义一个 @Bean
,就像定义其他 Spring 管理的对象一样。
在内部,Spring AI 的 ChatModel
会创建一个 FunctionCallback
的实例,该实例添加了通过 AI 模型调用它的逻辑。@Bean
的名称用作函数名称。
- Java
- Kotlin
@Configuration
static class Config {
@Bean
@Description("Get the weather in location") // function description
public Function<MockWeatherService.Request, MockWeatherService.Response> currentWeather() {
return new MockWeatherService();
}
}
@Configuration
class Config {
@Bean
@Description("Get the weather in location") // function description
fun currentWeather(): (Request) -> Response = MockWeatherService()
}
@Description
注解是可选的,它提供了一个函数描述,帮助模型理解何时调用该函数。设置这一属性非常重要,因为它可以帮助 AI 模型确定要调用哪个客户端函数。
另一种提供函数描述的方法是使用 @JsonClassDescription
注解在 MockWeatherService.Request
上:
- Java
- Kotlin
@Configuration
static class Config {
@Bean
public Function<Request, Response> currentWeather() { // bean name as function name
return new MockWeatherService();
}
}
@JsonClassDescription("Get the weather in location") // function description
public record Request(String location, Unit unit) {}
@Configuration
class Config {
@Bean
fun currentWeather(): (Request) -> Response { // bean name as function name
return MockWeatherService()
}
}
@JsonClassDescription("Get the weather in location") // function description
data class Request(val location: String, val unit: Unit)
最佳实践是在请求对象上添加注释信息,使得该函数生成的 JSON schema 尽可能具有描述性,以帮助 AI 模型选择正确的函数进行调用。
FunctionCallback
另一种注册函数的方法是创建一个 FunctionCallback
,如下所示:
- Java
- Kotlin
@Configuration
static class Config {
@Bean
public FunctionCallback weatherFunctionInfo() {
return FunctionCallback.builder()
.function("CurrentWeather", new MockWeatherService()) // (1) function name and instance
.description("Get the weather in location") // (2) function description
.inputType(MockWeatherService.Request.class) // (3) input type to build the JSON schema
.build();
}
}
import org.springframework.ai.model.function.withInputType
@Configuration
class Config {
@Bean
fun weatherFunctionInfo(): FunctionCallback {
return FunctionCallback.builder()
.function("CurrentWeather", MockWeatherService()) // (1) function name and instance
.description("Get the weather in location") // (2) function description
// (3) Required due to Kotlin SAM conversion being an opaque lambda
.inputType<MockWeatherService.Request>()
.build();
}
}
它封装了第三方 MockWeatherService
函数,并将其注册为 ChatClient
的 CurrentWeather
函数。它还提供了一个描述(2)和一个可选的响应转换器,用于将响应转换为模型期望的文本格式。
默认情况下,响应转换器会对 Response 对象执行 JSON 序列化。
FunctionCallback.Builder
内部会根据 MockWeatherService.Request
类来解析函数调用签名。
通过 bean 名称启用功能
为了让模型知道并调用你的 CurrentWeather
函数,你需要在提示请求中启用它:
ChatClient chatClient = ...
ChatResponse response = this.chatClient.prompt("What's the weather like in San Francisco, Tokyo, and Paris?")
.functions("CurrentWeather") // Enable the function
.call().
chatResponse();
logger.info("Response: {}", response);
上述用户问题将触发 3 次对 CurrentWeather
函数的调用(每个城市一次),最终响应将类似于以下内容:
Here is the current weather for the requested cities:
- San Francisco, CA: 30.0°C
- Tokyo, Japan: 10.0°C
- Paris, France: 15.0°C
FunctionCallbackWithPlainFunctionBeanIT.java 测试演示了这种方法。
客户端注册
除了自动配置外,您还可以动态注册回调函数。您可以使用函数调用或方法调用的方式,将函数注册到您的 ChatClient
或 ChatModel
请求中。
客户端注册使您能够默认注册函数。
函数调用
ChatClient chatClient = ...
ChatResponse response = this.chatClient.prompt("What's the weather like in San Francisco, Tokyo, and Paris?")
.functions(FunctionCallback.builder()
.function("currentWeather", (Request request) -> new Response(30.0, Unit.C)) // (1) function name and instance
.description("Get the weather in location") // (2) function description
.inputType(MockWeatherService.Request.class) // (3) input type to build the JSON schema
.build())
.call()
.chatResponse();
在此请求期间,动态函数默认启用。
这种方法允许根据用户输入动态选择不同的函数进行调用。
FunctionCallbackInPromptIT.java 集成测试提供了一个完整的示例,展示了如何向 ChatClient
注册一个函数并在提示请求中使用它。
方法调用
MethodInvokingFunctionCallback
允许通过反射调用方法,同时自动处理 JSON 模式生成和参数转换。它在将 Java 方法集成为 AI 模型交互中的可调用函数时特别有用。
MethodInvokingFunctionCallback
实现了 FunctionCallback
接口,并提供以下功能:
-
自动生成方法参数的 JSON schema
-
支持静态方法和实例方法
-
任意数量的参数(包括无参数)和返回值(包括 void)
-
任意参数/返回类型(基本类型、对象、集合)
-
对
ToolContext
参数的特殊处理
你需要使用 FunctionCallback.Builder
来创建 MethodInvokingFunctionCallback
,如下所示:
// Create using builder pattern
FunctionCallback methodInvokingCallback = FunctionCallback.builder()
.method("MethodName", Class<?>...argumentTypes) // The method to invoke and its argument types
.description("Function calling description") // Hints the AI to know when to call this method
.targetObject(targetObject) // Required instance methods for static methods use targetClass
.build();
以下是一些使用示例:
- Static Method Invocation
- Instance Method with ToolContext
public class WeatherService {
public static String getWeather(String city, TemperatureUnit unit) {
return "Temperature in " + city + ": 20" + unit;
}
}
// Usage
FunctionCallback callback = FunctionCallback.builder()
.method("getWeather", String.class, TemperatureUnit.class)
.description("Get weather information for a city")
.targetClass(WeatherService.class)
.build();
public class DeviceController {
public void setDeviceState(String deviceId, boolean state, ToolContext context) {
Map<String, Object> contextData = context.getContext();
// Implementation using context data
}
}
// Usage
DeviceController controller = new DeviceController();
String response = ChatClient.create(chatModel).prompt()
.user("Turn on the living room lights")
.functions(FunctionCallback.builder()
.method("setDeviceState", String.class,boolean.class,ToolContext.class)
.description("Control device state")
.targetObject(controller)
.build())
.toolContext(Map.of("location", "home"))
.call()
.content();
OpenAiChatClientMethodInvokingFunctionCallbackIT 集成测试提供了如何使用 FunctionCallback.Builder
创建方法调用 FunctionCallbacks
的更多示例。
工具上下文
Spring AI 现在支持通过工具上下文向函数回调传递额外的上下文信息。此功能允许您提供额外的、由用户提供的数据,这些数据可以在函数执行期间与 AI 模型传递的函数参数一起使用。
ToolContext 类提供了一种传递额外上下文信息的方式。
使用工具上下文
在函数调用的情况下,上下文信息作为 java.util.BiFunction
的第二个参数传递。
在方法调用中,上下文信息会作为 ToolContext
类型的方法参数传递。
函数调用
在构建聊天选项时,你可以设置工具上下文,并使用 BiFunction
作为回调:
chatOptions.setToolContext(toolContext);
chatOptions.setCallback((response, context) -> {
// 处理响应和上下文
return null;
});
BiFunction<MockWeatherService.Request, ToolContext, MockWeatherService.Response> weatherFunction =
(request, toolContext) -> {
String sessionId = (String) toolContext.getContext().get("sessionId");
String userId = (String) toolContext.getContext().get("userId");
// Use sessionId and userId in your function logic
double temperature = 0;
if (request.location().contains("Paris")) {
temperature = 15;
}
else if (request.location().contains("Tokyo")) {
temperature = 10;
}
else if (request.location().contains("San Francisco")) {
temperature = 30;
}
return new MockWeatherService.Response(temperature, 15, 20, 2, 53, 45, MockWeatherService.Unit.C);
};
ChatResponse response = chatClient.prompt("What's the weather like in San Francisco, Tokyo, and Paris?")
.functions(FunctionCallback.builder()
.function("getCurrentWeather", this.weatherFunction)
.description("Get the weather in location")
.inputType(MockWeatherService.Request.class)
.build())
.toolContext(Map.of("sessionId", "1234", "userId", "5678"))
.call()
.chatResponse();
在这个示例中,weatherFunction
被定义为一个 BiFunction,它接收请求和工具上下文作为参数。这使得你可以直接在函数逻辑中访问上下文。
这种方法允许你将特定会话或特定用户的信息传递给函数,从而实现更具上下文性和个性化的响应。
方法调用
public class DeviceController {
public void setDeviceState(String deviceId, boolean state, ToolContext context) {
Map<String, Object> contextData = context.getContext();
// Implementation using context data
}
}
// Usage
DeviceController controller = new DeviceController();
String response = ChatClient.create(chatModel).prompt()
.user("Turn on the living room lights")
.functions(FunctionCallback.builder()
.method("setDeviceState", String.class,boolean.class,ToolContext.class)
.description("Control device state")
.targetObject(controller)
.build())
.toolContext(Map.of("location", "home"))
.call()
.content();
章节摘要
📄️ 函数回调 API(已弃用)
Spring AI 中的 FunctionCallback 接口提供了一种标准化的方式来实现大语言模型(LLM)的函数调用功能。它允许开发者注册自定义函数,当 AI 模型在提示中检测到特定条件或意图时,可以调用这些函数。
📄️ 迁移到 ToolCallback API
本指南帮助您从已弃用的 FunctionCallback API 迁移到 Spring AI 中的新 ToolCallback API。有关新 API 的更多信息,请查阅 Tools Calling 文档。