跳到主要内容

NVIDIA Chat

Deepseek 3.2 中英对照 NVIDIA NVIDIA Chat

NVIDIA LLM API 是一个代理 AI 推理引擎,提供来自多个提供商的广泛模型。

Spring AI 通过复用现有的 OpenAI 客户端来集成 NVIDIA LLM API。为此,你需要将基础 URL 设置为 https://integrate.api.nvidia.com,选择一个提供的 LLM 模型,并获取其 api-key

Spring AI NVIDIA LLM API 1

备注

NVIDIA LLM API 要求必须明确设置 max-tokens 参数,否则会抛出服务器错误。

请查看 NvidiaWithOpenAiChatModelIT.java 测试文件,其中包含了在 Spring AI 中使用 NVIDIA LLM API 的示例。

前提条件

  • 创建 NVIDIA 账户并确保有足够的积分。

  • 选择一个要使用的 LLM 模型。例如下图截图中所示的 meta/llama-3.1-70b-instruct

  • 在所选模型的页面中,您可以获取用于访问该模型的 api-key

spring ai nvidia 注册

自动配置

备注

Spring AI 的自动配置和 starter 模块的 artifact 名称发生了重大变化。更多信息请参阅升级说明

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

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

或者将其添加到您的 Gradle build.gradle 构建文件中。

dependencies {
implementation 'org.springframework.ai:spring-ai-starter-model-openai'
}

:::提示
参考 依赖管理 章节,将 Spring AI BOM 添加到您的构建文件中。
:::

聊天属性

重试属性

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

属性描述默认值
spring.ai.retry.max-attempts最大重试尝试次数。10
spring.ai.retry.backoff.initial-interval指数退避策略的初始休眠时长。2 秒
spring.ai.retry.backoff.multiplier退避间隔乘数。5
spring.ai.retry.backoff.max-interval最大退避时长。3 分钟
spring.ai.retry.on-client-errors如果为 false,则抛出 NonTransientAiException,且不针对 4xx 客户端错误代码尝试重试。false
spring.ai.retry.exclude-on-http-codes不应触发重试(例如,以抛出 NonTransientAiException)的 HTTP 状态代码列表。
spring.ai.retry.on-http-codes应触发重试(例如,以抛出 TransientAiException)的 HTTP 状态代码列表。

连接属性

前缀 spring.ai.openai 用作属性前缀,使您能够连接到 OpenAI。

属性描述默认值
spring.ai.openai.base-url要连接的 URL。必须设置为 https://integrate.api.nvidia.com-
spring.ai.openai.api-keyNVIDIA API 密钥-

配置属性

备注

现在通过前缀为 spring.ai.model.chat 的顶级属性来配置聊天自动配置的启用与禁用。

若要启用,设置 spring.ai.model.chat=openai(默认已启用)

若要禁用,设置 spring.ai.model.chat=none(或任何与 openai 不匹配的值)

此项变更是为了支持配置多个模型。

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

