此版本仍在开发中,尚未被视为稳定版。为了获取最新的快照版本,请使用Spring AI 1.1.3spring-doc.cadn.net.cn

NVIDIA 聊天

NVIDIA LLM API 是一个代理AI推理引擎,提供了来自多个提供商的广泛模型选择。spring-doc.cadn.net.cn

Spring AI 通过复用现有的 OpenAI 客户端与 NVIDIA LLM API 集成。 为此,您需要将基础网址设置为 https://integrate.api.nvidia.com,选择提供的 LLM 模型 之一,并为其获取一个 api-keyspring-doc.cadn.net.cn

spring ai nvidia llm api 1
NVIDIA LLM API 需要显式设置 max-tokens 参数,否则将抛出服务器错误。

查看NvidiaWithOpenAiChatModelIT.java测试 中的示例,了解如何在Spring AI中使用NVIDIA LLM API。spring-doc.cadn.net.cn

前提条件

spring ai nvidia registration

自动配置

There has been a significant change in the Spring AI auto-configuration, starter modules' artifact names. Please refer to the 升级说明以获取更多信息。spring-doc.cadn.net.cn

Spring AI 为 OpenAI 聊天客户端提供了 Spring Boot 自动配置功能。要启用此功能,请在项目的 Maven pom.xml 文件中添加以下依赖项:spring-doc.cadn.net.cn

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>

或者添加到您的Gradle 构建脚本文件中。spring-doc.cadn.net.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-model-openai'
}
参考以下依赖管理部分,添加Spring AI BOM到你的构建文件中。

聊天属性

重试属性

前缀 spring.ai.retry 用于作为属性前缀,允许您配置OpenAI聊天模型的重试机制。spring-doc.cadn.net.cn

属性 描述 默认

spring.ai.retry.max-attemptsspring-doc.cadn.net.cn

最大重试次数。spring-doc.cadn.net.cn

10spring-doc.cadn.net.cn

spring.ai.retry.backoff.initial-intervalspring-doc.cadn.net.cn

指数退避策略的初始睡眠时长。spring-doc.cadn.net.cn

2 秒spring-doc.cadn.net.cn

spring.ai.retry.backoff.multiplierspring-doc.cadn.net.cn

退避间隔乘数。spring-doc.cadn.net.cn

5spring-doc.cadn.net.cn

spring.ai.retry.backoff.max-intervalspring-doc.cadn.net.cn

最大退避时长。spring-doc.cadn.net.cn

3 分钟。spring-doc.cadn.net.cn

spring.ai.retry.on-client-errorsspring-doc.cadn.net.cn

如果为false,则抛出NonTransientAiException,且不重试客户端错误代码4xxspring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

spring.ai.retry.exclude-on-http-codesspring-doc.cadn.net.cn

不应触发重试的HTTP状态代码列表(例如,用于抛出非暂时性AI异常)。spring-doc.cadn.net.cn

emptyspring-doc.cadn.net.cn

spring.ai.retry.on-http-codesspring-doc.cadn.net.cn

应触发重试的HTTP状态码列表(例如,用于抛出TransientAiException)。spring-doc.cadn.net.cn

emptyspring-doc.cadn.net.cn

连接属性

前缀 spring.ai.openai 用于作为属性前缀,以便您连接到OpenAI。spring-doc.cadn.net.cn

属性 描述 默认

spring.ai.openai.base-urlspring-doc.cadn.net.cn

连接到的URL。必须设置为https://integrate.api.nvidia.comspring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.api-keyspring-doc.cadn.net.cn

NVIDIA API 密钥spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

配置属性

启用和禁用聊天自动配置现在通过顶级属性使用前缀 spring.ai.model.chat 配置完成。spring-doc.cadn.net.cn

要启用,请设置 spring.ai.model.chat=openai (默认情况下已启用)spring-doc.cadn.net.cn

要禁用,请设置 spring.ai.model.chat=none(或任何不匹配 openai 的值)spring-doc.cadn.net.cn

这种修改是为了允许配置多个模型。spring-doc.cadn.net.cn

前缀 spring.ai.openai.chat 是属性前缀,用于配置OpenAI聊天模型的实现方式。spring-doc.cadn.net.cn

属性 描述 默认

spring.ai.openai.chat.enabled(已移除,不再有效)spring-doc.cadn.net.cn

启用OpenAI聊天模型。spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

spring.ai.model.chatspring-doc.cadn.net.cn

启用OpenAI聊天模型。spring-doc.cadn.net.cn

开源人工智能spring-doc.cadn.net.cn

