此版本仍在开发中,尚未被视为稳定版。如需最新的快照版本,请使用 Spring AI 1.1.3spring-doc.cadn.net.cn

Groq Chat

Groq 是一种基于 LPU™ 的极快的 AI 推断引擎,支持各种 AI 模型,支持 Tool/Function Calling 并暴露一个兼容 OpenAI API 的端点。spring-doc.cadn.net.cn

Spring AI通过重用现有的OpenAI客户端与集成。 为此,您需要获取一个Groq Api Key,设置基础URL为api.groq.com/openai,并选择一个提供的 Groq模型spring-doc.cadn.net.cn

spring ai groq integration
The Groq API 不完全兼容 OpenAI API。 请留意以下 兼容性限制。 此外,目前 Groq 不支持多模态消息。

检查 GroqWithOpenAiChatModelIT.java 测试 以了解如何在 Spring AI 中使用 Groq。spring-doc.cadn.net.cn

前置条件

  • 创建 API 密钥: 访问 这里 创建 API 密钥。 Spring AI 项目定义了一个配置属性,名为 spring.ai.openai.api-key,您应该将其设置为从 groq.com 获取的 API Key 的值。spring-doc.cadn.net.cn

  • 设置Groq URL
    您必须将spring.ai.openai.base-url属性设置为https://api.groq.com/openaispring-doc.cadn.net.cn

  • 选择一个Groq模型: 使用spring.ai.openai.chat.model=<model name>属性从可用的Groq模型中进行选择。spring-doc.cadn.net.cn

您可以在您的application.properties文件中设置这些配置属性:spring-doc.cadn.net.cn

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)引用自定义环境变量:spring-doc.cadn.net.cn

# 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

您也可以在应用程序代码中程序化设置这些配置:spring-doc.cadn.net.cn

// 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 仓库中。 请参阅 构件仓库 部分,将这些仓库添加到您的构建系统中。spring-doc.cadn.net.cn

为了帮助进行依赖管理,Spring AI 提供了一个 BOM(物料清单),以确保整个项目中使用的是相同的 Spring AI 版本。请参阅 依赖管理 部分,将 Spring AI BOM 添加到您的构建系统中。spring-doc.cadn.net.cn

Auto-configuration

Spring AI自动配置和starter模块的artifact名称有了重大变化。 请参阅升级说明获取更多信息。spring-doc.cadn.net.cn

Spring AI 提供了对 OpenAI Chat Client 的 Spring Boot 自动配置。 要启用它,请将以下依赖项添加到您的项目 Maven pom.xml 或 Gradle build.gradle 构建文件中:spring-doc.cadn.net.cn

<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-doc.cadn.net.cn

<property> </property> <description> </description> 默认

spring.ai.retry.max-attemptsspring-doc.cadn.net.cn

最大重试尝试次数。spring-doc.cadn.net.cn

10spring-doc.cadn.net.cn

spring.ai.retry.backoff.initial-intervalspring-doc.cadn.net.cn

指数退避策略的初始睡眠时长。spring-doc.cadn.net.cn

2 秒。spring-doc.cadn.net.cn

spring.ai.retry.backoff.multiplierspring-doc.cadn.net.cn

重试间隔倍数。spring-doc.cadn.net.cn

5spring-doc.cadn.net.cn

spring.ai.retry.backoff.max-intervalspring-doc.cadn.net.cn

最大退避持续时间。spring-doc.cadn.net.cn

3 min.spring-doc.cadn.net.cn

spring.ai.retry.on-client-errorsspring-doc.cadn.net.cn

如果为假,则抛出一个NonTransientAiException,并且不尝试重试4xx客户端错误代码spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

spring.ai.retry.exclude-on-http-codesspring-doc.cadn.net.cn

不应当触发重试的HTTP状态码列表(例如,抛出NonTransientAiException)。spring-doc.cadn.net.cn

<p>空内容</p>spring-doc.cadn.net.cn

spring.ai.retry.on-http-codesspring-doc.cadn.net.cn

应触发重试的HTTP状态码列表(例如,抛出TransientAiException)。spring-doc.cadn.net.cn

<p>空内容</p>spring-doc.cadn.net.cn

连接属性

