Groq
本站(springdoc.cn)中的内容来源于 spring.io ,原始版权归属于 spring.io。由 springdoc.cn 进行翻译,整理。可供个人学习、研究,未经许可,不得进行任何转载、商用或与之相关的行为。 商标声明:Spring 是 Pivotal Software, Inc. 在美国以及其他国家的商标。 |
Spring AI 通过复用现有 OpenAI 客户端与 Groq 集成。你需要获取 Groq Api Key,将 base-url 设置为 api.groq.com/openai
,并选择提供的 Groq 模型 之一。

Groq API 与 OpenAI API 并非完全兼容,请注意 这些限制。此外,当前 Groq 不支持多模态消息。 |
查看 GroqWithOpenAiChatModelIT.java 测试类,获取 Spring AI 与 Groq 结合使用的示例。
前提条件
-
创建 API Key:访问 此处 生成 API Key。Spring AI 项目定义了
spring.ai.openai.api-key
配置属性,需将其设置为从 groq.com 获取的API Key
值。 -
设置 Groq URL:必须将
spring.ai.openai.base-url
属性配置为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 Key)时的安全性,可使用 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 中央仓库 和Spring Snapshot 仓库。请参阅 Artifact 仓库 章节将这些仓库添加到您的构建系统。
为简化依赖管理,Spring AI 提供 BOM 以确保整个项目使用统一版本的 Spring AI。请参阅 依赖管理 章节将 Spring AI BOM 添加到你的构建系统。
自动配置
Spring AI 自动配置和 Starter 模块的构件名称已发生重大变更。更多信息请参阅 升级说明。 |
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 sec. |
spring.ai.retry.backoff.multiplier |
退避间隔乘数。 |
5 |
spring.ai.retry.backoff.max-interval |
最大退避时长。 |
3 min. |
spring.ai.retry.on-client-errors |
若为 false,则抛出 |
false |
spring.ai.retry.exclude-on-http-codes |
不应触发重试的 HTTP 状态码列表(例如用于抛出 |
empty |
spring.ai.retry.on-http-codes |
应触发重试的HTTP状态码列表(例如用于抛出 `TransientAiExceptio`n) |
empty |
连接属性
前缀 spring.ai.openai
用于配置连接至 OpenAI 的属性参数。
属性 | 说明 | 默认 |
---|---|---|
spring.ai.openai.base-url |
连接 URL 必须设置为: |
- |
spring.ai.openai.api-key |
Groq API Key |
- |
配置属性
聊天自动配置的启用/禁用现在通过顶级属性
此项变更为支持多模型配置。 |
前缀 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.chat.api-key |
可选覆盖 |
- |
spring.ai.openai.chat.options.model |
可用模型 名称包括: |
- |
spring.ai.openai.chat.options.temperature |
采样温度值,用于控制生成内容的表观创造力。数值越高输出越随机,数值越低结果越集中且确定。不建议在同一补全请求中同时修改 temperature 和 top_p 参数,因两者的交互作用难以预测。 |
0.8 |
spring.ai.openai.chat.options.frequencyPenalty |
介于 -2.0 到 2.0 之间的数值。正值会根据 Token 在已生成文本中的现有频率进行惩罚,从而降低模型逐字重复相同内容的可能性。 |
0.0f |
spring.ai.openai.chat.options.maxTokens |
聊天补全中生成的最大 Token 数量。输入 Token 和生成 Token 的总长度受模型上下文长度限制。 |
- |
spring.ai.openai.chat.options.n |
为每条输入消息生成的聊天补全选项数量。请注意:费用将基于所有选项生成的 Token 总数计算。保持 n=1 可最小化成本。 |
1 |
spring.ai.openai.chat.options.presencePenalty |
介于 -2.0 到 2.0 之间的数值。正值会根据 Token 是否已在已生成文本中出现进行惩罚,从而提高模型讨论新话题的可能性。 |
- |
spring.ai.openai.chat.options.responseFormat |
指定模型输出格式的对象。设置为 |
- |
spring.ai.openai.chat.options.seed |
该功能处于 Beta 阶段。若指定种子值,系统将尽力确保确定性采样——相同种子和参数的重复请求应返回相同结果。 |
- |
spring.ai.openai.chat.options.stop |
最多可设置 4 个停止序列,当 API 遇到这些序列时将停止生成后续 Token。 |
- |
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 |
控制模型调用函数的行为: |
- |
spring.ai.openai.chat.options.user |
用于标识终端用户的唯一ID,可帮助监测和防范滥用行为。 |
- |
spring.ai.openai.chat.options.functions |
函数名称列表,用于在单次提示请求中启用函数调用功能。这些名称对应的函数必须已在 |
- |
spring.ai.openai.chat.options.stream-usage |
(仅限流式传输)设置为 |
false |
spring.ai.openai.chat.options.proxy-tool-calls |
若为 |
false |
所有以 spring.ai.openai.chat.options 为前缀的属性,均可通过在 Prompt 调用中添加请求特定的 运行时选项 进行覆盖。
|
运行时选项
OpenAiChatOptions.java 提供模型配置参数,包括使用的模型名称、温度值(temperature)、频率惩罚系数(frequency penalty)等。
启动时,默认选项可通过 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#builder() 创建的通用 ChatOptions 实例。 |
函数调用
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 获取实时天气数据。预期响应为:“The weather in Amsterdam is currently 20 degrees Celsius, and the weather in Paris is currently 25 degrees Celsius.”。
详细了解 OpenAI 函数调用功能。
示例 Controller
创建 新的 Spring Boot 项目,在 pom(或gradle)依赖中添加 spring-ai-starter-model-openai
。
在 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 服务。
将以下依赖添加到项目的 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
支持 Fluent 式选项构建。