收藏本站,收获最前沿的人工智能与编程资讯!!

Spring AI 使用 Groq 对话模型

技术文档 16℃ 0

Groq 是一款基于 LPU™ 架构的**超高速 AI 推理引擎**,支持多种主流 AI 模型、工具/函数调用功能,并提供与 OpenAI API 兼容的服务端点。

Spring AI 通过**复用现有的 OpenAI 客户端**实现与 Groq 的集成。你只需获取 Groq API 密钥,将基础地址设置为 api.groq.com/openai,并选择对应的 Groq 模型即可使用。

注意:Groq API 与 OpenAI API 并非完全兼容,存在部分兼容性限制。此外,Groq 目前不支持多模态消息。    
可查看 GroqWithOpenAiChatModelIT.java 测试文件,了解 Spring AI 结合 Groq 的使用示例。

前提条件

  1. 创建 API 密钥:访问 Groq 官网创建 API 密钥,并将其配置到 Spring AI 的 spring.ai.openai.api-key 属性中。

  2. 设置服务地址:将 spring.ai.openai.base-url 设置为 https://api.groq.com/openai

  3. 选择模型:通过 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

安全配置(环境变量)

# application.yml
spring:
  ai:
    openai:
      api-key: ${GROQ_API_KEY}
      base-url: ${GROQ_BASE_URL}
      chat:
        model: ${GROQ_MODEL}

# 环境变量配置
export GROQ_API_KEY=<your-groq-api-key>
export GROQ_BASE_URL=https://api.groq.com/openai
export GROQ_MODEL=llama3-70b-8192

添加仓库与依赖管理

Spring AI 构件已发布至 Maven 中央仓库。建议使用 BOM 统一管理版本,确保项目依赖一致性。

自动配置

Spring AI 为 OpenAI 对话客户端提供自动配置,添加以下依赖即可启用:

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

对话属性配置

重试属性

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.openai 前缀用于配置 Groq 连接。

属性描述默认值
spring.ai.openai.base-url必须设为 https://api.groq.com/openai-
spring.ai.openai.api-keyGroq API 密钥-

模型配置属性

通过 spring.ai.model.chat=openai 启用对话自动配置(默认启用)。    
spring.ai.openai.chat 前缀用于模型参数配置。

属性描述默认值
spring.ai.openai.chat.options.model支持模型:llama3-8b/70b、mixtral-8x7b、gemma2-9b-it-
spring.ai.openai.chat.options.temperature采样温度(0~2),控制随机性0.8
spring.ai.openai.chat.options.maxTokens最大生成令牌数-
spring.ai.openai.chat.options.responseFormat输出格式,支持 json_object-

所有 spring.ai.openai.chat.options 前缀的属性,均可在运行时通过 Prompt 动态覆盖。

运行时选项

可在请求时动态覆盖默认配置:

ChatResponse response = chatModel.call(
    new Prompt(
        "生成5位著名海盗的名字",
        OpenAiChatOptions.builder()
            .model("mixtral-8x7b-32768")
            .temperature(0.4)
        .build()
    ));

函数调用

Groq 支持工具/函数调用,可将自定义 Java 函数注册给模型,模型会智能选择调用。

工具示例

@SpringBootApplication
public class GroqApplication {
    public static void main(String[] args) { SpringApplication.run(GroqApplication.class, args); }

    @Bean
    CommandLineRunner runner(ChatClient.Builder builder) {
        return args -> {
            var response = builder.build().prompt()
                .user("阿姆斯特丹和巴黎的天气如何?")
                .functions("weatherFunction")
                .call().content();
            System.out.println(response);
        };
    }

    @Bean @Description("获取指定地点天气")
    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 req) {
            return new WeatherResponse(req.location.contains("Amsterdam") ? 20 : 25, req.unit);
        }
    }
}

多模态

Groq API 目前不支持图片、音频等媒体内容输入。

示例控制器

@RestController
public class ChatController {
    private final OpenAiChatModel chatModel;

    @Autowired
    public ChatController(OpenAiChatModel chatModel) { this.chatModel = chatModel; }

    @GetMapping("/ai/generate")
    public Map generate(@RequestParam(defaultValue = "讲个笑话") String message) {
        return Map.of("generation", chatModel.call(message));
    }

    @GetMapping("/ai/generateStream")
    public Flux<ChatResponse> generateStream(@RequestParam(defaultValue = "讲个笑话") String message) {
        return chatModel.stream(new Prompt(new UserMessage(message)));
    }
}

手动配置

不使用自动配置时,手动创建客户端:

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

// 同步调用
ChatResponse response = chatModel.call(new Prompt("生成5位著名海盗的名字"));

// 流式调用
Flux<ChatResponse> fluxResponse = chatModel.stream(new Prompt("生成5位著名海盗的名字"));

相关推荐