spring.ai.openai.chat.base-urlspring-doc.cadn.net.cn

可选地覆盖spring.ai.openai.base-url以提供聊天特定的URL。必须设置为https://integrate.api.nvidia.comspring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.api-keyspring-doc.cadn.net.cn

可选地,覆盖 `spring.ai.openai.api-key` 以提供聊天特定的 API 密钥。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.options.modelspring-doc.cadn.net.cn

要使用的NVIDIA LLM模型spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.options.temperaturespring-doc.cadn.net.cn

用于控制生成完成内容的表面创新性的采样温度。较高的值会使输出更加随机,而较低的值会使结果更加集中和确定性。不建议在同一完成请求中同时修改温度(temperature)和顶级概率(top_p),因为这两个设置之间的相互作用难以预测。spring-doc.cadn.net.cn

0.8spring-doc.cadn.net.cn

spring.ai.openai.chat.options.frequencyPenaltyspring-doc.cadn.net.cn

介于-2.0和2.0之间的数值。正值会根据新词在文本中已有的出现频率对其进行惩罚,从而降低模型重复相同行文的确切概率。spring-doc.cadn.net.cn

0.0fspring-doc.cadn.net.cn

spring.ai.openai.chat.options.maxTokensspring-doc.cadn.net.cn

聊天补全时生成的最大Tokens数量。输入Tokens和生成Tokens的总长度受到模型上下文长度的限制。spring-doc.cadn.net.cn

注意:NVIDIA LLM API 需要显式设置 max-tokens 参数,否则将抛出服务器错误。spring-doc.cadn.net.cn

spring.ai.openai.chat.options.nspring-doc.cadn.net.cn

针对每条输入消息生成的聊天补全选项数量。请注意,您将根据所有选项生成的Tokens总数来计费。为了最小化成本,请将 n 保持为 1。spring-doc.cadn.net.cn

1spring-doc.cadn.net.cn

spring.ai.openai.chat.options.presencePenaltyspring-doc.cadn.net.cn

介于-2.0和2.0之间的数值。正值会根据新词是否已出现在文本中对其进行惩罚,从而增加模型谈论新主题的可能性。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.options.responseFormatspring-doc.cadn.net.cn

指定模型输出格式的对象。设置为{ "type": "json_object" }启用JSON模式,确保模型生成的消息是有效的JSON格式。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.options.seedspring-doc.cadn.net.cn

此功能处于测试阶段。如果指定了,我们的系统将尽力进行确定性采样,以便使用相同的种子和参数的重复请求应返回相同的结果。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.options.stopspring-doc.cadn.net.cn

最多4个序列,到达这些序列后API将停止生成更多Tokens。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.options.topPspring-doc.cadn.net.cn

一种替代温度采样的方法称为核采样,模型会考虑具有前p概率质量的Tokens的结果。因此,0.1意味着只考虑构成前10%概率质量的Tokens。我们通常建议调整这个参数或温度,但不建议同时调整两者。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.options.toolsspring-doc.cadn.net.cn

模型可能调用的工具列表。当前,仅支持函数作为工具。使用此功能来提供模型可能为其生成JSON输入的函数列表。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.options.toolChoicespring-doc.cadn.net.cn

控制模型调用(如有)哪个函数。none 表示模型将不调用任何函数,而直接生成消息。auto 表示模型可以在生成消息或调用函数之间进行选择。通过 {"type": "function", "function": {"name": "my_function"}} 指定特定函数会强制模型调用该函数。当没有提供函数时,默认为 none。如果存在函数,则默认为 auto。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.options.userspring-doc.cadn.net.cn

代表您终端用户的唯一标识符,有助于OpenAI监控和检测滥用行为。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.options.stream-usagespring-doc.cadn.net.cn

(仅限流式处理)设置此选项可添加一个额外的块,用于统计整个请求的Tokens使用情况。此块的choices字段为空数组,所有其他块也将包含一个使用情况字段,但其值为null。spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

spring.ai.openai.chat.options.tool-namesspring-doc.cadn.net.cn

用于在单个提示请求中启用函数调用的工具列表,这些工具通过它们的名称来识别。具有这些名称的工具必须存在于ToolCallback注册表中。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.options.tool-callbacksspring-doc.cadn.net.cn

向ChatModel注册的工具回调。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.options.internal-tool-execution-enabledspring-doc.cadn.net.cn

如果为 false,Spring AI 将不内部处理工具调用,而是将它们代理给客户端。此后,处理工具调用、将其分派给适当函数并返回结果的责任在于客户端。如果为 true(默认值),Spring AI 将内部处理函数调用。此设置仅适用于支持函数调用的聊天模型。spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

