Spring AI 第二讲 之 Chat Model API 第七节Mistral AI Chat

Spring AI 支持来自 Mistral AI 的各种 AI 语言模型。您可以与 Mistral AI 语言模型互动,并基于 Mistral 模型创建多语言对话助手。

先决条件

要访问 Mistral AI 语言模型,您需要与 MistralAI 创建一个 API。在 MistralAI 注册页面创建账户,并在 API Keys 页面生成令牌。Spring AI 项目定义了一个名为 spring.ai.mistralai.api-key 的配置属性,您应将其设置为从 console.mistral.ai 获取的 API 密钥的值。导出环境变量是设置该配置属性的一种方法:

export SPRING_AI_MISTRALAI_API_KEY=<INSERT KEY HERE>

添加资源库和 BOM

Spring AI 工件发布在 Spring Milestone 和 Snapshot 资源库中。请参阅 "资源库 "部分,将这些资源库添加到您的构建系统中。
为了帮助进行依赖性管理,Spring AI 提供了一个 BOM(物料清单),以确保在整个项目中使用一致的 Spring AI 版本。请参阅 "依赖关系管理 "部分,将 Spring AI BOM 添加到构建系统中。

自动配置

Spring AI 为 MistralAI 聊天客户端提供 Spring Boot 自动配置功能。要启用它,请在项目的 Maven pom.xml 文件中添加以下依赖项:

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

或 Gradle build.gradle 构建文件。

dependencies {
    implementation 'org.springframework.ai:spring-ai-mistral-ai-spring-boot-starter'
}

请参阅 "依赖关系管理 "部分,将 Spring AI BOM 添加到构建文件中。

Chat 属性

重试属性

spring.ai.retry 作为属性前缀,可用于配置 Mistral AI 聊天模型的重试机制。

Property 说明 Default

spring.ai.retry.max-attempts

重试的最大次数。

10

spring.ai.retry.backoff.initial-interval

指数后退策略的初始睡眠时间。

2 sec.

spring.ai.retry.backoff.multiplier

回退间隔倍增。

5

spring.ai.retry.backoff.max-interval

最大回退持续时间。

3 min.

spring.ai.retry.on-client-errors

如果为false,则抛出 NonTransientAiException 异常,并且不尝试重试 4xx 客户端错误代码

false

spring.ai.retry.exclude-on-http-codes

不应触发重试(例如抛出 NonTransientAiException)的 HTTP 状态代码列表。

empty

spring.ai.retry.on-http-codes

应触发重试(例如抛出 TransientAiException)的 HTTP 状态代码列表。

empty

连接属性

spring.ai.mistralai前缀用作属性前缀,可让您连接到OpenAI。

Property Description Default

spring.ai.mistralai.base-url

要连接的 URL

api.mistral.ai

spring.ai.mistralai.api-key

应用程序接口密钥

-

配置属性

spring.ai.mistralai.chat 前缀是属性前缀,用于配置 MistralAI 的聊天模型实现。

Property Description Default

spring.ai.mistralai.chat.enabled

启用 MistralAI 聊天模型。

true

spring.ai.mistralai.chat.base-url

可选择覆盖 spring.ai.mistralai.base-url 以提供特定的聊天 URL

-

spring.ai.mistralai.chat.api-key

可选重载 spring.ai.mistralai.api-key,以提供特定于聊天的 api-key。

-

spring.ai.mistralai.chat.options.model

这就是要使用的 MistralAI 聊天模型

open-mistral-7bopen-mixtral-8x7bmistral-small-latestmistral-medium-latestmistral-large-latest

spring.ai.mistralai.chat.options.temperature

采样温度,用于控制生成的补间明显的创造性。取值越高,输出结果越随机,取值越低,结果越集中和确定。不建议针对同一个补全请求修改温度和 top_p,因为这两个设置之间的相互作用很难预测。

0.8

spring.ai.mistralai.chat.options.maxTokens

