1. 概述
本文将介绍如何使用 Spring AI 集成基于 LPU的Groq AI推理引擎 提供的模型,构建一个聊天机器人。
Groq提供了REST接口,应用程序可通过调用其接口来使用服务。同时,Groq还支持多种编程语言的SDK,包括Python和JavaScript。在Python生态中,LangChain 和 LiteLLM 等主流库已支持Groq。此外,Vercel AI SDK 也提供了专门的Groq集成模块。
✅ 关键优势:Groq完全兼容OpenAI客户端库,因此应用可以轻松从OpenAI切换到Groq服务。Spring AI的OpenAI聊天客户端只需少量配置修改即可连接Groq,目前Spring AI尚未提供独立的Groq库。
2. 前提条件
Spring AI框架通过对应的starter库集成多种LLM服务。要集成Groq服务,Spring Boot应用需添加 Spring AI OpenAI 依赖:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
<version>1.0.0-M6</version>
</dependency>
建议使用 Spring Initializr 工具优化依赖管理。
⚠️ 必要步骤:需在 Groq云平台 注册并创建API密钥:
注册后用户可获得免费订阅额度,但Groq会对API请求实施模型相关的速率限制以保证公平使用。
3. 核心Spring AI组件与配置
要有效利用Spring AI的OpenAI库访问Groq服务,需理解关键类:
OpenAiChatModel
:客户端类,接收Prompt
对象调用底层服务OpenAiChatOptions
:用于指定模型名称、温度、最大token数等参数
配置要点:
- 必须覆盖
spring.ai.openai.chat.base-url
指向Groq接口:api.groq.com/openai
- 在
spring.ai.openai.chat.api-key
设置Groq API密钥(建议从环境变量读取) - 通用配置
spring.ai.openai.base-url
和spring.ai.openai.api-key
也可用,但优先级低于chat命名空间配置
4. 自动配置Groq客户端
本节展示如何通过OpenAiAutoConfiguration
自动配置OpenAiChatModel
。首先在application-groq.properties
中配置:
spring.application.name=spring-ai-groq-demo
spring.ai.openai.base-url=https://api.groq.com/openai
spring.ai.openai.api-key=gsk_XXXX
spring.ai.openai.chat.base-url=https://api.groq.com/openai
spring.ai.openai.chat.api-key=gsk_XXXX
spring.ai.openai.chat.options.temperature=0.7
spring.ai.openai.chat.options.model=llama-3.3-70b-versatile
❗ 踩坑提示:必须同时配置spring.ai.openai
命名空间的URL和密钥,否则部分Spring AI bean会导致启动失败。
创建Spring服务类GroqChatService
:
@Service
public class GroqChatService {
@Autowired
private OpenAiChatModel groqClient;
public String chat(String prompt) {
return groqClient.call(prompt);
}
public ChatOptions getChatOptions() {
return groqClient.getDefaultOptions();
}
}
工作原理:OpenAiAutoConfiguration
使用配置文件属性实例化OpenAiChatModel
。服务类通过call()
方法调用Groq服务,getChatOptions()
返回客户端配置。
JUnit测试示例:
void whenCallOpenAIClient_thenReturnResponseFromGroq() {
String prompt = """
Context:
Support Ticket #98765:
Product: XYZ Wireless Mouse
Issue Description: The mouse connects intermittently to my laptop.
I've tried changing batteries and reinstalling drivers,
but the cursor still freezes randomly for a few seconds before resuming normal movement.
It affects productivity significantly.
Question:
Based on the support ticket, what is the primary technical issue
the user is experiencing with their 'XYZ Wireless Mouse'?;
""";
String response = groqChatService.chat(prompt);
logger.info("Response from Groq:{}", response);
assertThat(response.toLowerCase()).isNotNull()
.isNotEmpty()
.containsAnyOf("laptop", "mouse", "connect");
ChatOptions openAiChatOptions = groqChatService.getChatOptions();
String model = openAiChatOptions.getModel();
Double temperature = openAiChatOptions.getTemperature();
assertThat(openAiChatOptions).isInstanceOf(OpenAiChatOptions.class);
assertThat(model).isEqualTo("llama-3.3-70b-versatile");
assertThat(temperature).isEqualTo(Double.valueOf(0.7));
}
测试用例包含上下文(鼠标支持工单)和问题,Groq返回分析结果:
The primary technical issue the user is experiencing with their
'XYZ Wireless Mouse' is intermittent connectivity, resulting in the
cursor freezing randomly for a few seconds before resuming normal movement.
5. 自定义Groq客户端
实际应用中通常需要动态配置模型、温度等参数。首先创建自定义配置类:
@Configuration(proxyBeanMethods = false)
public class ChatAppConfiguration {
@Value("${groq.api-key}")
private String GROQ_API_KEY;
@Value("${groq.base-url}")
private String GROQ_API_URL;
@Bean
public OpenAiChatModel customGroqChatClient() {
OpenAiApi groqOpenAiApi = new OpenAiApi.Builder()
.apiKey(GROQ_API_KEY)
.baseUrl(GROQ_API_URL)
.build();
return OpenAiChatModel.builder()
.openAiApi(groqOpenAiApi)
.build();
}
}
灵活点:通过低层OpenAiApi
类构建客户端,可扩展复杂逻辑(如从下游系统读取配置)。
创建自定义服务类:
@Service
public class CustomGroqChatService {
@Autowired
private OpenAiChatModel customGroqChatClient;
public String chat(String prompt, String model, Double temperature) {
ChatOptions chatOptions = OpenAiChatOptions.builder()
.model(model)
.temperature(temperature)
.build();
return customGroqChatClient.call(new Prompt(prompt, chatOptions))
.getResult()
.getOutput()
.getText();
}
}
关键改进:动态指定模型和温度参数,从ChatResponse
提取响应文本。
JUnit测试示例:
void whenCustomGroqClientCalled_thenReturnResponse() {
String prompt = """
Context:
The Eiffel Tower is one of the most famous landmarks
in Paris, attracting millions of visitors each year.
Question:
In which city is the Eiffel Tower located?
""";
String response = customGroqChatService.chat(prompt, "llama-3.1-8b-instant", 0.8);
assertThat(response)
.isNotNull()
.isNotEmpty()
.contains("Paris");
logger.info("Response from custom Groq client: {}", response);
}
Groq返回结果:
The Eiffel Tower is located in Paris, France.
6. 总结
本文展示了如何通过Spring AI的OpenAI库集成Groq推理引擎。该库还支持Groq的工具功能,可注册和调用外部工具执行操作。
⚠️ 重要限制:
- Groq对多模态模型支持有限,导致Spring AI暂无法提供相关功能
- Groq与OpenAI并非完全兼容,使用时需注意这些约束
完整示例代码可在 GitHub 获取。