函数调用

您可以使用OpenAiChatModel并让 OpenAI 模型智能地选择输出包含参数的 JSON 对象,以调用一个或多个已注册的函数。 这允许您将 LLM 功能与外部工具和 API 连接起来。 OpenAI 模型经过训练,可以检测何时应该调用函数,并使用符合函数签名的 JSON 进行响应。spring-doc.cadn.net.cn

OpenAI API 不直接调用该函数;相反,该模型会生成 JSON,您可以使用该 JSON 在代码中调用函数,并将结果返回给模型以完成对话。spring-doc.cadn.net.cn

Spring AI 提供了灵活且用户友好的方法来注册和调用自定义函数。 通常,自定义函数需要提供一个函数name,description和函数调用signature(作为 JSON 架构)让模型知道函数需要哪些参数。这description帮助模型了解何时调用函数。spring-doc.cadn.net.cn

作为开发人员,您需要实现一个函数,该函数采用从 AI 模型发送的函数调用参数,并将结果返回给模型。您的函数可以反过来调用其他第三方服务来提供结果。spring-doc.cadn.net.cn

Spring AI 使这就像定义@Bean定义,该定义返回一个java.util.Function并在调用ChatModel.spring-doc.cadn.net.cn

在后台, Spring 使用适当的适配器代码包装您的 POJO(函数),以便与 AI 模型进行交互,从而避免编写繁琐的样板代码。 底层基础架构的基础是 FunctionCallback.java 接口和配套的 Builder 实用程序类,以简化 Java 回调函数的实现和注册。spring-doc.cadn.net.cn

运作方式

假设我们希望 AI 模型使用它没有的信息进行响应,例如,给定位置的当前温度。spring-doc.cadn.net.cn

我们可以为 AI 模型提供有关我们自己的函数的元数据,它可以在处理您的提示时使用这些元数据来检索该信息。spring-doc.cadn.net.cn

例如,如果在处理提示期间,AI 模型确定它需要有关给定位置温度的其他信息,它将启动服务器端生成的请求/响应交互。AI 模型调用客户端函数。 AI 模型以 JSON 格式提供方法调用详细信息,客户端负责执行该函数并返回响应。spring-doc.cadn.net.cn

模型-客户端交互在 Spring AI 函数调用流程图中进行了说明。spring-doc.cadn.net.cn

Spring AI 大大简化了您需要编写以支持函数调用的代码。 它为您代理函数调用对话。 您可以简单地将函数定义作为@Bean,然后在提示选项中提供函数的 Bean 名称。 您还可以在提示符中引用多个函数 Bean 名称。spring-doc.cadn.net.cn

快速开始

让我们创建一个聊天机器人,通过调用我们自己的函数来回答问题。 为了支持聊天机器人的响应,我们将注册自己的函数,该函数获取一个位置并返回该位置的当前天气。spring-doc.cadn.net.cn

当模型需要回答诸如"What’s the weather like in Boston?"AI 模型将调用客户端,提供 location 值作为要传递给函数的参数。这种类似 RPC 的数据以 JSON 形式传递。spring-doc.cadn.net.cn

我们的函数调用一些基于 SaaS 的天气服务 API,并将天气响应返回给模型以完成对话。在此示例中,我们将使用一个名为MockWeatherService对不同位置的温度进行硬编码。spring-doc.cadn.net.cn

以下内容MockWeatherService.java表示天气服务 API:spring-doc.cadn.net.cn

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);
	}
}

将函数注册为 Bean

使用 OpenAiChatModel 自动配置,您可以通过多种方式在 Spring 上下文中将自定义函数注册为 bean。spring-doc.cadn.net.cn

我们首先介绍对 POJO 最友好的选项。spring-doc.cadn.net.cn

普通 Java 函数

在此方法中,您将定义一个@Bean就像你对待任何其他 Spring 托管对象一样。spring-doc.cadn.net.cn

在内部,Spring AIChatModel将创建一个FunctionCallback这增加了通过 AI 模型调用它的逻辑。 的名称@Bean作为ChatOption.spring-doc.cadn.net.cn

@Configuration
static class Config {

	@Bean
	@Description("Get the weather in location") // function description
	public Function<MockWeatherService.Request, MockWeatherService.Response> currentWeather() {
		return new MockWeatherService();
	}

}

@Descriptionannotation 是可选的,它提供了一个函数描述,可帮助模型了解何时调用该函数。这是一个重要的属性,可帮助 AI 模型确定要调用的客户端函数。spring-doc.cadn.net.cn