使用前缀spring.ai.openai作为属性前缀,以便连接到OpenAI。spring-doc.cadn.net.cn

<property> </property> <description> </description> 默认

spring.ai.openai.base-urlspring-doc.cadn.net.cn

The URL to connect to. Must be set to https://api.groq.com/openaispring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.api-keyspring-doc.cadn.net.cn

Groq API密钥spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

配置属性

现在通过带有前缀spring.ai.model.chat的顶级属性来配置聊天自动配置的启用和禁用。spring-doc.cadn.net.cn

要启用,请设置:spring.ai.model.chat=openai(默认已启用)spring-doc.cadn.net.cn

要禁用,请设置 spring.ai.model.chat=none (或任何与 openai 匹配的值)spring-doc.cadn.net.cn

此更改是为了允许配置多个模型。spring-doc.cadn.net.cn

spring.ai.openai.chat 前缀是属性前缀,允许你配置与 OpenAI 的聊天模型实现相关的设置。spring-doc.cadn.net.cn

<property> </property> <description> </description> 默认

spring.ai.openai.chat.enabled (已删除且不再有效)spring-doc.cadn.net.cn

启用OpenAI聊天模型。spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

spring.ai.openai.chatspring-doc.cadn.net.cn

启用OpenAI聊天模型。spring-doc.cadn.net.cn

OpenAIspring-doc.cadn.net.cn

spring.ai.openai.chat.base-urlspring-doc.cadn.net.cn

Optional 用于覆盖 spring.ai.openai.base-url,提供特定于聊天的 URL。必须设置为 https://api.groq.com/openaispring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.api-keyspring-doc.cadn.net.cn

Optional 允许覆盖 spring.ai.openai.api-key 提供聊天相关的 api-keyspring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.options.modelspring-doc.cadn.net.cn

The 可用模型名称是 llama3-8b-8192, llama3-70b-8192, mixtral-8x7b-32768, gemma2-9b-it.spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.options.temperaturespring-doc.cadn.net.cn

使用以控制生成完成内容的看似创造力的采样温度。较高值会使输出更具随机性,而较低值会使结果更集中和确定。不建议在同一完成请求中同时修改温度和top_p,因为这两个设置之间的交互难以预测。spring-doc.cadn.net.cn

0.8spring-doc.cadn.net.cn

spring.ai.openai.chat.options.frequencyPenaltyspring-doc.cadn.net.cn

在-2.0到2.0之间的数字。正数值根据文本中现有内容中新词的频率对新词进行惩罚,从而降低模型逐字重复相同行的可能性。spring-doc.cadn.net.cn

0.0fspring-doc.cadn.net.cn

spring.ai.openai.chat.options.maxTokensspring-doc.cadn.net.cn

生成聊天补全时的最大token数。输入token和生成token的总长度受限于模型的上下文长度。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.options.nspring-doc.cadn.net.cn

每条输入消息生成多少个聊天补全选项。请注意,您将根据所有选项生成的Tokens数量进行收费。为了最小化成本,请保持n为1。spring-doc.cadn.net.cn

1spring-doc.cadn.net.cn

spring.ai.openai.chat.options.presencePenaltyspring-doc.cadn.net.cn

在-2.0到2.0之间的数字。正数值根据新词在整个文本中出现的频率来惩罚新的词汇,从而增加模型讨论新话题的可能性。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.options.responseFormatspring-doc.cadn.net.cn

指定模型必须输出的格式。设置为{ "type": "json_object" }启用JSON模式,保证模型生成的消息是有效的JSON。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.options.seedspring-doc.cadn.net.cn

此功能处于测试版。如指定,我们的系统将尽力进行确定性采样,这意味着使用相同的种子和参数重复请求应返回相同的结果。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.options.stopspring-doc.cadn.net.cn

API将在生成更多Tokens之前停止生成至多4个序列。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.options.topPspring-doc.cadn.net.cn

在采样温度之外,还有一种称为核采样的方法,该方法中模型会考虑具有 top_p 概率质量的标记结果。因此 0.1 表示只有位于前 10% 概率质量的标记才会被考虑。我们通常建议修改此值或温度中的一个,但不同时修改两者。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.options.toolsspring-doc.cadn.net.cn