聊天完成时要生成的最大标记数。输入词组和生成词组的总长度受模型上下文长度的限制。

-

spring.ai.mistralai.chat.options.safePrompt

表示是否在所有对话之前注入安全提示。

false

spring.ai.mistralai.chat.options.randomSeed

该功能处于测试阶段。如果指定了该功能,我们的系统将尽最大努力进行确定性采样,这样,使用相同种子和参数的重复请求将返回相同的结果。

-

spring.ai.mistralai.chat.options.stop

最多 4 个序列,在这些序列中,API 将停止生成更多令牌。

-

spring.ai.mistralai.chat.options.topP

温度采样的另一种方法是核采样,即模型考虑概率质量为 top_p 的标记的结果。因此,0.1 意味着只考虑概率质量最高的 10%的标记。一般情况下,我们建议改变这一点或温度,但不能同时改变。

-

spring.ai.mistralai.chat.options.responseFormat

指定模型必须输出的格式的对象。设置为 { "type": "json_object" } 可启用 JSON 模式,该模式可确保模型生成的信息是有效的 JSON 格式。

-

spring.ai.mistralai.chat.options.tools

模型可调用的工具列表。目前只支持函数作为工具。用它来提供模型可生成 JSON 输入的函数列表。

-

spring.ai.mistralai.chat.options.toolChoice

