工具调用

工具调用(也称为_函数调用_)是AI应用程序中常见的模式,它允许模型与一组API或_工具_进行交互,从而增强其能力。 工具主要用于:

  • 信息检索。此类工具可用于从外部源(如数据库、Web服务、文件系统或Web搜索引擎)检索信息。目标是增强模型的知识,使其能够回答否则无法回答的问题。因此,它们可用于检索增强生成(RAG)场景。例如,一个工具可以用于检索给定位置的当前天气,检索最新的新闻文章,或查询数据库以获取特定记录。

  • 采取行动。此类工具可用于在软件系统中采取行动,例如发送电子邮件、在数据库中创建新记录、提交表单或触发工作流。目标是自动化原本需要人工干预或显式编程的任务。例如,一个工具可以用于为与聊天机器人交互的客户预订航班,填写网页上的表单,或在代码生成场景中基于自动化测试(TDD)实现Java类。

尽管我们通常将_工具调用_称为模型能力,但实际上由客户端应用程序提供工具调用逻辑。模型只能请求工具调用并提供输入参数,而应用程序负责根据输入参数执行工具调用并返回结果。模型永远无法访问作为工具提供的任何API,这是一个关键的安全考虑。 Spring AI提供了便捷的API来定义工具、从模型解析工具调用请求并执行工具调用。以下部分概述了Spring AI中的工具调用功能。

查看 聊天模型比较 以了解哪些AI模型支持工具调用。

请按照指南从已弃用的 FunctionCallback 迁移到 ToolCallback API

快速开始

让我们看看如何在Spring AI中开始使用工具调用。我们将实现两个简单的工具:一个用于信息检索,一个用于采取行动。信息检索工具将用于获取用户时区中的当前日期和时间。行动工具将用于在指定时间设置闹钟。

信息检索

AI模型无法访问实时信息。任何假设了解当前日期或天气预报等信息的问题都无法由模型回答。但是,我们可以提供一个可以检索此信息的工具,并让模型在需要访问实时信息时调用此工具。

让我们在 DateTimeTools 类中实现一个工具,以获取用户时区中的当前日期和时间。该工具不带任何参数。Spring Framework的 LocaleContextHolder 可以提供用户的时区。该工具将被定义为用 @Tool 注解的方法。为了帮助模型理解是否以及何时调用此工具,我们将提供工具功能的详细描述。

import java.time.LocalDateTime;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.context.i18n.LocaleContextHolder;

class DateTimeTools {

    @Tool(description = "Get the current date and time in the user's timezone")
    String getCurrentDateTime() {
        return LocalDateTime.now().atZone(LocaleContextHolder.getTimeZone().toZoneId()).toString();
    }

}

接下来,让我们将工具提供给模型。在此示例中,我们将使用 ChatClient 与模型交互。我们将通过 tools() 方法传递 DateTimeTools 的实例来向模型提供工具。当模型需要知道当前日期和时间时,它将请求调用该工具。在内部,ChatClient 将调用该工具并将结果返回给模型,然后模型将使用工具调用结果生成对原始问题的最终响应。

ChatModel chatModel = ...

String response = ChatClient.create(chatModel)
        .prompt("What day is tomorrow?")
        .tools(new DateTimeTools())
        .call()
        .content();

System.out.println(response);

输出将类似于:

Tomorrow is 2015-10-21.

您可以再次尝试问同样的问题。这次,不要将工具提供给模型。输出将类似于:

I am an AI and do not have access to real-time information. Please provide the current date so I can accurately determine what day tomorrow will be.

没有该工具,模型不知道如何回答问题,因为它无法确定当前日期和时间。

采取行动

AI模型可用于生成实现某些目标的计划。例如,模型可以生成预订丹麦旅行的计划。但是,模型无法执行该计划。这就是工具的作用:它们可以用于执行模型生成的计划。

在前面的示例中,我们使用工具来确定当前日期和时间。在此示例中,我们将定义第二个工具,用于在特定时间设置闹钟。目标是在从现在起10分钟后设置闹钟,因此我们需要将这两个工具都提供给模型来完成此任务。

我们将新工具添加到与以前相同的 DateTimeTools 类中。新工具将接受一个参数,即ISO-8601格式的时间。然后,该工具将向控制台打印一条消息,指示已为给定时间设置了闹钟。与以前一样,该工具被定义为用 @Tool 注解的方法,我们还使用它来提供详细描述,以帮助模型理解何时以及如何使用该工具。

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.context.i18n.LocaleContextHolder;

class DateTimeTools {

    @Tool(description = "Get the current date and time in the user's timezone")
    String getCurrentDateTime() {
        return LocalDateTime.now().atZone(LocaleContextHolder.getTimeZone().toZoneId()).toString();
    }

    @Tool(description = "Set a user alarm for the given time, provided in ISO-8601 format")
    void setAlarm(String time) {
        LocalDateTime alarmTime = LocalDateTime.parse(time, DateTimeFormatter.ISO_DATE_TIME);
        System.out.println("Alarm set for " + alarmTime);
    }

}

接下来,让我们将这两个工具都提供给模型。我们将使用 ChatClient 与模型交互。我们将通过 tools() 方法传递 DateTimeTools 的实例来向模型提供工具。当我们要求从现在起10分钟后设置闹钟时,模型将首先需要知道当前日期和时间。然后,它将使用当前日期和时间来计算闹钟时间。最后,它将使用闹钟工具设置闹钟。在内部,ChatClient 将处理模型发出的任何工具调用请求,并将任何工具调用执行结果发送回模型,以便模型可以生成最终响应。

ChatModel chatModel = ...

String response = ChatClient.create(chatModel)
        .prompt("Can you set an alarm 10 minutes from now?")
        .tools(new DateTimeTools())
        .call()
        .content();

System.out.println(response);

在应用程序日志中,您可以检查闹钟是否已在正确时间设置。

概述

Spring AI通过一组灵活的抽象支持工具调用,允许您以一致的方式定义、解析和执行工具。本节概述了Spring AI中工具调用的主要概念和组件。

tool calling 01
  1. 当我们要将工具提供给模型时,我们将其定义包含在聊天请求中。每个工具定义都包含名称、描述和输入参数的Schema。

  2. 当模型决定调用工具时,它会发送一个响应,其中包含工具名称和根据定义的Schema建模的输入参数。

  3. 应用程序负责使用工具名称识别并执行带有提供输入参数的工具。

  4. 工具调用的结果由应用程序处理。

  5. 应用程序将工具调用结果发送回模型。

  6. 模型使用工具调用结果作为附加上下文生成最终响应。

工具是工具调用的构建块,它们由 ToolCallback 接口建模。Spring AI提供了内置支持,用于从方法和函数中指定 ToolCallback(s),但您始终可以定义自己的 ToolCallback 实现来支持更多用例。

