NVIDIA 聊天

NVIDIA LLM API 是一個代理 AI 推理引擎,提供了來自各種提供商的多種模型。

Spring AI 透過複用現有的OpenAI客戶端與 NVIDIA LLM API 整合。為此,您需要將 base-url 設定為 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 registration

自動配置

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

不應觸發重試的 HTTP 狀態碼列表(例如,用於丟擲 NonTransientAiException)。

spring.ai.retry.on-http-codes

應觸發重試的 HTTP 狀態碼列表(例如,用於丟擲 TransientAiException)。

連線屬性

字首 spring.ai.openai 用作屬性字首,允許您連線到 OpenAI。

屬性 描述 預設值

spring.ai.openai.base-url

要連線的 URL。必須設定為 integrate.api.nvidia.com

-

spring.ai.openai.api-key

NVIDIA 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 聊天模型。

true

spring.ai.model.chat

啟用 OpenAI 聊天模型。

openai

spring.ai.openai.chat.base-url

可選地覆蓋 spring.ai.openai.base-url 以提供聊天特定的 URL。必須設定為 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

用於控制生成補全內容的表觀創造性的取樣溫度。值越高,輸出越隨機;值越低,結果越集中和確定性。不建議在同一補全請求中同時修改 temperature 和 top_p,因為這兩個設定的相互作用難以預測。

0.8

spring.ai.openai.chat.options.frequencyPenalty

介於 -2.0 和 2.0 之間的數字。正值會根據新 token 在文字中已出現的頻率來懲罰新 token,從而降低模型逐字重複同一行的可能性。

0.0f

spring.ai.openai.chat.options.maxTokens

在聊天補全中生成的最大 token 數。輸入 token 和生成 token 的總長度受限於模型的上下文長度。

注意:NVIDIA LLM API 要求顯式設定 max-tokens 引數,否則將丟擲伺服器錯誤。

spring.ai.openai.chat.options.n

為每個輸入訊息生成多少個聊天補全選項。請注意,您將根據所有選項生成的 token 總數計費。將 n 設為 1 以最小化成本。

1

spring.ai.openai.chat.options.presencePenalty

介於 -2.0 和 2.0 之間的數字。正值會根據新 token 是否已出現在文字中來懲罰新 token,從而增加模型談論新主題的可能性。

-

spring.ai.openai.chat.options.responseFormat

一個物件,指定模型必須輸出的格式。設定為 { "type": "json_object" } 可啟用 JSON 模式,這保證模型生成的訊息是有效的 JSON。

-

spring.ai.openai.chat.options.seed

此功能處於 Beta 階段。如果指定,我們的系統將盡最大努力進行確定性取樣,以便使用相同的種子和引數重複請求時應返回相同的結果。

-

spring.ai.openai.chat.options.stop

API 將停止生成後續 token 的最多 4 個序列。

-

spring.ai.openai.chat.options.topP

一種替代溫度取樣的核取樣(nucleus sampling)方法,模型會考慮 top_p 機率質量的 token 結果。因此,0.1 意味著只考慮構成前 10% 機率質量的 token。我們通常建議修改此引數或 temperature,但不要同時修改兩者。

-

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.functions

函式列表,按名稱標識,用於在單個 prompt 請求中啟用函式呼叫。具有這些名稱的函式必須存在於 functionCallbacks 登錄檔中。

-

spring.ai.openai.chat.options.stream-usage

(僅用於流式傳輸)設定為新增一個額外的塊,其中包含整個請求的 token 使用統計資訊。此塊的 choices 欄位是一個空陣列,所有其他塊也將包含一個 usage 欄位,但其值為 null。

false

spring.ai.openai.chat.options.proxy-tool-calls

如果為 true,Spring AI 將不內部處理函式呼叫,而是將其代理給客戶端。然後由客戶端負責處理函式呼叫,將其分派給適當的函式,並返回結果。如果為 false(預設值),Spring AI 將在內部處理函式呼叫。僅適用於支援函式呼叫的聊天模型。

false

所有帶有 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 function calling

您可以在 ChatModel 中註冊自定義 Java 函式,讓提供的模型智慧地選擇輸出一個包含呼叫一個或多個已註冊函式所需引數的 JSON 物件。這是一種將 LLM 功能與外部工具和 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,然後該 bean 可以獲取即時天氣資料。預期的響應如下所示:“阿姆斯特丹目前天氣為 20 攝氏度,巴黎目前天氣為 25 攝氏度。”

閱讀更多關於 OpenAI 函式呼叫的內容。

示例 Controller

建立一個新的 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-tokens 引數,否則將丟擲伺服器錯誤。

這是一個使用聊天模型生成文字的簡單 @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);
    }
}