Groq 聊天

Groq 是一個基於 LPU™ 的超高速 AI 推理引擎,支援各種 AI 模型,支援 工具/函式呼叫 並公開了與 OpenAI API 相容的端點。

Spring AI 透過重用現有的 OpenAI 客戶端與 Groq 整合。為此,您需要獲取一個 Groq Api Key,將基礎 URL 設定為 api.groq.com/openai,並選擇一個提供的 Groq 模型

spring ai groq integration
Groq API 不完全相容 OpenAI API。請注意以下 相容性限制。此外,Groq 目前不支援多模態訊息。

檢視 GroqWithOpenAiChatModelIT.java 測試,瞭解如何將 Groq 與 Spring AI 結合使用的示例。

先決條件

  • 建立 API 金鑰:訪問 此處 建立 API 金鑰。Spring AI 專案定義了一個名為 spring.ai.openai.api-key 的配置屬性,您應該將其設定為從 groq.com 獲取的 API 金鑰 的值。

  • 設定 Groq URL:您必須將 spring.ai.openai.base-url 屬性設定為 https://api.groq.com/openai

  • 選擇 Groq 模型:使用 spring.ai.openai.chat.model=<模型名稱> 屬性從可用的 Groq 模型 中選擇。

您可以在 application.properties 檔案中設定這些配置屬性

spring.ai.openai.api-key=<your-groq-api-key>
spring.ai.openai.base-url=https://api.groq.com/openai
spring.ai.openai.chat.model=llama3-70b-8192

為了在處理 API 金鑰等敏感資訊時增強安全性,您可以使用 Spring 表示式語言 (SpEL) 來引用自定義環境變數

# In application.yml
spring:
  ai:
    openai:
      api-key: ${GROQ_API_KEY}
      base-url: ${GROQ_BASE_URL}
      chat:
        model: ${GROQ_MODEL}
# In your environment or .env file
export GROQ_API_KEY=<your-groq-api-key>
export GROQ_BASE_URL=https://api.groq.com/openai
export GROQ_MODEL=llama3-70b-8192

您還可以在應用程式程式碼中以程式設計方式設定這些配置

// Retrieve configuration from secure sources or environment variables
String apiKey = System.getenv("GROQ_API_KEY");
String baseUrl = System.getenv("GROQ_BASE_URL");
String model = System.getenv("GROQ_MODEL");

新增儲存庫和 BOM

Spring AI 工件釋出在 Maven Central 和 Spring Snapshot 儲存庫中。請參閱 工件儲存庫 部分,將這些儲存庫新增到您的構建系統。

為了幫助管理依賴項,Spring AI 提供了一個 BOM(物料清單),以確保在整個專案中使用的 Spring AI 版本一致。請參閱 依賴項管理 部分,將 Spring AI BOM 新增到您的構建系統。

自動配置

Spring AI 自動配置、啟動模組的工件名稱發生了重大變化。請參閱 升級說明 以獲取更多資訊。

Spring AI 為 OpenAI 聊天客戶端提供了 Spring Boot 自動配置。要啟用它,請將以下依賴項新增到您的專案的 Maven pom.xml 或 Gradle build.gradle 構建檔案中

  • Maven

  • Gradle

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
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 客戶端錯誤程式碼

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。必須設定為 https://api.groq.com/openai

-

spring.ai.openai.api-key

Groq 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.openai.chat

啟用 OpenAI 聊天模型。

openai

spring.ai.openai.chat.base-url

可選覆蓋 spring.ai.openai.base-url 以提供特定於聊天的 URL。必須設定為 https://api.groq.com/openai

-

spring.ai.openai.chat.api-key

可選覆蓋 spring.ai.openai.api-key 以提供特定於聊天的 api-key

-

spring.ai.openai.chat.options.model

可用模型 名稱為 llama3-8b-8192, llama3-70b-8192, mixtral-8x7b-32768, gemma2-9b-it

-

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

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

-

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

此功能處於 Beta 階段。如果指定,我們的系統將盡力確定性地取樣,以便具有相同種子和引數的重複請求應返回相同的結果。

-

spring.ai.openai.chat.options.stop

API 將停止生成更多令牌的最多 4 個序列。

-

spring.ai.openai.chat.options.topP

除了使用溫度取樣之外的另一種方法,稱為核取樣,模型考慮具有 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。

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 將在內部處理函式呼叫。僅適用於支援函式呼叫的聊天模型

true

所有以 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() 建立。

函式呼叫

Groq API 端點支援 工具/函式呼叫,當選擇支援工具/函式的模型時。

檢視工具 支援的模型
spring ai groq functions 2

您可以使用 ChatModel 註冊自定義 Java 函式,並讓提供的 Groq 模型智慧地選擇輸出包含引數的 JSON 物件,以呼叫一個或多個註冊函式。這是一種將 LLM 功能與外部工具和 API 連線的強大技術。

工具示例

下面是 Spring AI 如何使用 Groq 函式呼叫的一個簡單示例

@SpringBootApplication
public class GroqApplication {

    public static void main(String[] args) {
        SpringApplication.run(GroqApplication.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 函式呼叫 的更多資訊。

多模態

目前 Groq API 不支援媒體內容。

示例控制器

建立 一個新的 Spring Boot 專案,並將 spring-ai-starter-model-openai 新增到您的 pom(或 gradle)依賴項中。

src/main/resources目錄下新增一個application.properties檔案,以啟用和配置 OpenAi 聊天模型

spring.ai.openai.api-key=<GROQ_API_KEY>
spring.ai.openai.base-url=https://api.groq.com/openai
spring.ai.openai.chat.options.model=llama3-70b-8192
spring.ai.openai.chat.options.temperature=0.7
api-key 替換為您的 OpenAI 憑據。

這將建立一個 OpenAiChatModel 實現,您可以將其注入到您的類中。這是一個使用聊天模型進行文字生成的簡單 @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);
    }
}

手動配置

OpenAiChatModel 實現了 ChatModelStreamingChatModel,並使用 [低階 API] 連線到 OpenAI 服務。

spring-ai-openai 依賴項新增到您的專案的 Maven pom.xml 檔案中

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

或新增到您的 Gradle build.gradle 構建檔案中。

dependencies {
    implementation 'org.springframework.ai:spring-ai-openai'
}
請參閱 依賴項管理 部分,將 Spring AI BOM 新增到您的構建檔案中。

接下來,建立一個 OpenAiChatModel 並將其用於文字生成

var openAiApi = new OpenAiApi("https://api.groq.com/openai", System.getenv("GROQ_API_KEY"));
var openAiChatOptions = OpenAiChatOptions.builder()
            .model("llama3-70b-8192")
            .temperature(0.4)
            .maxTokens(200)
        .build();
var chatModel = new OpenAiChatModel(this.openAiApi, this.openAiChatOptions);


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

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

OpenAiChatOptions 提供聊天請求的配置資訊。OpenAiChatOptions.Builder 是一個流暢的選項構建器。

© . This site is unofficial and not affiliated with VMware.