ChatModel 实现透明地将工具调用请求分派给相应的 ToolCallback 实现,并将工具调用结果发送回模型,最终由模型生成最终响应。它们通过 ToolCallingManager 接口来实现这一点,该接口负责管理工具执行生命周期。

ChatClientChatModel 都接受 ToolCallback 对象列表,以使工具可供模型和最终执行它们的 ToolCallingManager 使用。

除了直接传递 ToolCallback 对象之外,您还可以传递工具名称列表,这些名称将使用 ToolCallbackResolver 接口动态解析。

以下部分将更详细地介绍所有这些概念和API,包括如何自定义和扩展它们以支持更多用例。

方法作为工具

Spring AI提供了内置支持,用于通过两种方式从方法中指定工具(即 ToolCallback(s)):

  • 声明式地,使用 @Tool 注解

  • 编程式地,使用低级 MethodToolCallback 实现。

声明式规范:@Tool

您可以通过使用 @Tool 注解方法将其转换为工具。

class DateTimeTools {

    @Tool(description = "Get the current date and time in the user's timezone")
    String getCurrentDateTime() {
        return LocalDateTime.now().atZone(LocaleContextHolder.getTimeZone().toZoneId()).toString();
    }

}

@Tool 注解允许您提供有关工具的关键信息:

  • name:工具的名称。如果未提供,将使用方法名称。AI模型使用此名称在调用工具时识别它。因此,不允许在同一个类中存在两个同名的工具。在特定聊天请求中,名称在所有可供模型使用的工具中必须是唯一的。

  • description:工具的描述,模型可以使用它来理解何时以及如何调用工具。如果未提供,将使用方法名称作为工具描述。但是,强烈建议提供详细描述,因为这对于模型理解工具目的和如何使用它至关重要。未能提供良好描述可能导致模型不该使用工具时使用,或错误地使用。

  • returnDirect:工具结果是直接返回给客户端还是传递回模型。有关更多详细信息,请参见 直接返回

  • resultConverter:用于将工具调用结果转换为 String 对象以发送回AI模型的 ToolCallResultConverter 实现。有关更多详细信息,请参见 结果转换

该方法可以是静态或实例方法,并且可以具有任何可见性(public、protected、package-private或private)。包含该方法的类可以是顶级类或嵌套类,并且也可以具有任何可见性(只要它在您计划实例化它的地方可访问)。

Spring AI为 @Tool 注解方法提供了AOT编译的内置支持,只要包含方法的类是Spring bean(例如 @Component)。否则,您需要为GraalVM编译器提供必要的配置。例如,通过使用 @RegisterReflection(memberCategories = MemberCategory.INVOKE_DECLARED_METHODS) 注解该类。

您可以为方法定义任意数量的参数(包括无参数),类型可以是大多数类型(基本类型、POJO、枚举、列表、数组、映射等)。同样,方法可以返回大多数类型,包括 void。如果方法返回一个值,则返回类型必须是可序列化类型,因为结果将被序列化并发送回模型。

某些类型不受支持。有关更多详细信息,请参见 方法工具限制

Spring AI将自动为 @Tool 注解方法的输入参数生成JSON Schema。Schema由模型用于理解如何调用工具并准备工具请求。@ToolParam 注解可用于提供有关输入参数的附加信息,例如描述或参数是必需还是可选。默认情况下,所有输入参数都被视为必需。

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

class DateTimeTools {

    @Tool(description = "Set a user alarm for the given time")
    void setAlarm(@ToolParam(description = "Time in ISO-8601 format") String time) {
        LocalDateTime alarmTime = LocalDateTime.parse(time, DateTimeFormatter.ISO_DATE_TIME);
        System.out.println("Alarm set for " + alarmTime);
    }

}

@ToolParam 注解允许您提供有关工具参数的关键信息:

  • description:参数的描述,模型可以使用它更好地理解如何使用它。例如,参数应采用什么格式,允许什么值等等。

  • required:参数是必需还是可选。默认情况下,所有参数都被视为必需。

如果参数被 @Nullable 注解,则它将被视为可选,除非使用 @ToolParam 注解明确标记为必需。

除了 @ToolParam 注解,您还可以使用Swagger的 @Schema 注解或Jackson的 @JsonProperty。有关更多详细信息,请参见 JSON Schema

将工具添加到 ChatClient

当使用声明式规范方法时,您可以在调用 ChatClient 时将工具类实例传递给 tools() 方法。此类工具仅适用于它们所添加的特定聊天请求。

ChatClient.create(chatModel)
    .prompt("What day is tomorrow?")
    .tools(new DateTimeTools())
    .call()
    .content();

在底层,ChatClient 将从工具类实例中的每个 @Tool 注解方法生成一个 ToolCallback 并将其传递给模型。如果您更喜欢自己生成 ToolCallback(s),可以使用 ToolCallbacks 实用程序类。

ToolCallback[] dateTimeTools = ToolCallbacks.from(new DateTimeTools());

将默认工具添加到 ChatClient

当使用声明式规范方法时,您可以通过将工具类实例传递给 defaultTools() 方法来将默认工具添加到 ChatClient.Builder。 如果同时提供了默认工具和运行时工具,则运行时工具将完全覆盖默认工具。

默认工具在由同一 ChatClient.Builder 构建的所有 ChatClient 实例执行的所有聊天请求中共享。它们对于跨不同聊天请求常用工具很有用,但如果不小心使用,也可能很危险,冒着在不应该使用时使其可用的风险。

ChatModel chatModel = ...
ChatClient chatClient = ChatClient.builder(chatModel)
    .defaultTools(new DateTimeTools())
    .build();

将工具添加到 ChatModel

当使用声明式规范方法时,您可以将工具类实例传递给您用于调用 ChatModelToolCallingChatOptionstoolCallbacks() 方法。此类工具仅适用于它们所添加的特定聊天请求。

ChatModel chatModel = ...
ToolCallback[] dateTimeTools = ToolCallbacks.from(new DateTimeTools());
ChatOptions chatOptions = ToolCallingChatOptions.builder()
    .toolCallbacks(dateTimeTools)
    .build();
Prompt prompt = new Prompt("What day is tomorrow?", chatOptions);
chatModel.call(prompt);

将默认工具添加到 ChatModel

当使用声明式规范方法时,您可以在构建 ChatModel 时通过将工具类实例传递给用于创建 ChatModelToolCallingChatOptions 实例的 toolCallbacks() 方法来添加默认工具。 如果同时提供了默认工具和运行时工具,则运行时工具将完全覆盖默认工具。

默认工具在该 ChatModel 实例执行的所有聊天请求中共享。它们对于跨不同聊天请求常用工具很有用,但如果不小心使用,也可能很危险,冒着在不应该使用时使其可用的风险。

ToolCallback[] dateTimeTools = ToolCallbacks.from(new DateTimeTools());
ChatModel chatModel = OllamaChatModel.builder()
    .ollamaApi(OllamaApi.builder().build())
    .defaultOptions(ToolCallingChatOptions.builder()
            .toolCallbacks(dateTimeTools)
            .build())
    .build();

