获取最新的快照版本,请使用 Spring AI 1.1.3spring-doc.cadn.net.cn

Perplexity Chart

Perplexity AI 提供了一项独特的AI服务,将语言模型与实时搜索功能相结合。它提供了多种模型,并支持会话式AI的流式响应。spring-doc.cadn.net.cn

Spring AI 通过复用现有的 OpenAI 客户端与Perplexity AI集成。开始之前,您需要获取一个 Perplexity API密钥,配置基础URL,并选择一个受支持的 模型spring-doc.cadn.net.cn

spring ai perplexity integration
Perplexity API与OpenAI API并不完全兼容。 Perplexity将实时网络搜索结果与其语言模型响应相结合。 与OpenAI不同,Perplexity不公开toolCallsfunction call的评分机制。 此外,目前Perplexity还不支持多模态消息。

查看PerplexityWithOpenAiChatModelIT.java测试用例以获取使用Spring AI结合Perplexity的示例。spring-doc.cadn.net.cn

前提条件

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

spring.ai.openai.api-key=<your-perplexity-api-key>
spring.ai.openai.base-url=https://api.perplexity.ai
spring.ai.openai.chat.model=llama-3.1-sonar-small-128k-online
spring.ai.openai.chat.completions-path=/chat/completions

为了在处理 API 密钥等敏感信息时增强安全性,可以使用 Spring 表达式语言(SpEL)来引用自定义环境变量:spring-doc.cadn.net.cn

# In application.yml
spring:
  ai:
    openai:
      api-key: ${PERPLEXITY_API_KEY}
      base-url: ${PERPLEXITY_BASE_URL}
      chat:
        model: ${PERPLEXITY_MODEL}
        completions-path: ${PERPLEXITY_COMPLETIONS_PATH}
# In your environment or .env file
export PERPLEXITY_API_KEY=<your-perplexity-api-key>
export PERPLEXITY_BASE_URL=https://api.perplexity.ai
export PERPLEXITY_MODEL=llama-3.1-sonar-small-128k-online
export PERPLEXITY_COMPLETIONS_PATH=/chat/completions

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

// Retrieve configuration from secure sources or environment variables
String apiKey = System.getenv("PERPLEXITY_API_KEY");
String baseUrl = System.getenv("PERPLEXITY_BASE_URL");
String model = System.getenv("PERPLEXITY_MODEL");
String completionsPath = System.getenv("PERPLEXITY_COMPLETIONS_PATH");

添加仓库和BOM

Spring AI 工件发布在 Maven Central 和 Spring Snapshot 仓库中。 请参阅 工件仓库 部分,以将这些仓库添加到您的构建系统。spring-doc.cadn.net.cn

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

自动配置

There has been a significant change in the Spring AI auto-configuration, starter modules' artifact names. Please refer to the 升级说明以获取更多信息。spring-doc.cadn.net.cn

Spring AI 为 OpenAI 聊天客户端提供了 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

属性 描述 默认

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 分钟。spring-doc.cadn.net.cn

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

如果为false,则抛出NonTransientAiException,且不重试客户端错误代码4xxspring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

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

不应触发重试的HTTP状态代码列表(例如,用于抛出非暂时性AI异常)。spring-doc.cadn.net.cn

emptyspring-doc.cadn.net.cn

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

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

emptyspring-doc.cadn.net.cn

连接属性

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

属性 描述 默认

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

连接到的URL。必须设置为https://api.perplexity.aispring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

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

您的困惑度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

属性 描述 默认

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

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

开源人工智能spring-doc.cadn.net.cn

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

支持的Perplexity模型之一。示例:llama-3.1-sonar-small-128k-online.spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

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

可选地覆盖spring.ai.openai.base-url以提供聊天特定的URL。必须设置为https://api.perplexity.aispring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.openai.chat.completions-pathspring-doc.cadn.net.cn

必须设置为 /chat/completionsspring-doc.cadn.net.cn

/v1/chat/completionsspring-doc.cadn.net.cn

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

响应中的随机性程度,值介于0(包含)和2(不包含)之间。较大的值更随机,较小的值更确定。所需范围:0 < x < 2spring-doc.cadn.net.cn

0.2spring-doc.cadn.net.cn

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

乘法惩罚,大于0的值。大于1.0的值会根据新词在当前文本中的已存在频率对其进行惩罚,从而降低模型重复相同行文字的确切概率。值为1.0表示无惩罚。与presence_penalty不兼容。所需范围:x > 0spring-doc.cadn.net.cn

1spring-doc.cadn.net.cn

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

API 返回的最大完成Tokens数量。在max_tokens中请求的总Tokens数加上messages中发送的提示Tokens数,不得超过所请求模型的上下文窗口Tokens限制。如果未指定,则模型将生成Tokens,直到遇到停止Tokens或其上下文窗口结束为止。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

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

介于-2.0和2.0之间的值。正值会根据新词元是否已出现在文本中对其进行惩罚,从而增加模型谈论新主题的可能性。与frequency_penalty不兼容。所需范围:-2 < x < 2spring-doc.cadn.net.cn

0spring-doc.cadn.net.cn

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

核采样阈值,取值范围在0到1(包含)之间。对于每个后续的Tokens,模型会考虑具有top_p概率质量的Tokens结果。我们建议调整top_k或top_p中的一个,而不是同时调整两者。所需范围:0 < x < 1spring-doc.cadn.net.cn

0.9spring-doc.cadn.net.cn

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

(仅限流式处理)设置此选项可添加一个额外的块,用于统计整个请求的Tokens使用情况。此块的choices字段为空数组,所有其他块也将包含一个使用情况字段,但其值为null。spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

所有以spring.ai.openai.chat.options为前缀的属性都可以通过向Prompt调用中添加特定于请求的运行时选项在运行时覆盖。

运行时选项

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

On start-up, the default options can be configured with the OpenAiChatModel(api, options) constructor or the spring.ai.openai.chat.options.* properties.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("llama-3.1-sonar-large-128k-online")
            .temperature(0.4)
        .build()
    ));
除了特定于模型的OpenAiChatOptions之外,您还可以使用通过ChatOptions#builder()创建的可移植ChatOptions实例。

函数调用

Perplexity 不支持显式函数调用。相反,它直接将搜索结果融入到响应中。

多模态

目前,Perplexity API 不支持媒体内容。

示例控制器

创建一个新的Spring Boot项目,并将spring-boot-starter-web添加到您的pom(或gradle)依赖中。spring-doc.cadn.net.cn

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

spring.ai.openai.api-key=<PERPLEXITY_API_KEY>
spring.ai.openai.base-url=https://api.perplexity.ai
spring.ai.openai.chat.completions-path=/chat/completions
spring.ai.openai.chat.options.model=llama-3.1-sonar-small-128k-online
spring.ai.openai.chat.options.temperature=0.7

# The Perplexity API doesn't support embeddings, so we need to disable it.
spring.ai.openai.embedding.enabled=false
api-key替换为您的Perplexity Api密钥。

这将创建一个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);
    }
}

支持的模型

Perplexity支持多种针对搜索增强型对话AI优化的模型。详情请参阅支持的模型spring-doc.cadn.net.cn