属性描述默认
spring.ai.openai.chat.enabled (已移除且不再有效)启用 OpenAI 聊天模型。
spring.ai.model.chat启用OpenAI聊天模型。openai
spring.ai.openai.chat.base-url可选,覆盖 spring.ai.openai.base-url 以提供聊天特定 URL。必须设置为 https://integrate.api.nvidia.com-
spring.ai.openai.chat.api-key可选地覆盖 spring.ai.openai.api-key 以提供聊天专用的 API 密钥-
spring.ai.openai.chat.options.model要使用的NVIDIA LLM模型-
spring.ai.openai.chat.options.temperature采样温度用于控制生成完成内容的表观创造力。较高的值会使输出更加随机,而较低的值会使结果更加集中和确定性。不建议在同一完成请求中同时修改温度和top_p参数,因为这两个设置的相互作用难以预测。0.8
spring.ai.openai.chat.options.frequencyPenalty介于 -2.0 和 2.0 之间的数值。正值会根据新词元在文本中已有的出现频率对其进行惩罚,从而降低模型逐字重复相同内容的可能性。0.0f
spring.ai.openai.chat.options.maxTokens聊天补全生成的最大令牌数。输入令牌和生成令牌的总长度受模型上下文长度限制。注意:NVIDIA LLM API 要求必须显式设置 max-tokens 参数,否则会抛出服务器错误。
spring.ai.openai.chat.options.n为每条输入消息生成多少个聊天完成选项。请注意,您将根据所有选项中生成的令牌总数收费。将 n 保持为 1 以最小化成本。1
spring.ai.openai.chat.options.presencePenalty数值范围在-2.0到2.0之间。正值会根据新令牌是否已在现有文本中出现来施加惩罚,从而增加模型转向新话题的可能性。-
spring.ai.openai.chat.options.responseFormat一个指定模型必须输出格式的对象。将其设置为 { "type": "json_object" } 可启用 JSON 模式,这能保证模型生成的消息是有效的 JSON。-
spring.ai.openai.chat.options.seed此功能目前处于测试阶段。若指定该功能,我们的系统将尽力确保采样的确定性,即在相同种子和参数条件下,重复请求应返回相同的结果。-
spring.ai.openai.chat.options.stop最多 4 个序列,API 将停止生成更多标记。-
spring.ai.openai.chat.options.topP除了使用温度进行采样外,还有一种称为核心采样的替代方法。在这种方法中,模型仅考虑累积概率质量达到 top_p 的令牌结果。例如,top_p 设为 0.1 意味着只考虑构成前 10% 概率质量的令牌。通常我们建议调整此参数或温度参数,但不要同时调整两者。-
spring.ai.openai.chat.options.tools模型可以调用的工具列表。目前仅支持函数作为工具。使用此选项可提供模型可能生成 JSON 输入的函数列表。-
spring.ai.openai.chat.options.toolChoice控制模型调用哪个(如果有的话)函数。none 表示模型不会调用函数,而是生成一条消息。auto 表示模型可以选择生成消息或调用函数。通过 {"type": "function", "function": {"name": "my_function"}} 指定特定函数会强制模型调用该函数。当没有函数存在时,默认值为 none。当存在函数时,默认值为 auto-
spring.ai.openai.chat.options.user一个代表您最终用户的唯一标识符,可以帮助OpenAI监控和检测滥用行为。-
spring.ai.openai.chat.options.stream-usage(仅限流式传输) 设置此项可为整个请求添加包含令牌使用统计信息的额外数据块。该数据块的 choices 字段为空数组,所有其他数据块也将包含 usage 字段,但其值为 null。false
spring.ai.openai.chat.options.tool-names工具列表,通过其名称标识,用于在单个提示请求中启用函数调用。具有这些名称的工具必须存在于 ToolCallback 注册表中。-
spring.ai.openai.chat.options.tool-callbacks要注册到 ChatModel 的回调函数。-
spring.ai.openai.chat.options.internal-tool-execution-enabled如果为 false,Spring AI 将不会在内部处理工具调用,而是将其代理给客户端。此时,客户端负责处理工具调用、分派到相应函数并返回结果。如果为 true(默认值),Spring AI 将在内部处理函数调用。仅适用于支持函数调用的聊天模型。
提示

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

运行时选项

OpenAiChatOptions.java 提供了模型配置,例如使用的模型、温度参数、频率惩罚等。

启动时,可通过 OpenAiChatModel(api, options) 构造函数或 spring.ai.openai.chat.options.* 属性配置默认选项。

在运行时,你可以通过在 Prompt 调用中添加新的、针对特定请求的选项来覆盖默认选项。例如,为特定请求覆盖默认模型和温度参数:

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 实例,它可以通过 ChatOptions#builder() 来创建。

函数调用

NVIDIA LLM API 在选择支持该功能的模型时支持工具/函数调用。

Spring AI NVIDIA 函数调用

您可以为ChatModel注册自定义Java函数,并让所提供的模型智能地选择输出包含调用一个或多个注册函数参数的JSON对象。这是一种将大语言模型能力与外部工具和API连接起来的强大技术。

工具示例

以下是使用Spring AI调用NVIDIA LLM API函数的一个简单示例:

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

在这个例子中,当模型需要天气信息时,它会自动调用 weatherFunction bean,从而获取实时天气数据。预期响应如下:"阿姆斯特丹目前的气温为 20 摄氏度,巴黎目前的气温为 25 摄氏度。"

了解更多关于OpenAI 函数调用的信息。

示例控制器

创建一个新的 Spring Boot 项目,并将 spring-ai-starter-model-openai 添加到你的 pom(或 gradle)依赖中。

src/main/resources 目录下添加一个 application.properties 文件,以启用并配置 OpenAi 聊天模型:

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 类示例。

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