所有以spring.ai.openai.chat.options为前缀的属性都可以通过向Prompt调用中添加特定于请求的运行时选项在运行时覆盖。

运行时选项

OpenAiChatOptions.java 文件提供了模型配置,如使用的模型、温度、频率惩罚等参数。spring-doc.cadn.net.cn

On start-up, the default options can be configured with the OpenAiChatModel(api, options) constructor or the spring.ai.openai.chat.options.* properties.spring-doc.cadn.net.cn

在运行时,您可以通过向Prompt调用添加新的、针对请求的选项来覆盖默认选项。 例如,要为特定请求覆盖默认模型和温度:spring-doc.cadn.net.cn

ChatResponse response = chatModel.call(
    new Prompt(
        "Generate the names of 5 famous pirates.",
        OpenAiChatOptions.builder()
            .model("mixtral-8x7b-32768")
            .temperature(0.4)
        .build()
    ));
除了特定于模型的OpenAiChatOptions之外,您还可以使用通过ChatOptions#builder()创建的可移植ChatOptions实例。

函数调用

NVIDIA LLM API 支持在选择支持此功能的模型时进行工具/函数调用。spring-doc.cadn.net.cn

spring ai nvidia function calling

您可以向ChatModel注册自定义的Java函数,并让提供的模型智能地选择输出一个JSON对象,该对象包含调用一个或多个已注册函数的参数。 这是一种强大的技术,用于将LLM功能与外部工具和API连接起来。spring-doc.cadn.net.cn

工具示例

下面是一个使用Spring AI调用NVIDIA LLM API函数的简单示例:spring-doc.cadn.net.cn

spring.ai.openai.api-key=${NVIDIA_API_KEY}
spring.ai.openai.base-url=https://integrate.api.nvidia.com
spring.ai.openai.chat.options.model=meta/llama-3.1-70b-instruct
spring.ai.openai.chat.options.max-tokens=2048
@SpringBootApplication
public class NvidiaLlmApplication {

    public static void main(String[] args) {
        SpringApplication.run(NvidiaLlmApplication.class, args);
    }

    @Bean
    CommandLineRunner runner(ChatClient.Builder chatClientBuilder) {
        return args -> {
            var chatClient = chatClientBuilder.build();

            var response = chatClient.prompt()
                .user("What is the weather in Amsterdam and Paris?")
                .functions("weatherFunction") // reference by bean name.
                .call()
                .content();

            System.out.println(response);
        };
    }

    @Bean
    @Description("Get the weather in location")
    public Function<WeatherRequest, WeatherResponse> weatherFunction() {
        return new MockWeatherService();
    }

    public static class MockWeatherService implements Function<WeatherRequest, WeatherResponse> {

        public record WeatherRequest(String location, String unit) {}
        public record WeatherResponse(double temp, String unit) {}

        @Override
        public WeatherResponse apply(WeatherRequest request) {
            double temperature = request.location().contains("Amsterdam") ? 20 : 25;
            return new WeatherResponse(temperature, request.unit);
        }
    }
}

在此示例中,当模型需要天气信息时,它将自动调用weatherService bean,后者可以获取实时天气数据。 预期的响应如下:"阿姆斯特丹当前的天气为20摄氏度,巴黎当前的天气为25摄氏度。"spring-doc.cadn.net.cn

了解更多关于OpenAI的函数调用功能。spring-doc.cadn.net.cn

示例控制器

创建一个新的Spring Boot项目,并将spring-boot-starter-web添加到您的pom(或gradle)依赖中。spring-doc.cadn.net.cn

src/main/resources目录下添加一个application.properties文件,以启用和配置OpenAi聊天模型:spring-doc.cadn.net.cn

spring.ai.openai.api-key=${NVIDIA_API_KEY}
spring.ai.openai.base-url=https://integrate.api.nvidia.com
spring.ai.openai.chat.options.model=meta/llama-3.1-70b-instruct

# The NVIDIA LLM API doesn't support embeddings, so we need to disable it.
spring.ai.openai.embedding.enabled=false

# The NVIDIA LLM API requires this parameter to be set explicitly or server internal error will be thrown.
spring.ai.openai.chat.options.max-tokens=2048
api-key替换为您的NVIDIA凭据。
NVIDIA LLM API 需要显式设置 max-token 参数,否则将抛出服务器错误。

这是一个使用聊天模型进行文本生成的简单@Controller类的例子。spring-doc.cadn.net.cn

@RestController
public class ChatController {

    private final OpenAiChatModel chatModel;

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

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

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