Spring AI中函数调用Mistral AI最新API


Mistral AI 是开源大型语言模型的领先开发商,宣布为其尖端模型添加函数调用支持。

函数调用是一项促进 LLM 与外部工具和 API 集成的功能。它使语言模型能够请求执行客户端函数,从而允许其访问必要的运行时信息或动态执行任务。 

在这里,我将讨论如何使用 Mistral AI 的新函数调用功能与 Java,特别是Spring AI。

Java中的函数调用
如果您想使用 Java 和Spring AI测试最新的 Mistral AI 功能,您会发现 Mistral 不支持 Java 客户端,并且尚未发布函数调用 API。
因此,我不得不通过探索他们的 JavaScript/Python 客户端来解决这个问题。

我扩展了最初由 Ricken Bazolo 创建的MistralAiApi Java 客户端,以包含缺少的函数调用功能。更新后的客户端运行良好,如付款状态演示所示。

由于我的重点是 Spring AI,因此我不会在这里深入研究客户端的技术复杂性。


Spring AI 的函数调用
Spring AI 允许您定义@Bean返回用户定义的java.util.Function. 它自动推断函数的输入类型并相应地生成 JSON(或开放 API)模式。此外,Spring AI 通过使用必要的适配器代码包装 POJO(函数)来处理与 AI 模型的复杂交互,从而消除了您编写重复代码的需要。

此外,Spring AI 简化了代码与支持函数调用的其他 AI 模型的可移植性,并允许开发高效的本机 (GraalVM) 可执行文件。

假设我们希望人工智能模型用它没有的信息做出响应。例如,本 Mistral AI教程中所示的您最近的付款交易的状态。

让我们用 Spring AI 重新实现本教程。

使用Initializr引导新的引导应用程序,并将 MistralAI 引导启动器依赖项添加到 POM:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-mistral-ai-spring-boot-starter</artifactId>
    <version>0.8.1</version>
</dependency>

使用application.properties来配置它:

spring.ai.mistralai.api-key=${MISTRAL_AI_API_KEY}
spring.ai.mistralai.chat.options.model=mistral-small-latest

这将为您提供功能齐全的MistralAiChatClient:

@Autowired
MistralAiChatClient chatClient;

接下来假设我们有一个由支付交易组成的数据集:

public record Transaction(String transactionId) {}

public record Status(String status) {}

public static final Map<Transaction, Status> PAYMENT_DATA = Map.of(
            new Transaction("T1001"), new Status("Paid"),
            new Transaction(
"T1002"), new Status("Unpaid"),
            new Transaction(
"T1003"), new Status("Paid"),
            new Transaction(
"T1004"), new Status("Paid"),
            new Transaction(
"T1005"), new Status("Pending"));

用户可以提出有关该数据集的问题并使用函数调用来回答这些问题。例如,让我们考虑一个检索给定交易的付款状态的函数:

@Bean
@Description("Get payment status of a transaction")
public Function<Transaction, Status> retrievePaymentStatus() {
        return (transaction) -> new Status(PAYMENT_DATA.get(transaction).status());
}

它使用一个普通的java.util.Function,以 aTransaction作为输入并返回Status该交易的 。函数被注册为@Bean并使用@Description注释来定义函数描述。Spring AI 极大地简化了支持函数调用所需编写的代码。它为您代理函数调用对话。您还可以在提示中引用多个函数 bean 名称。

var options = MistralAiChatOptions.builder()
   .withFunction("retrievePaymentStatus")
   .build();

ChatResponse paymentStatusResponse = chatClient.call(
      new Prompt(
"What's the status of my transaction with id T1005?",  options);

我们在提示中制定问题,包括提示选项中的关联函数名称。函数名称应该与 Bean 名称匹配。

提示:您可以考虑在文件中配置一次,而不是在每个请求的提示选项中重复指定函数名称,application.properties例如:spring.ai.mistralai.chat.options.functions=retrievePaymentStatus。这种方法可确保该功能始终启用并可用于所有提示问题。但是,请务必注意,此方法可能会导致为不需要该功能的请求传输不必要的上下文令牌。

就是这样。Spring AI 将代表您促进函数调用的对话。可以打印响应内容:

System.out.println(paymentStatusResponse.getResult().getOutput().getContent());

并期望这样的结果:

The status of your transaction T1005 is "Pending".

详细点击标题