Groq 聊天
Spring AI 透過重複使用現有的 OpenAI 用戶端來與 Groq 整合。為此,您需要取得一個 Groq API 金鑰,將 base-url 設定為 api.groq.com/openai,並選擇一個提供的 Groq 模型。

Groq API 並不完全與 OpenAI API 相容。請注意以下相容性限制。此外,目前 Groq 不支援多模態訊息。 |
請查看 GroqWithOpenAiChatModelIT.java 測試,以取得搭配 Spring AI 使用 Groq 的範例。
先決條件
-
建立 API 金鑰。請造訪這裡建立 API 金鑰。Spring AI 專案定義了一個名為
spring.ai.openai.api-key
的組態屬性,您應該將其設定為從 groq.com 取得的API 金鑰
值。 -
設定 Groq URL。您必須將
spring.ai.openai.base-url
屬性設定為api.groq.com/openai
。 -
選擇 Groq 模型。使用
spring.ai.openai.chat.model=<模型名稱>
屬性來設定模型。
匯出環境變數是設定該組態屬性的一種方式
export SPRING_AI_OPENAI_API_KEY=<INSERT GROQ API KEY HERE>
export SPRING_AI_OPENAI_BASE_URL=https://api.groq.com/openai
export SPRING_AI_OPENAI_CHAT_MODEL=llama3-70b-8192
自動組態
Spring AI 為 OpenAI 聊天用戶端提供 Spring Boot 自動組態。若要啟用它,請將以下依賴性新增至您專案的 Maven pom.xml
或 Gradle build.gradle
建置檔案
-
Maven
-
Gradle
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>
dependencies {
implementation 'org.springframework.ai:spring-ai-openai-spring-boot-starter'
}
請參閱依賴性管理章節,將 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,且不嘗試重試 |
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。必須設定為 |
- |
spring.ai.openai.api-key |
Groq API 金鑰 |
- |
組態屬性
前綴 spring.ai.openai.chat
是屬性前綴,可讓您設定 OpenAI 的聊天模型實作。
屬性 | 描述 | 預設值 |
---|---|---|
spring.ai.openai.chat.enabled |
啟用 OpenAI 聊天模型。 |
true |
spring.ai.openai.chat.base-url |
選用,覆寫 spring.ai.openai.base-url 以提供聊天專用 URL。必須設定為 |
- |
spring.ai.openai.chat.api-key |
選用,覆寫 spring.ai.openai.api-key 以提供聊天專用 API 金鑰 |
- |
spring.ai.openai.chat.options.model |
可用的模型名稱為 |
- |
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 |
指定模型必須輸出格式的物件。設定為 |
- |
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.functions |
函式清單,依其名稱識別,以在單一提示請求中啟用函式呼叫。具有這些名稱的函式必須存在於 functionCallbacks 登錄檔中。 |
- |
spring.ai.openai.chat.options.stream-usage |
(僅限串流) 設定為新增額外區塊,其中包含整個請求的權杖使用量統計資訊。此區塊的 |
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()
.withModel("mixtral-8x7b-32768")
.withTemperature(0.4)
.build()
));
除了模型特定的 OpenAiChatOptions 之外,您還可以使用可攜式 ChatOptions 執行個體,使用 ChatOptionsBuilder#builder() 建立。 |
函式呼叫
Groq API 端點在選擇支援工具/函式的模型時,支援工具/函式呼叫。
查看工具支援的模型。 |

您可以向 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,然後可以擷取即時天氣資料。預期的回應看起來像這樣:「阿姆斯特丹目前的天氣為攝氏 20 度,巴黎目前的天氣為攝氏 25 度。」
深入瞭解 OpenAI 函式呼叫。
範例控制器
建立新的 Spring Boot 專案,並將 spring-ai-openai-spring-boot-starter
新增至您的 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 實作 ChatModel
和 StreamingChatModel
,並使用 [low-level-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()
.withModel("llama3-70b-8192")
.withTemperature(0.4)
.withMaxTokens(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
是流暢的選項建構器。