编程式规范:MethodToolCallback

您可以通过编程式构建 MethodToolCallback 将方法转换为工具。

class DateTimeTools {

    String getCurrentDateTime() {
        return LocalDateTime.now().atZone(LocaleContextHolder.getTimeZone().toZoneId()).toString();
    }

}

MethodToolCallback.Builder 允许您构建 MethodToolCallback 实例并提供有关工具的关键信息:

  • toolDefinition:定义工具名称、描述和输入Schema的 ToolDefinition 实例。您可以使用 ToolDefinition.Builder 类构建它。必需。

  • toolMetadata:定义附加设置(例如结果是否应直接返回给客户端以及要使用的结果转换器)的 ToolMetadata 实例。您可以使用 ToolMetadata.Builder 类构建它。

  • toolMethod:表示工具方法的 Method 实例。必需。

  • toolObject:包含工具方法的对象实例。如果方法是静态的,则可以省略此参数。

  • toolCallResultConverter:用于将工具调用结果转换为 String 对象以发送回AI模型的 ToolCallResultConverter 实例。如果未提供,将使用默认转换器 (DefaultToolCallResultConverter)。

ToolDefinition.Builder 允许您构建 ToolDefinition 实例并定义工具名称、描述和输入Schema:

  • name:工具的名称。如果未提供,将使用方法名称。AI模型使用此名称在调用工具时识别它。因此,不允许在同一个类中存在两个同名的工具。在特定聊天请求中,名称在所有可供模型使用的工具中必须是唯一的。

  • description:工具的描述,模型可以使用它来理解何时以及如何调用工具。如果未提供,将使用方法名称作为工具描述。但是,强烈建议提供详细描述,因为这对于模型理解工具目的和如何使用它至关重要。未能提供良好描述可能导致模型不该使用工具时使用,或错误地使用。

  • inputSchema:工具输入参数的JSON Schema。如果未提供,Schema将根据方法参数自动生成。您可以使用 @ToolParam 注解提供有关输入参数的附加信息,例如描述或参数是必需还是可选。默认情况下,所有输入参数都被视为必需。有关更多详细信息,请参见 JSON Schema

ToolMetadata.Builder 允许您构建 ToolMetadata 实例并定义工具的附加设置:

  • returnDirect:工具结果是直接返回给客户端还是传递回模型。有关更多详细信息,请参见 直接返回

Method method = ReflectionUtils.findMethod(DateTimeTools.class, "getCurrentDateTime");
ToolCallback toolCallback = MethodToolCallback.builder()
    .toolDefinition(ToolDefinitions.builder(method)
            .description("Get the current date and time in the user's timezone")
            .build())
    .toolMethod(method)
    .toolObject(new DateTimeTools())
    .build();

该方法可以是静态或实例方法,并且可以具有任何可见性(public、protected、package-private或private)。包含该方法的类可以是顶级类或嵌套类,并且也可以具有任何可见性(只要它在您计划实例化它的地方可访问)。

Spring AI为工具方法提供了AOT编译的内置支持,只要包含方法的类是Spring bean(例如 @Component)。否则,您需要为GraalVM编译器提供必要的配置。例如,通过使用 @RegisterReflection(memberCategories = MemberCategory.INVOKE_DECLARED_METHODS) 注解该类。

您可以为方法定义任意数量的参数(包括无参数),类型可以是大多数类型(基本类型、POJO、枚举、列表、数组、映射等)。同样,方法可以返回大多数类型,包括 void。如果方法返回一个值,则返回类型必须是可序列化类型,因为结果将被序列化并发送回模型。

某些类型不受支持。有关更多详细信息,请参见 方法工具限制

如果方法是静态的,则可以省略 toolObject() 方法,因为它不需要。

class DateTimeTools {

    static String getCurrentDateTime() {
        return LocalDateTime.now().atZone(LocaleContextHolder.getTimeZone().toZoneId()).toString();
    }

}
Method method = ReflectionUtils.findMethod(DateTimeTools.class, "getCurrentDateTime");
ToolCallback toolCallback = MethodToolCallback.builder()
    .toolDefinition(ToolDefinitions.builder(method)
            .description("Get the current date and time in the user's timezone")
            .build())
    .toolMethod(method)
    .build();

Spring AI将自动为方法的输入参数生成JSON Schema。Schema由模型用于理解如何调用工具并准备工具请求。@ToolParam 注解可用于提供有关输入参数的附加信息,例如描述或参数是必需还是可选。默认情况下,所有输入参数都被视为必需。

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.springframework.ai.tool.annotation.ToolParam;

class DateTimeTools {

    void setAlarm(@ToolParam(description = "Time in ISO-8601 format") String time) {
        LocalDateTime alarmTime = LocalDateTime.parse(time, DateTimeFormatter.ISO_DATE_TIME);
        System.out.println("Alarm set for " + alarmTime);
    }

}

@ToolParam 注解允许您提供有关工具参数的关键信息:

  • description:参数的描述,模型可以使用它更好地理解如何使用它。例如,参数应采用什么格式,允许什么值等等。

  • required:参数是必需还是可选。默认情况下,所有参数都被视为必需。

如果参数被 @Nullable 注解,则它将被视为可选,除非使用 @ToolParam 注解明确标记为必需。

除了 @ToolParam 注解,您还可以使用Swagger的 @Schema 注解或Jackson的 @JsonProperty。有关更多详细信息,请参见 JSON Schema

将工具添加到 ChatClientChatModel

当使用编程式规范方法时,您可以将 MethodToolCallback 实例传递给 ChatClienttoolCallbacks() 方法。 该工具仅适用于它所添加的特定聊天请求。

ToolCallback toolCallback = ...
ChatClient.create(chatModel)
    .prompt("What day is tomorrow?")
    .toolCallbacks(toolCallback)
    .call()
    .content();

将默认工具添加到 ChatClient

当使用编程式规范方法时,您可以通过将 MethodToolCallback 实例传递给 defaultToolCallbacks() 方法来将默认工具添加到 ChatClient.Builder。 如果同时提供了默认工具和运行时工具,则运行时工具将完全覆盖默认工具。

默认工具在由同一 ChatClient.Builder 构建的所有 ChatClient 实例执行的所有聊天请求中共享。它们对于跨不同聊天请求常用工具很有用,但如果不小心使用,也可能很危险,冒着在不应该使用时使其可用的风险。

ChatModel chatModel = ...
ToolCallback toolCallback = ...
ChatClient chatClient = ChatClient.builder(chatModel)
    .defaultToolCallbacks(toolCallback)
    .build();

将工具添加到 ChatModel

当使用编程式规范方法时,您可以将 MethodToolCallback 实例传递给您用于调用 ChatModelToolCallingChatOptionstoolCallbacks() 方法。该工具仅适用于它所添加的特定聊天请求。