提供函数描述的另一种方法是使用@JsonClassDescription注解MockWeatherService.Request:spring-doc.cadn.net.cn

@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) {}

最佳实践是使用信息对请求对象进行注释,以便为该函数生成的 JSON 架构尽可能具有描述性,以帮助 AI 模型选择要调用的正确函数。spring-doc.cadn.net.cn

FunctionCallback 包装器

注册函数的另一种方法是创建一个FunctionCallback喜欢这个:spring-doc.cadn.net.cn

@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) function input type
        .build();
	}

}

它包装了第三方MockWeatherService函数并将其注册为CurrentWeather函数替换为OpenAiChatModel. 它还提供用于为函数调用生成 JSON 架构的描述 (2) 和输入类型 (3)。spring-doc.cadn.net.cn

默认情况下,响应转换器执行 Response 对象的 JSON 序列化。
FunctionCallback内部根据MockWeatherService.Request类。

在 Chat Options 中指定函数

要让模型知道并调用您的CurrentWeather函数,以便在提示请求中启用它:spring-doc.cadn.net.cn

OpenAiChatModel chatModel = ...

UserMessage userMessage = new UserMessage("What's the weather like in San Francisco, Tokyo, and Paris?");

ChatResponse response = this.chatModel.call(new Prompt(this.userMessage,
		OpenAiChatOptions.builder().withFunction("CurrentWeather").build())); // Enable the function

logger.info("Response: {}", response);

上述用户问题将触发对CurrentWeather函数(每个城市一个),最终响应将如下所示:spring-doc.cadn.net.cn

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

使用提示选项注册/调用函数

除了自动配置之外,您还可以使用Prompt请求:spring-doc.cadn.net.cn

OpenAiChatModel chatModel = ...

UserMessage userMessage = new UserMessage("What's the weather like in San Francisco, Tokyo, and Paris?");

var promptOptions = OpenAiChatOptions.builder()
	.withFunctionCallbacks(List.of(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) function input type
        .build())) // function code
	.build();

ChatResponse response = this.chatModel.call(new Prompt(this.userMessage, this.promptOptions));
默认情况下,在此请求的持续时间内启用提示内注册的函数。

这种方法允许根据用户输入动态选择要调用的不同函数。spring-doc.cadn.net.cn

FunctionCallbackInPromptIT.java 集成测试提供了一个完整的示例,说明如何使用OpenAiChatModel并在提示请求中使用它。spring-doc.cadn.net.cn

工具上下文支持

Spring AI 现在支持通过工具上下文将额外的上下文信息传递给函数回调。此功能允许您提供可在函数执行中使用的额外数据,从而增强函数调用的灵活性和能力。spring-doc.cadn.net.cn

作为java.util.BiFunction.这ToolContextcontains 作为不可变的Map<String,Object>允许您访问键值对。spring-doc.cadn.net.cn

如何使用工具上下文

您可以在构建聊天选项时设置工具上下文,并将 BiFunction 用于回调:spring-doc.cadn.net.cn

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);
    };

OpenAiChatOptions options = OpenAiChatOptions.builder()
    .withModel(OpenAiApi.ChatModel.GPT_4_O.getValue())
    .withFunctionCallbacks(List.of(FunctionCallback.builder()
        .function("getCurrentWeather", this.weatherFunction)
        .description("Get the weather in location")
        .inputType(MockWeatherService.Request.class)
        .build()))
    .withToolContext(Map.of("sessionId", "123", "userId", "user456"))
    .build();

在此示例中,weatherFunction定义为将请求和工具上下文作为参数的 BiFunction。这允许您直接在函数 logic中访问上下文。spring-doc.cadn.net.cn

然后,您可以在调用聊天模型时使用以下选项:spring-doc.cadn.net.cn

UserMessage userMessage = new UserMessage("What's the weather like in San Francisco, Tokyo, and Paris?");
ChatResponse response = chatModel.call(new Prompt(List.of(this.userMessage), options));

这种方法允许您将特定于会话或用户的信息传递给您的函数,从而实现更多上下文和个性化的响应。spring-doc.cadn.net.cn

附录:

Spring AI 函数调用流程

下图说明了OpenAiChatModel函数调用:spring-doc.cadn.net.cn

OpenAI API 函数调用流程

下图说明了 OpenAI API 函数调用的流程:spring-doc.cadn.net.cn

OpenAiApiToolFunctionCallIT.java 提供了有关如何使用 OpenAI API 函数调用的完整示例。 它基于 OpenAI 函数调用教程spring-doc.cadn.net.cn