模型可能调用的工具列表。目前,仅支持函数作为工具。使用此选项提供模型可以生成JSON输入的函数列表。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.options.toolChoicespring-doc.cadn.net.cn

controls which(如果有的话)函数是由模型调用的。none表示模型不会调用任何函数,而是生成一条消息。auto表示模型可以在生成消息或调用函数之间进行选择。通过{"type": "function", "function": {"name": "my_function"}}指定特定的函数强制模型调用该函数。如果没有提供函数,则默认为none;如果提供了函数,则默认为auto。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.options.userspring-doc.cadn.net.cn

代表您最终用户的唯一标识符,这有助于OpenAI监控和检测滥用行为。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.options.stream-usagespring-doc.cadn.net.cn

(仅适用于流式传输) 设置以添加一个额外的分块,其中包含整个请求的 token 使用统计信息。此分块的 choices 字段为空数组,所有其他分块也将包含一个 usage 字段,但其值为 null。spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

spring.ai.openai.chat.options.tool-namesspring-doc.cadn.net.cn

使用名称标识的工具列表,以在单个提示请求中启用功能调用。具有这些名称的工具必须存在于ToolCallback注册表中。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.options.tool-callbacksspring-doc.cadn.net.cn

使用回调注册与ChatModel相关的工具。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.options.internal-tool-execution-enabledspring-doc.cadn.net.cn

如果为假,Spring AI 将不会内部处理工具调用,而是将它们代理给客户端。然后需要由客户端负责处理这些工具调用、将其分派到适当的函数,并返回结果。如果为真(默认值),Spring AI 将会内部处理这些函数调用。仅适用于支持功能调用的聊天模型。spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

所有以spring.ai.openai.chat.options开头的属性可以在运行时通过向Prompt调用添加请求特定的运行时选项来覆盖。

运行时选项

The OpenAiChatOptions.java 提供了模型配置,例如要使用的模型、温度、频率惩罚等。spring-doc.cadn.net.cn

启动时,可以使用OpenAiChatModel(api, options)构造函数或spring.ai.openai.chat.options.*属性来配置默认选项。spring-doc.cadn.net.cn

在运行时,您可以覆盖默认选项并通过向Prompt调用添加新的、针对请求的选项来实现。例如,要为特定请求覆盖默认模型和温度:spring-doc.cadn.net.cn

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-doc.cadn.net.cn

检查工具 支持的模型
spring ai groq functions 2

您可以将自定义的Java函数注册到您的ChatModel中,并且由提供的Groq模型智能选择输出一个包含调用已注册函数所需参数的JSON对象。 这是一种强大的技术,可以将LLM能力与外部工具和API连接起来。spring-doc.cadn.net.cn

工具示例

这里是如何使用Groq函数调用与Spring AI的一个简单示例:spring-doc.cadn.net.cn

@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摄氏度。"spring-doc.cadn.net.cn

读取有关OpenAI的更多信息 函数调用spring-doc.cadn.net.cn

多模态

当前,Groq API 不支持媒体内容。

样本控制器

创建一个新的Spring Boot项目,并在pom(或gradle)依赖中添加spring-ai-starter-model-openaispring-doc.cadn.net.cn

src/main/resources目录下添加一个application.properties文件,以启用并配置OpenAI聊天模型:spring-doc.cadn.net.cn

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类示例。spring-doc.cadn.net.cn

@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);
    }
}

手动配置

The OpenAiChatModel 实现了ChatModelStreamingChatModel,并使用[低级API]连接到 OpenAI 服务。spring-doc.cadn.net.cn

将如下的spring-ai-openai依赖添加到项目中Maven的pom.xml文件中:spring-doc.cadn.net.cn

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

请将以下内容添加到您的Gradle build.gradle 构建文件中。spring-doc.cadn.net.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-openai'
}
请参阅依赖管理部分,将Spring AI BOM添加到您的构建文件中。

接下来,创建一个OpenAiChatModel 并用于文本生成:spring-doc.cadn.net.cn

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."));

The OpenAiChatOptions 提供了聊天请求的配置信息。 The OpenAiChatOptions.Builder 是流畅选项构建器。spring-doc.cadn.net.cn