ChatModel chatModel = ...
ToolCallback toolCallback = ...
ChatOptions chatOptions = ToolCallingChatOptions.builder()
    .toolCallbacks(toolCallback)
    .build():
Prompt prompt = new Prompt("What day is tomorrow?", chatOptions);
chatModel.call(prompt);

将默认工具添加到 ChatModel

当使用编程式规范方法时,您可以在构建 ChatModel 时通过将 MethodToolCallback 实例传递给用于创建 ChatModelToolCallingChatOptions 实例的 toolCallbacks() 方法来添加默认工具。 如果同时提供了默认工具和运行时工具,则运行时工具将完全覆盖默认工具。

默认工具在该 ChatModel 实例执行的所有聊天请求中共享。它们对于跨不同聊天请求常用工具很有用,但如果不小心使用,也可能很危险,冒着在不应该使用时使其可用的风险。

ToolCallback toolCallback = ...
ChatModel chatModel = OllamaChatModel.builder()
    .ollamaApi(OllamaApi.builder().build())
    .defaultOptions(ToolCallingChatOptions.builder()
            .toolCallbacks(toolCallback)
            .build())
    .build();

方法工具限制

以下类型目前不支持作为用作工具的方法的参数或返回类型:

  • Optional

  • 异步类型(例如 CompletableFutureFuture

  • 响应式类型(例如 FlowMonoFlux

  • 函数式类型(例如 FunctionSupplierConsumer)。

函数式类型可以使用基于函数的工具规范方法支持。有关更多详细信息,请参见 函数作为工具

函数作为工具

Spring AI提供了内置支持,用于从函数中指定工具,无论是编程式地使用低级 FunctionToolCallback 实现,还是动态地作为运行时解析的 @Bean(s)。

编程式规范:FunctionToolCallback

您可以通过编程式构建 FunctionToolCallback 将函数式类型(FunctionSupplierConsumerBiFunction)转换为工具。

public class WeatherService implements Function<WeatherRequest, WeatherResponse> {
    public WeatherResponse apply(WeatherRequest request) {
        return new WeatherResponse(30.0, Unit.C);
    }
}

public enum Unit { C, F }
public record WeatherRequest(String location, Unit unit) {}
public record WeatherResponse(double temp, Unit unit) {}

FunctionToolCallback.Builder 允许您构建 FunctionToolCallback 实例并提供有关工具的关键信息:

  • name:工具的名称。AI模型使用此名称在调用工具时识别它。因此,不允许在同一上下文中存在两个同名的工具。名称在所有可供模型使用的工具中必须是唯一的,用于特定聊天请求。必需。

  • toolFunction:表示工具方法的函数对象(FunctionSupplierConsumerBiFunction)。必需。

  • description:工具的描述,模型可以使用它来理解何时以及如何调用工具。如果未提供,将使用方法名称作为工具描述。但是,强烈建议提供详细描述,因为这对于模型理解工具目的和如何使用它至关重要。未能提供良好描述可能导致模型不该使用工具时使用,或错误地使用。

  • inputType:函数输入的类型。必需。

  • inputSchema:工具输入参数的JSON Schema。如果未提供,Schema将根据 inputType 自动生成。您可以使用 @ToolParam 注解提供有关输入参数的附加信息,例如描述或参数是必需还是可选。默认情况下,所有输入参数都被视为必需。有关更多详细信息,请参见 JSON Schema

  • toolMetadata:定义附加设置(例如结果是否应直接返回给客户端以及要使用的结果转换器)的 ToolMetadata 实例。您可以使用 ToolMetadata.Builder 类构建它。

  • toolCallResultConverter:用于将工具调用结果转换为 String 对象以发送回AI模型的 ToolCallResultConverter 实例。如果未提供,将使用默认转换器 (DefaultToolCallResultConverter)。

ToolMetadata.Builder 允许您构建 ToolMetadata 实例并定义工具的附加设置:

  • returnDirect:工具结果是直接返回给客户端还是传递回模型。有关更多详细信息,请参见 直接返回

ToolCallback toolCallback = FunctionToolCallback
    .builder("currentWeather", new WeatherService())
    .description("Get the weather in location")
    .inputType(WeatherRequest.class)
    .build();

函数输入和输出可以是 Void 或POJO。输入和输出POJO必须是可序列化的,因为结果将被序列化并发送回模型。函数以及输入和输出类型必须是public。

某些类型不受支持。有关更多详细信息,请参见 函数工具限制

将工具添加到 ChatClient

当使用编程式规范方法时,您可以将 FunctionToolCallback 实例传递给 ChatClienttoolCallbacks() 方法。该工具仅适用于它所添加的特定聊天请求。

ToolCallback toolCallback = ...
ChatClient.create(chatModel)
    .prompt("What's the weather like in Copenhagen?")
    .toolCallbacks(toolCallback)
    .call()
    .content();

将默认工具添加到 ChatClient

当使用编程式规范方法时,您可以通过将 FunctionToolCallback 实例传递给 defaultToolCallbacks() 方法来将默认工具添加到 ChatClient.Builder。 如果同时提供了默认工具和运行时工具,则运行时工具将完全覆盖默认工具。

默认工具在由同一 ChatClient.Builder 构建的所有 ChatClient 实例执行的所有聊天请求中共享。它们对于跨不同聊天请求常用工具很有用,但如果不小心使用,也可能很危险,冒着在不应该使用时使其可用的风险。

ChatModel chatModel = ...
ToolCallback toolCallback = ...
ChatClient chatClient = ChatClient.builder(chatModel)
    .defaultToolCallbacks(toolCallback)
    .build();

将工具添加到 ChatModel

当使用编程式规范方法时,您可以将 FunctionToolCallback 实例传递给 ToolCallingChatOptionstoolCallbacks() 方法。该工具仅适用于它所添加的特定聊天请求。

ChatModel chatModel = ...
ToolCallback toolCallback = ...
ChatOptions chatOptions = ToolCallingChatOptions.builder()
    .toolCallbacks(toolCallback)
    .build():
Prompt prompt = new Prompt("What's the weather like in Copenhagen?", chatOptions);
chatModel.call(prompt);

将默认工具添加到 ChatModel

当使用编程式规范方法时,您可以在构建 ChatModel 时通过将 FunctionToolCallback 实例传递给用于创建 ChatModelToolCallingChatOptions 实例的 toolCallbacks() 方法来添加默认工具。 如果同时提供了默认工具和运行时工具,则运行时工具将完全覆盖默认工具。

默认工具在该 ChatModel 实例执行的所有聊天请求中共享。它们对于跨不同聊天请求常用工具很有用,但如果不小心使用,也可能很危险,冒着在不应该使用时使其可用的风险。

ToolCallback toolCallback = ...
ChatModel chatModel = OllamaChatModel.builder()
    .ollamaApi(OllamaApi.builder().build())
    .defaultOptions(ToolCallingChatOptions.builder()
            .toolCallbacks(toolCallback)
            .build())
    .build();

动态规范:@Bean

除了编程式地指定工具之外,您还可以将工具定义为Spring bean,并让Spring AI使用 ToolCallbackResolver 接口(通过 SpringBeanToolCallbackResolver 实现)在运行时动态解析它们。此选项使您可以使用任何 FunctionSupplierConsumerBiFunction bean 作为工具。bean名称将用作工具名称,Spring Framework的 @Description 注解可用于提供工具的描述,模型可以使用它来理解何时以及如何调用工具。如果您不提供描述,则方法名称将用作工具描述。但是,强烈建议提供详细描述,因为这对于模型理解工具目的和如何使用它至关重要。未能提供良好描述可能导致模型不该使用工具时使用,或错误地使用。

@Configuration(proxyBeanMethods = false)
class WeatherTools {

    WeatherService weatherService = new WeatherService();

	@Bean
	@Description("Get the weather in location")
	Function<WeatherRequest, WeatherResponse> currentWeather() {
		return weatherService;
	}

}

某些类型不受支持。有关更多详细信息,请参见 函数工具限制

工具输入参数的JSON Schema将自动生成。您可以使用 @ToolParam 注解提供有关输入参数的附加信息,例如描述或参数是必需还是可选。默认情况下,所有输入参数都被视为必需。有关更多详细信息,请参见 JSON Schema

record WeatherRequest(@ToolParam(description = "The name of a city or a country") String location, Unit unit) {}

这种工具规范方法有一个缺点,即不能保证类型安全,因为工具解析是在运行时完成的。为了缓解这个问题,您可以使用 @Bean 注解明确指定工具名称并将值存储在常量中,以便在聊天请求中使用它而不是硬编码工具名称。

@Configuration(proxyBeanMethods = false)
class WeatherTools {

    public static final String CURRENT_WEATHER_TOOL = "currentWeather";

	@Bean(CURRENT_WEATHER_TOOL)
	@Description("Get the weather in location")
	Function<WeatherRequest, WeatherResponse> currentWeather() {
		...
	}

}

将工具添加到 ChatClient

当使用动态规范方法时,您可以将工具名称(即函数bean名称)传递给 ChatClienttoolNames() 方法。 该工具仅适用于它所添加的特定聊天请求。

ChatClient.create(chatModel)
    .prompt("What's the weather like in Copenhagen?")
    .toolNames("currentWeather")
    .call()
    .content();

将默认工具添加到 ChatClient

当使用动态规范方法时,您可以通过将工具名称传递给 defaultToolNames() 方法来将默认工具添加到 ChatClient.Builder。 如果同时提供了默认工具和运行时工具,则运行时工具将完全覆盖默认工具。

默认工具在由同一 ChatClient.Builder 构建的所有 ChatClient 实例执行的所有聊天请求中共享。它们对于跨不同聊天请求常用工具很有用,但如果不小心使用,也可能很危险,冒着在不应该使用时使其可用的风险。

ChatModel chatModel = ...
ChatClient chatClient = ChatClient.builder(chatModel)
    .defaultToolNames("currentWeather")
    .build();

将工具添加到 ChatModel

当使用动态规范方法时,您可以将工具名称传递给您用于调用 ChatModelToolCallingChatOptionstoolNames() 方法。该工具仅适用于它所添加的特定聊天请求。

ChatModel chatModel = ...
ChatOptions chatOptions = ToolCallingChatOptions.builder()
    .toolNames("currentWeather")
    .build();
Prompt prompt = new Prompt("What's the weather like in Copenhagen?", chatOptions);
chatModel.call(prompt);

将默认工具添加到 ChatModel

当使用动态规范方法时,您可以在构建 ChatModel 时通过将工具名称传递给用于创建 ChatModelToolCallingChatOptions 实例的 toolNames() 方法来添加默认工具。 如果同时提供了默认工具和运行时工具,则运行时工具将完全覆盖默认工具。

默认工具在该 ChatModel 实例执行的所有聊天请求中共享。它们对于跨不同聊天请求常用工具很有用,但如果不小心使用,也可能很危险,冒着在不应该使用时使其可用的风险。

ChatModel chatModel = OllamaChatModel.builder()
    .ollamaApi(OllamaApi.builder().build())
    .defaultOptions(ToolCallingChatOptions.builder()
            .toolNames("currentWeather")
            .build())
    .build();

函数工具限制

以下类型目前不支持作为用作函数的输入或输出类型:

  • 基本类型

  • Optional

  • 集合类型(例如 ListMapArraySet

  • 异步类型(例如 CompletableFutureFuture

  • 响应式类型(例如 FlowMonoFlux)。

基本类型和集合可以使用基于方法_的工具规范方法支持。有关更多详细信息,请参见 方法作为工具

工具规范

在Spring AI中,工具通过 ToolCallback 接口建模。在前面的部分中,我们已经看到了如何使用Spring AI提供的内置支持(请参阅 方法作为工具函数作为工具)从方法和函数定义工具。本节将深入探讨工具规范以及如何自定义和扩展它以支持更多用例。

工具回调

ToolCallback 接口提供了一种定义可由AI模型调用的工具的方式,包括定义和执行逻辑。它是您想要从头开始定义工具时要实现的主要接口。例如,您可以从MCP客户端(使用模型上下文协议)或 ChatClient(用于构建模块化代理应用程序)定义 ToolCallback

该接口提供以下方法:

public interface ToolCallback {

	/**
	 * Definition used by the AI model to determine when and how to call the tool.
	 */
	ToolDefinition getToolDefinition();

	/**
	 * Metadata providing additional information on how to handle the tool.
	 */
	ToolMetadata getToolMetadata();

    /**
	 * Execute tool with the given input and return the result to send back to the AI model.
	 */
	String call(String toolInput);

    /**
	 * Execute tool with the given input and context, and return the result to send back to the AI model.
	 */
	String call(String toolInput, ToolContext tooContext);

}

Spring AI为工具方法(MethodToolCallback)和工具函数(FunctionToolCallback)提供了内置实现。

工具定义

ToolDefinition 接口提供AI模型了解工具可用性所需的信息,包括工具名称、描述和输入Schema。每个 ToolCallback 实现都必须提供 ToolDefinition 实例来定义工具。

该接口提供以下方法:

public interface ToolDefinition {

	/**
	 * The tool name. Unique within the tool set provided to a model.
	 */
	String name();

	/**
	 * The tool description, used by the AI model to determine what the tool does.
	 */
	String description();

	/**
	 * The schema of the parameters used to call the tool.
	 */
	String inputSchema();

}

有关输入Schema的更多详细信息,请参见 JSON Schema

ToolDefinition.Builder 允许您使用默认实现(DefaultToolDefinition)构建 ToolDefinition 实例。

ToolDefinition toolDefinition = ToolDefinition.builder()
    .name("currentWeather")
    .description("Get the weather in location")
    .inputSchema("""
        {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string"
                },
                "unit": {
                    "type": "string",
                    "enum": ["C", "F"]
                }
            },
            "required": ["location", "unit"]
        }
    """)
    .build();

方法工具定义

从方法构建工具时,ToolDefinition 会自动为您生成。如果您更喜欢自己生成 ToolDefinition,可以使用此便捷构建器。

Method method = ReflectionUtils.findMethod(DateTimeTools.class, "getCurrentDateTime");
ToolDefinition toolDefinition = ToolDefinitions.from(method);

从方法生成的 ToolDefinition 包含方法名称作为工具名称,方法名称作为工具描述,以及方法输入参数的JSON Schema。如果方法用 @Tool 注解,则工具名称和描述(如果设置)将从注解中获取。

有关更多详细信息,请参见 方法作为工具

如果您更愿意显式提供某些或所有属性,可以使用 ToolDefinition.Builder 构建自定义 ToolDefinition 实例。

Method method = ReflectionUtils.findMethod(DateTimeTools.class, "getCurrentDateTime");
ToolDefinition toolDefinition = ToolDefinitions.builder(method)
    .name("currentDateTime")
    .description("Get the current date and time in the user's timezone")
    .inputSchema(JsonSchemaGenerator.generateForMethodInput(method))
    .build();

函数工具定义

从函数构建工具时,ToolDefinition 会自动为您生成。当您使用 FunctionToolCallback.Builder 构建 FunctionToolCallback 实例时,您可以提供将用于生成 ToolDefinition 的工具名称、描述和输入Schema。有关更多详细信息,请参见 函数作为工具

JSON Schema

当向AI模型提供工具时,模型需要知道用于调用工具的输入类型的Schema。Schema用于理解如何调用工具并准备工具请求。Spring AI通过 JsonSchemaGenerator 类提供内置支持,用于为工具的输入类型生成JSON Schema。Schema作为 ToolDefinition 的一部分提供。

有关 ToolDefinition 以及如何将输入Schema传递给它的更多详细信息,请参见 工具定义

JsonSchemaGenerator 类在底层用于为方法或函数的输入参数生成JSON Schema,使用 方法作为工具函数作为工具 中描述的任何策略。JSON Schema生成逻辑支持一系列注解,您可以在方法和函数的输入参数上使用这些注解来自定义结果Schema。

本节描述了在为工具输入参数生成JSON Schema时可以自定义的两个主要选项:描述和必需状态。

描述

除了为工具本身提供描述之外,您还可以为工具的输入参数提供描述。描述可用于提供有关输入参数的关键信息,例如参数应采用什么格式、允许什么值等等。这有助于模型理解输入Schema以及如何使用它。Spring AI通过以下注解之一提供内置支持,用于为输入参数生成描述:

  • Spring AI的 @ToolParam(description = "…​")

  • Jackson的 @JsonClassDescription(description = "…​")

  • Jackson的 @JsonPropertyDescription(description = "…​")

  • Swagger的 @Schema(description = "…​")

此方法适用于方法和函数,您可以将其递归用于嵌套类型。

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.context.i18n.LocaleContextHolder;

class DateTimeTools {

    @Tool(description = "Set a user alarm for the given time")
    void setAlarm(@ToolParam(description = "Time in ISO-8601 format") String time) {
        LocalDateTime alarmTime = LocalDateTime.parse(time, DateTimeFormatter.ISO_DATE_TIME);
        System.out.println("Alarm set for " + alarmTime);
    }

}

必需/可选

默认情况下,每个输入参数都被视为必需,这强制AI模型在调用工具时为其提供一个值。但是,您可以通过使用以下注解之一使输入参数可选,优先级顺序如下:

  • Spring AI的 @ToolParam(required = false)

  • Jackson的 @JsonProperty(required = false)

  • Swagger的 @Schema(required = false)

  • Spring Framework的 @Nullable

此方法适用于方法和函数,您可以将其递归用于嵌套类型。

class CustomerTools {

    @Tool(description = "Update customer information")
    void updateCustomerInfo(Long id, String name, @ToolParam(required = false) String email) {
        System.out.println("Updated info for customer with id: " + id);
    }

}

为输入参数定义正确的必需状态对于降低幻觉风险并确保模型在调用工具时提供正确输入至关重要。在前面的示例中,email 参数是可选的,这意味着模型可以在不为其提供值的情况下调用工具。如果参数是必需的,模型在调用工具时将必须为其提供一个值。如果没有值,模型可能会编造一个,导致幻觉。

结果转换

工具调用的结果使用 ToolCallResultConverter 序列化,然后发送回AI模型。ToolCallResultConverter 接口提供了一种将工具调用结果转换为 String 对象的方法。

该接口提供以下方法:

@FunctionalInterface
public interface ToolCallResultConverter {

	/**
	 * Given an Object returned by a tool, convert it to a String compatible with the
	 * given class type.
	 */
	String convert(@Nullable Object result, @Nullable Type returnType);

}

结果必须是可序列化类型。默认情况下,结果使用Jackson序列化为JSON(DefaultToolCallResultConverter),但您可以通过提供自己的 ToolCallResultConverter 实现来自定义序列化过程。

Spring AI在方法和函数工具中都依赖于 ToolCallResultConverter

方法工具调用结果转换

当使用声明式方法从方法构建工具时,您可以通过设置 @Tool 注解的 resultConverter() 属性来为工具提供自定义的 ToolCallResultConverter

class CustomerTools {

    @Tool(description = "Retrieve customer information", resultConverter = CustomToolCallResultConverter.class)
    Customer getCustomerInfo(Long id) {
        return customerRepository.findById(id);
    }

}

如果使用编程式方法,您可以通过设置 MethodToolCallback.BuilderresultConverter() 属性来为工具提供自定义的 ToolCallResultConverter

有关更多详细信息,请参见 方法作为工具

函数工具调用结果转换

当使用编程式方法从函数构建工具时,您可以通过设置 FunctionToolCallback.BuilderresultConverter() 属性来为工具提供自定义的 ToolCallResultConverter

有关更多详细信息,请参见 函数作为工具

工具上下文

Spring AI通过 ToolContext API支持将附加上下文信息传递给工具。此功能允许您提供额外的、用户提供的数据,这些数据可以在工具执行中与AI模型传递的工具参数一起使用。

tool context
class CustomerTools {

    @Tool(description = "Retrieve customer information")
    Customer getCustomerInfo(Long id, ToolContext toolContext) {
        return customerRepository.findById(id, toolContext.getContext().get("tenantId"));
    }

}

ToolContext 在调用 ChatClient 时使用用户提供的数据填充。

ChatModel chatModel = ...

String response = ChatClient.create(chatModel)
        .prompt("Tell me more about the customer with ID 42")
        .tools(new CustomerTools())
        .toolContext(Map.of("tenantId", "acme"))
        .call()
        .content();

System.out.println(response);

ToolContext 中提供的任何数据都不会发送给AI模型。

同样,您可以在直接调用 ChatModel 时定义工具上下文数据。

ChatModel chatModel = ...
ToolCallback[] customerTools = ToolCallbacks.from(new CustomerTools());
ChatOptions chatOptions = ToolCallingChatOptions.builder()
    .toolCallbacks(customerTools)
    .toolContext(Map.of("tenantId", "acme"))
    .build();
Prompt prompt = new Prompt("Tell me more about the customer with ID 42", chatOptions);
chatModel.call(prompt);

如果 toolContext 选项在默认选项和运行时选项中都设置,则生成的 ToolContext 将是两者的合并, 其中运行时选项优先于默认选项。

直接返回

默认情况下,工具调用的结果会作为响应发送回模型。然后,模型可以使用该结果继续对话。

在某些情况下,您可能希望将结果直接返回给调用者,而不是将其发送回模型。例如,如果您构建了一个依赖RAG工具的代理,您可能希望将结果直接返回给调用者,而不是将其发送回模型进行不必要的后处理。或者,您可能有一些工具应该结束代理的推理循环。

每个 ToolCallback 实现都可以定义工具调用的结果是直接返回给调用者还是发送回模型。默认情况下,结果会发送回模型。但您可以按工具更改此行为。

ToolCallingManager 负责管理工具执行生命周期,负责处理与工具关联的 returnDirect 属性。如果该属性设置为 true,则工具调用的结果将直接返回给调用者。否则,结果将发送回模型。

如果同时请求多个工具调用,则所有工具的 returnDirect 属性都必须设置为 true 才能将结果直接返回给调用者。否则,结果将发送回模型。

return direct
  1. 当我们要将工具提供给模型时,我们将工具定义包含在聊天请求中。如果希望工具执行结果直接返回给调用者,我们将 returnDirect 属性设置为 true

  2. 当模型决定调用工具时,它会发送一个响应,其中包含工具名称和根据定义的Schema建模的输入参数。

  3. 应用程序负责使用工具名称识别并执行带有提供输入参数的工具。

  4. 工具调用的结果由应用程序处理。

  5. 应用程序将工具调用结果直接发送给调用者,而不是将其发送回模型。

方法直接返回

当使用声明式方法从方法构建工具时,您可以通过将 @Tool 注解的 returnDirect 属性设置为 true 来将工具标记为直接将结果返回给调用者。

class CustomerTools {

    @Tool(description = "Retrieve customer information", returnDirect = true)
    Customer getCustomerInfo(Long id) {
        return customerRepository.findById(id);
    }

}

如果使用编程式方法,您可以通过 ToolMetadata 接口设置 returnDirect 属性并将其传递给 MethodToolCallback.Builder

ToolMetadata toolMetadata = ToolMetadata.builder()
    .returnDirect(true)
    .build();

有关更多详细信息,请参见 方法作为工具

函数直接返回

当使用编程式方法从函数构建工具时,您可以通过 ToolMetadata 接口设置 returnDirect 属性并将其传递给 FunctionToolCallback.Builder

ToolMetadata toolMetadata = ToolMetadata.builder()
    .returnDirect(true)
    .build();

有关更多详细信息,请参见 函数作为工具

工具执行

工具执行是使用提供的输入参数调用工具并返回结果的过程。工具执行由 ToolCallingManager 接口处理,该接口负责管理工具执行生命周期。

public interface ToolCallingManager {

	/**
	 * Resolve the tool definitions from the model's tool calling options.
	 */
	List<ToolDefinition> resolveToolDefinitions(ToolCallingChatOptions chatOptions);

	/**
	 * Execute the tool calls requested by the model.
	 */
	ToolExecutionResult executeToolCalls(Prompt prompt, ChatResponse chatResponse);

}

如果您正在使用任何Spring AI Spring Boot Starter,DefaultToolCallingManagerToolCallingManager 接口的自动配置实现。您可以通过提供自己的 ToolCallingManager bean来自定义工具执行行为。

@Bean
ToolCallingManager toolCallingManager() {
    return ToolCallingManager.builder().build();
}

默认情况下,Spring AI在每个 ChatModel 实现中为您透明地管理工具执行生命周期。但是,您可以选择禁用此行为并自行控制工具执行。本节描述了这两种情况。

框架控制的工具执行

当使用默认行为时,Spring AI将自动拦截模型的任何工具调用请求,调用工具并将结果返回给模型。所有这些都由每个 ChatModel 实现使用 ToolCallingManager 为您透明地完成。

framework manager
  1. 当我们要将工具提供给模型时,我们将其定义包含在聊天请求 (Prompt) 中,并调用 ChatModel API,该API将请求发送到AI模型。

  2. 当模型决定调用工具时,它会发送一个响应 (ChatResponse),其中包含工具名称和根据定义的Schema建模的输入参数。

  3. ChatModel 将工具调用请求发送到 ToolCallingManager API。

  4. ToolCallingManager 负责识别要调用的工具并使用提供的输入参数执行它。

  5. 工具调用的结果返回给 ToolCallingManager

  6. ToolCallingManager 将工具执行结果返回给 ChatModel

  7. ChatModel 将工具执行结果发送回AI模型 (ToolResponseMessage)。

  8. AI模型使用工具调用结果作为附加上下文生成最终响应,并通过 ChatClient 将其发送回调用者 (ChatResponse)。

目前,与模型交换的关于工具执行的内部消息不向用户公开。如果您需要访问这些消息,则应使用用户控制的工具执行方法。

确定工具调用是否符合执行条件的逻辑由 ToolExecutionEligibilityPredicate 接口处理。默认情况下,工具执行资格由检查 ToolCallingChatOptionsinternalToolExecutionEnabled 属性是否设置为 true(默认值)以及 ChatResponse 是否包含任何工具调用来确定。

public class DefaultToolExecutionEligibilityPredicate implements ToolExecutionEligibilityPredicate {

	@Override
	public boolean test(ChatOptions promptOptions, ChatResponse chatResponse) {
		return ToolCallingChatOptions.isInternalToolExecutionEnabled(promptOptions) && chatResponse != null
				&& chatResponse.hasToolCalls();
	}

}

您可以在创建 ChatModel bean时提供 ToolExecutionEligibilityPredicate 的自定义实现。

用户控制的工具执行

在某些情况下,您可能希望自行控制工具执行生命周期。您可以通过将 ToolCallingChatOptionsinternalToolExecutionEnabled 属性设置为 false 来实现。

当您使用此选项调用 ChatModel 时,工具执行将委托给调用者,从而使您完全控制工具执行生命周期。您有责任检查 ChatResponse 中的工具调用并使用 ToolCallingManager 执行它们。

以下示例演示了用户控制的工具执行方法的最小实现:

ChatModel chatModel = ...
ToolCallingManager toolCallingManager = ToolCallingManager.builder().build();

ChatOptions chatOptions = ToolCallingChatOptions.builder()
    .toolCallbacks(new CustomerTools())
    .internalToolExecutionEnabled(false)
    .build();
Prompt prompt = new Prompt("Tell me more about the customer with ID 42", chatOptions);

ChatResponse chatResponse = chatModel.call(prompt);

while (chatResponse.hasToolCalls()) {
    ToolExecutionResult toolExecutionResult = toolCallingManager.executeToolCalls(prompt, chatResponse);

    prompt = new Prompt(toolExecutionResult.conversationHistory(), chatOptions);

    chatResponse = chatModel.call(prompt);
}

System.out.println(chatResponse.getResult().getOutput().getText());

当选择用户控制的工具执行方法时,我们建议使用 ToolCallingManager 来管理工具调用操作。这样,您可以受益于Spring AI提供的工具执行内置支持。但是,没有任何东西可以阻止您实现自己的工具执行逻辑。

以下示例显示了用户控制的工具执行方法与 ChatMemory API结合使用的最小实现:

ToolCallingManager toolCallingManager = DefaultToolCallingManager.builder().build();
ChatMemory chatMemory = MessageWindowChatMemory.builder().build();
String conversationId = UUID.randomUUID().toString();

ChatOptions chatOptions = ToolCallingChatOptions.builder()
    .toolCallbacks(ToolCallbacks.from(new MathTools()))
    .internalToolExecutionEnabled(false)
    .build();
Prompt prompt = new Prompt(
        List.of(new SystemMessage("You are a helpful assistant."), new UserMessage("What is 6 * 8?")),
        chatOptions);
chatMemory.add(conversationId, prompt.getInstructions());

Prompt promptWithMemory = new Prompt(chatMemory.get(conversationId), chatOptions);
ChatResponse chatResponse = chatModel.call(promptWithMemory);
chatMemory.add(conversationId, chatResponse.getResult().getOutput());

while (chatResponse.hasToolCalls()) {
    ToolExecutionResult toolExecutionResult = toolCallingManager.executeToolCalls(promptWithMemory,
            chatResponse);
    chatMemory.add(conversationId, toolExecutionResult.conversationHistory()
        .get(toolExecutionResult.conversationHistory().size() - 1));
    promptWithMemory = new Prompt(chatMemory.get(conversationId), chatOptions);
    chatResponse = chatModel.call(promptWithMemory);
    chatMemory.add(conversationId, chatResponse.getResult().getOutput());
}

UserMessage newUserMessage = new UserMessage("What did I ask you earlier?");
chatMemory.add(conversationId, newUserMessage);

ChatResponse newResponse = chatModel.call(new Prompt(chatMemory.get(conversationId)));

异常处理

当工具调用失败时,异常会作为 ToolExecutionException 传播,可以捕获它来处理错误。 ToolExecutionExceptionProcessor 可用于处理 ToolExecutionException,结果有两种:生成错误消息发送回AI模型,或抛出异常由调用者处理。

@FunctionalInterface
public interface ToolExecutionExceptionProcessor {

	/**
	 * Convert an exception thrown by a tool to a String that can be sent back to the AI
	 * model or throw an exception to be handled by the caller.
	 */
	String process(ToolExecutionException exception);

}

如果您正在使用任何Spring AI Spring Boot Starter,DefaultToolExecutionExceptionProcessorToolExecutionExceptionProcessor 接口的自动配置实现。默认情况下,RuntimeException 的错误消息会发送回模型,而受检异常和错误(例如 IOExceptionOutOfMemoryError)总是抛出。DefaultToolExecutionExceptionProcessor 构造函数允许您将 alwaysThrow 属性设置为 truefalse。如果为 true,则会抛出异常而不是向模型发送错误消息。

您可以使用 spring.ai.tools.throw-exception-on-error 属性来控制 DefaultToolExecutionExceptionProcessor bean 的行为:

属性 描述 默认

spring.ai.tools.throw-exception-on-error

如果为 true,工具调用错误将作为异常抛出,由调用者处理。如果为 false,错误将转换为消息并发送回AI模型,允许它处理并响应错误。

false

@Bean
ToolExecutionExceptionProcessor toolExecutionExceptionProcessor() {
    return new DefaultToolExecutionExceptionProcessor(true);
}

如果您定义了自己的 ToolCallback 实现,请确保在 call() 方法中发生错误时抛出 ToolExecutionException

ToolExecutionExceptionProcessor 由默认的 ToolCallingManager (DefaultToolCallingManager) 内部使用,以在工具执行期间处理异常。有关工具执行生命周期的更多详细信息,请参见 工具执行

工具解析

将工具传递给模型的主要方法是在调用 ChatClientChatModel 时提供 ToolCallback(s), 使用 方法作为工具函数作为工具 中描述的策略之一。

但是,Spring AI也支持使用 ToolCallbackResolver 接口在运行时动态解析工具。

public interface ToolCallbackResolver {

	/**
	 * Resolve the {@link ToolCallback} for the given tool name.
	 */
	@Nullable
	ToolCallback resolve(String toolName);

}

当使用这种方法时:

  • 在客户端,您将工具名称而不是 ToolCallback(s) 提供给 ChatClientChatModel

  • 在服务器端,ToolCallbackResolver 实现负责将工具名称解析为相应的 ToolCallback 实例。

默认情况下,Spring AI依赖于 DelegatingToolCallbackResolver,它将工具解析委托给 ToolCallbackResolver 实例列表:

  • SpringBeanToolCallbackResolverFunctionSupplierConsumerBiFunction 类型的Spring bean中解析工具。有关更多详细信息,请参见 动态规范:@Bean

  • StaticToolCallbackResolverToolCallback 实例的静态列表中解析工具。当使用Spring Boot自动配置时,此解析器会自动配置应用程序上下文中定义的所有 ToolCallback 类型的bean。

如果您依赖于Spring Boot自动配置,您可以通过提供自定义的 ToolCallbackResolver bean来自定义解析逻辑。

@Bean
ToolCallbackResolver toolCallbackResolver(List<FunctionCallback> toolCallbacks) {
    StaticToolCallbackResolver staticToolCallbackResolver = new StaticToolCallbackResolver(toolCallbacks);
    return new DelegatingToolCallbackResolver(List.of(staticToolCallbackResolver));
}

ToolCallbackResolverToolCallingManager 内部使用,以在运行时动态解析工具,支持 框架控制的工具执行用户控制的工具执行

可观测性

工具调用包括对 spring.ai.tool 观测值的可观测性支持,这些观测值测量完成时间并传播跟踪信息。请参阅 工具调用可观测性

Spring AI可以选择将工具调用参数和结果导出为span属性,出于敏感性原因,默认禁用。详细信息: 工具调用参数和结果数据

日志记录

工具调用功能的所有主要操作都以 DEBUG 级别记录。您可以通过将 org.springframework.ai 包的日志级别设置为 DEBUG 来启用日志记录。