控制模型调用哪个函数(如果有的话)。"无 "表示模型不会调用函数,而是生成一条消息。"自动 "表示模型可以选择生成消息或调用函数。通过 {"type: "function", "function": {"name": "my_function"}}强制模型调用该函数。none 是默认值,表示没有函数。

-

spring.ai.mistralai.chat.options.functions

由函数名称标识的函数列表,用于在单个提示请求中启用函数调用。具有这些名称的函数必须存在于 functionCallbacks 注册表中。

-

spring.ai.mistralai.chat.options.functionCallbacks

MistralAI 工具功能回调,用于注册 ChatModel。

-

您可以为 ChatModel 和 EmbeddingModel 实现覆盖常用的 spring.ai.mistralai.base-url 和 spring.ai.mistralai.api-key 属性。如果设置了 spring.ai.mistralai.chat.base-url 和 spring.ai.mistralai.chat.api-key 属性,它们将优先于通用属性。如果您想为不同的模型和不同的模型端点使用不同的 MistralAI 账户,这将非常有用。

所有以 spring.ai.mistralai.chat.options 为前缀的属性都可以通过在提示调用中添加特定于请求的运行时选项在运行时重写。

运行时选项

MistralAiChatOptions.java提供了模型配置,如要使用的模型、温度、频率惩罚等。
启动时,可使用 MistralAiChatModel(api, options) 构造函数或 spring.ai.mistralai.chat.options.* 属性配置默认选项。
在运行时,您可以通过在提示调用中添加新的、针对特定请求的选项来覆盖默认选项。例如,覆盖特定请求的默认模型和温度:

ChatResponse response = chatModel.call(
    new Prompt(
        "Generate the names of 5 famous pirates.",
        MistralAiChatOptions.builder()
            .withModel(MistralAiApi.ChatModel.LARGE.getValue())
            .withTemperature(0.5f)
        .build()
    ));

除了特定于模型的 MistralAiChatOptions外,您还可以使用通过 ChatOptionsBuilder#builder() 创建的便携式 ChatOptions 实例。

函数调用

您可以向 MistralAiChatModel 注册自定义 Java 函数,然后让 Mistral AI 模型智能地选择输出包含参数的 JSON 对象,以调用一个或多个已注册函数。这是一种将 LLM 功能与外部工具和 API 相连接的强大技术。了解更多有关Mistral AI 函数调用的信息。

示例控制器(自动配置)

创建一个新的 Spring Boot 项目,并将 spring-ai-mistral-ai-spring-boot-starter 添加到你的 pom(或 gradle)依赖项中。
在 src/main/resources 目录下添加 application.properties 文件,以启用和配置 OpenAi 聊天模型:

spring.ai.mistralai.api-key=YOUR_API_KEY
spring.ai.mistralai.chat.options.model=mistral-medium
spring.ai.mistralai.chat.options.temperature=0.7
将 api-key 替换为您的 OpenAI 凭据。

这将创建一个 MistralAiChatModel 实现,您可以将其注入到您的类中。下面是一个使用聊天模型生成文本的简单 @Controller 类的示例。

@RestController
public class ChatController {

    private final MistralAiChatModel chatModel;

    @Autowired
    public ChatController(MistralAiChatModel chatModel) {
        this.chatModel = chatModel;
    }

    @GetMapping("/ai/generate")
    public Map generate(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
        return Map.of("generation", chatModel.call(message));
    }

    @GetMapping("/ai/generateStream")
	public Flux<ChatResponse> generateStream(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
        var prompt = new Prompt(new UserMessage(message));
        return chatModel.stream(prompt);
    }
}

手动配置

MistralAiChatModel实现了 ChatModel 和 StreamingChatModel,并使用Low-level MistralAiApi 客户端连接到 MistralAI 服务。

在项目的 Maven pom.xml 文件中添加 spring-ai-mistral-ai 依赖关系:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-mistral-ai</artifactId>
</dependency>

或 Gradle build.gradle 构建文件。

dependencies {
    implementation 'org.springframework.ai:spring-ai-mistral-ai'
}

请参阅 "依赖关系管理 "部分,将 Spring AI BOM 添加到构建文件中。

接下来,创建一个 MistralAiChatModel 并将其用于文本生成:

var mistralAiApi = new MistralAiApi(System.getenv("MISTRAL_AI_API_KEY"));

var chatModel = new MistralAiChatModel(mistralAiApi, MistralAiChatOptions.builder()
                .withModel(MistralAiApi.ChatModel.LARGE.getValue())
                .withTemperature(0.4f)
                .withMaxToken(200)
                .build());

ChatResponse response = chatModel.call(
    new Prompt("Generate the names of 5 famous pirates."));

// Or with streaming responses
Flux<ChatResponse> response = chatModel.stream(
    new Prompt("Generate the names of 5 famous pirates."));

MistralAiChatOptions 为聊天请求提供配置信息。MistralAiChatOptions.Builder 是一个流畅的选项生成器。

Low-level  MistralAiApi 客户端

下面是一个如何以编程方式使用 api 的简单片段:

MistralAiApi mistralAiApi =
    new MistralAiApi(System.getenv("MISTRAL_AI_API_KEY"));

ChatCompletionMessage chatCompletionMessage =
    new ChatCompletionMessage("Hello world", Role.USER);

// Sync request
ResponseEntity<ChatCompletion> response = mistralAiApi.chatCompletionEntity(
    new ChatCompletionRequest(List.of(chatCompletionMessage), MistralAiApi.ChatModel.LARGE.getValue(), 0.8f, false));

// Streaming request
Flux<ChatCompletionChunk> streamResponse = mistralAiApi.chatCompletionStream(
        new ChatCompletionRequest(List.of(chatCompletionMessage), MistralAiApi.ChatModel.LARGE.getValue(), 0.8f, true));

更多信息请参阅 MistralAiApi.java的 JavaDoc。

MistralAiApi Samples

Mistral AI 函数调用

您可以使用 MistralAiChatModel 注册自定义 Java 函数,并让 Mistral AI 模型智能地选择输出包含调用一个或多个已注册函数的参数的 JSON 对象。这允许您将 LLM 功能与外部工具和 API 连接起来。 open-mixtral-8x22b、mistral_small_latest 和 Mistra_large_latest 模型经过训练,可以检测何时应调用函数并使用符合函数签名的 JSON 进行响应。

MistralAI API 不直接调用该函数;相反,模型会生成 JSON,您可以使用它来调用代码中的函数并将结果返回给模型以完成对话。

截至 2024 年 3 月 13 日,Mistral AI 已在其 mistral_large_latest 模型中集成了对并行函数调用的支持,而这一功能在首个春季 AI Mistral AI 时还不存在。

Spring AI 提供了灵活且用户友好的方式来注册和调用自定义函数。一般来说,自定义函数需要提供函数名称、描述和函数调用签名(作为 JSON 模式),以使模型知道函数需要什么参数。该描述有助于模型理解何时调用该函数。

作为开发人员,您需要实现一个函数,该函数接受从 AI 模型发送的函数调用参数,并将结果响应回模型。您的函数可以依次调用其他第三方服务来提供结果。

Spring AI 使这就像定义一个返回 java.util.Function 的 @Bean 定义一样简单,并在调用 ChatModel 时提供 bean 名称作为选项。

在底层,Spring 使用适当的适配器代码包装您的 POJO(函数),以支持与 AI 模型的交互,从而使您免于编写繁琐的样板代码。底层基础设施的基础是 FunctionCallback.java接口和配套的 FunctionCallbackWrapper.java实用程序类,用于简化 Java 回调函数的实现和注册。

怎么运行的

假设我们想让人工智能模型回应它所不具备的信息,例如某个地点的当前温度。

我们可以向人工智能模型提供有关我们自身功能的元数据,让它在处理您的提示时可以用来检索这些信息。

例如,如果在处理提示时,人工智能模型确定它需要关于给定地点温度的额外信息,它就会启动服务器端生成的请求/响应交互。人工智能模型会调用客户端函数。人工智能模型以 JSON 格式提供方法调用详情,客户端负责执行该函数并返回响应。

Spring AI 大大简化了为支持函数调用而编写的代码。它为您提供函数调用对话的中介。您只需将函数定义作为 @Bean 提供,然后在提示选项中提供函数的 Bean 名称即可。您还可以在提示中引用多个函数 Bean 名称。

快速入门

让我们创建一个聊天机器人,通过调用我们自己的函数来回答问题。为了支持聊天机器人的回答,我们将注册自己的函数,该函数接收一个地点并返回该地点的当前天气。

当需要回答诸如 "波士顿的天气如何?"这样的问题时,人工智能模型将调用客户端,提供位置值作为参数传递给函数。这种类似 RPC 的数据以 JSON 格式传递。

我们的函数会调用一些基于 SaaS 的天气服务 API,并将天气响应返回给模型,以完成对话。在本示例中,我们将使用一个名为 MockWeatherService 的简单实现,它对不同地点的温度进行了硬编码。

下面的 MockWeatherService.java 表示天气服务 API:

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

有了 MistralAiChatModel Auto-Configuration,你就有多种方法在 Spring 上下文中将自定义函数注册为 Bean。

我们首先介绍对 POJO 最友好的选项。

普通 Java 函数

在这种方法中,你可以在应用程序上下文中定义 @Beans,就像定义其他 Spring 托管对象一样。

在内部,Spring AI ChatModel 会创建一个 FunctionCallbackWrapper 封装器实例,该封装器会添加通过 AI 模型调用的逻辑。@Bean 的名称将作为 ChatOption 传递。

@Configuration
static class Config {

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

@Description 注解是可选的,它提供了一个函数描述 (2),帮助模型理解何时调用函数。这是一个重要的属性,可以帮助人工智能模型确定要调用的客户端函数。

另一个提供函数说明的选项是在 MockWeatherService.Request 上使用 @JsonClassDescription 注解来提供函数说明:

@Configuration
static class Config {

	@Bean
	public Function<Request, Response> currentWeather3() { // (1) bean name as function name.
		return new MockWeatherService();
	}
	...
}

@JsonClassDescription("Get the weather in location") // (2) function description
public record Request(String location, Unit unit) {}

最佳做法是在请求对象中注释信息,使生成的函数 JSON 模式尽可能具有描述性,以帮助人工智能模型选择要调用的正确函数。

PaymentStatusBeanIT.java演示了这种方法。

PaymentStatusBeanOpenAiIT使用 OpenAI API 实现了相同的功能。在这方面,MistralAI 与 OpenAI 几乎完全相同。

函数回调包装器

注册函数的另一种方法是创建 FunctionCallbackWrapper 封装器,如下所示:

@Configuration
static class Config {

	@Bean
	public FunctionCallback weatherFunctionInfo() {

		return new FunctionCallbackWrapper<>("CurrentWeather", // (1) function name
				"Get the weather in location", // (2) function description
				(response) -> "" + response.temp() + response.unit(), // (3) Response Converter
				new MockWeatherService()); // function code
	}
	...
}

它封装了第三方 MockWeatherService 函数,并将其注册为 MistralAiChatModel 的 CurrentWeather 函数。它还提供了一个说明 (2) 和一个可选的响应转换器 (3),用于将响应转换成模型所期望的文本。

默认情况下,响应转换器会对响应对象进行 JSON 序列化。

FunctionCallbackWrapper 内部根据 MockWeatherService.Request 类解析函数调用签名。

在聊天选项中指定功能

要让模型知道并调用您的 CurrentWeather 函数,您需要在提示请求中启用它:

MistralAiChatModel chatModel = ...

UserMessage userMessage = new UserMessage("What's the weather like in Paris?");

ChatResponse response = chatModel.call(new Prompt(List.of(userMessage),
		MistralAiChatOptions.builder().withFunction("CurrentWeather").build())); // (1) Enable the function

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

上述用户问题将触发对 CurrentWeather 函数的 3 次调用(每个城市一次),并产生最终回复。

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

除了自动配置外,您还可以通过 Prompt 请求动态注册回调函数:

MistralAiChatModel chatModel = ...

UserMessage userMessage = new UserMessage("What's the weather like in Paris?");

var promptOptions = MistralAiChatOptions.builder()
	.withFunctionCallbacks(List.of(new FunctionCallbackWrapper<>(
		"CurrentWeather", // name
		"Get the weather in location", // function description
		new MockWeatherService()))) // function code
	.build();

ChatResponse response = chatModel.call(new Prompt(List.of(userMessage), promptOptions));

在该请求的持续时间内,提示中注册的功能默认为启用。

这种方法可以根据用户的输入动态地选择要调用的不同函数。

PaymentStatusPromptIT.java 集成测试提供了一个完整示例,说明如何在 MistralAiChatModel 中注册函数并在提示请求中使用该函数。

附录

(博客)使用最新的 Mistral AI API 在 Java 和 Spring AI 中进行函数调用


Mistral AI API 函数调用流程

下图说明了 Mistral AI 底层 API 的函数调用流程

PaymentStatusFunctionCallingIT.java 提供了如何使用 Mistral AI API 函数调用的完整示例。它基于 Mistral AI 函数调用教程

最近更新

  1. TCP协议是安全的吗?

    2024-06-10 21:08:02       14 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-10 21:08:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-10 21:08:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-10 21:08:02       18 阅读

热门阅读

  1. 什么是负载均衡?在网络中如何实现?

    2024-06-10 21:08:02       7 阅读
  2. Spring

    2024-06-10 21:08:02       9 阅读
  3. C语言中整形提升举例说明

    2024-06-10 21:08:02       9 阅读
  4. C#--使用CMake构建C++程序调用示例

    2024-06-10 21:08:02       12 阅读
  5. ubuntu20.04 升级(卸载安装)NVIDIA 驱动程序

    2024-06-10 21:08:02       10 阅读
  6. 硬件工程师学习规划

    2024-06-10 21:08:02       11 阅读
  7. BGP选路规则

    2024-06-10 21:08:02       9 阅读
  8. EntitiesSample_9. CrossQuery

    2024-06-10 21:08:02       11 阅读