Perplexity

本站(springdoc.cn)中的内容来源于 spring.io ,原始版权归属于 spring.io。由 springdoc.cn 进行翻译,整理。可供个人学习、研究,未经许可,不得进行任何转载、商用或与之相关的行为。 商标声明:Spring 是 Pivotal Software, Inc. 在美国以及其他国家的商标。

Perplexity AI 提供独特的 AI 服务,将其语言模型与实时搜索功能相结合。该服务支持多种模型,并为对话式 AI 提供流式响应能力。

Spring AI 通过复用现有 OpenAI 客户端与 Perplexity AI 集成。使用时需:获取 Perplexity API Key、配置 Base URL 并选择支持的 模型

spring ai perplexity integration
Perplexity API 与 OpenAI API 不完全兼容。Perplexity 将实时网络搜索结果与其语言模型响应相结合。与 OpenAI 不同,Perplexity 不暴露 toolCallsfunction call 机制)。此外,当前 Perplexity 不支持多模态消息。

查看 PerplexityWithOpenAiChatModelIT.java 测试示例,了解如何在 Spring AI 中使用 Perplexity。

先决条件

  • 创建 API 密钥:访问 此处 生成密钥。在 Spring AI 项目中通过 spring.ai.openai.api-key 属性进行配置。

  • 设置 Perplexity Base URL:将 spring.ai.openai.base-url 属性配置为 api.perplexity.ai

  • 选择 Perplexity 模型:使用 spring.ai.openai.chat.model=<模型名称> 属性指定模型。可用选项请参阅 支持的模型列表

  • 设置聊天补全路径:将 spring.ai.openai.chat.completions-path 配置为 /chat/completions。详情请参阅 聊天补全 API 档

你可以在 application.properties 文件中设置这些配置属性:

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 Key 等敏感信息的安全性,可使用 Spring 表达式语言(SpEL)引用自定义环境变量:

# 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

You can also set these configurations programmatically in your application code:

// 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 AI 提供 BOM 确保项目中使用一致的 Spring AI 版本。请参考 依赖管理 章节将 Spring AI BOM 添加到构建系统中。

自动配置

Spring AI 自动配置及 Starter 模块的 artifact 命名已发生重大变更。具体升级说明请参阅 更新文档

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,则抛出 NonTransientAiException 异常,且不对 4xx 客户端错误代码进行重试。

false

spring.ai.retry.exclude-on-http-codes

不应触发重试的 HTTP 状态码列表(例如用于抛出 NonTransientAiException 异常)。

empty

spring.ai.retry.on-http-codes

应触发重试的 HTTP 状态码列表(例如用于抛出 TransientAiException 异常)。

empty

连接属性

前缀 spring.ai.openai 用作属性前缀,用于配置 OpenAI 连接参数。

属性 说明 默认值

spring.ai.openai.base-url

连接目标 URL。必须设置为 api.perplexity.ai

-

spring.ai.openai.chat.api-key

Perplexity API Key

-

配置属性

聊天自动配置的启用/禁用现在通过顶级属性配置,前缀为 spring.ai.model.chat

  • 启用方式:spring.ai.model.chat=openai(默认已启用)

  • 禁用方式:spring.ai.model.chat=none(或任何非 openai 的值)

此项变更是为了支持多模型配置。

前缀 spring.ai.openai.chat 用于配置 OpenAI 聊天模型实现的属性前缀。

属性 说明 默认值

spring.ai.model.chat

启用 OpenAI 聊天模型。

openai

spring.ai.openai.chat.model

支持的 Perplexity 模型 之一。例如:llama-3.1-sonar-small-128k-online

-

spring.ai.openai.chat.base-url

可选参数,用于覆盖 spring.ai.openai.base-url 以提供聊天专用 URL。必须设置为 api.perplexity.ai

-

spring.ai.openai.chat.completions-path

必须设置为:/chat/completions

/v1/chat/completions

spring.ai.openai.chat.options.temperature

响应中随机性的程度,取值范围为 0(包含)到 2(不包含)。值越高,响应越随机;值越低,响应越确定。要求范围:0 < x < 2

0.2

spring.ai.openai.chat.options.frequencyPenalty

大于 0 的乘法惩罚值。大于 1.0 的值会根据新标记在已有文本中出现的频率进行惩罚,从而降低模型逐字重复相同内容的可能性。值为 1.0 表示不进行惩罚。与 presence_penalty 不兼容。要求范围:x > 0

1

spring.ai.openai.chat.options.maxTokens

API 返回的最大补全 token 数。max_tokens 请求的总 token 数与消息中发送的提示 token 数之和不得超过所请求模型的上下文窗口 token 限制。若未指定,模型将生成 token 直至达到停止 token 或上下文窗口结束。

-

spring.ai.openai.chat.options.presencePenalty

介于 -2.0 和 2.0 之间的值。正值会根据新 token 是否已出现在当前文本中进行惩罚,从而增加模型讨论新话题的可能性。与 frequency_penalty 不兼容。有效范围:-2 < x < 2

0

spring.ai.openai.chat.options.topP

核心采样阈值,取值范围为 0 到 1(含)。对于每个后续 token,模型会考虑概率质量累加达 top_p 值的 token 结果。建议仅调整 top_ktop_p 中的一个参数。有效范围:0 < x < 1

0.9

spring.ai.openai.chat.options.stream-usage

(仅限流式传输)设置后将为整个请求添加包含 token 使用统计信息的附加数据块。该数据块的 choices 字段为空数组,其他所有数据块也将包含 usage 字段,但其值为 null

false

所有以 spring.ai.openai.chat.options 为前缀的属性,均可通过在 Prompt 调用中添加请求特定的 运行时配置 进行运行时覆盖。

运行时配置

OpenAiChatOptions.java 提供模型配置参数,包括使用的模型、温度值、频率惩罚系数等。

启动时,默认选项可通过 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("llama-3.1-sonar-large-128k-online")
            .temperature(0.4)
        .build()
    ));
除模型特定的 OpenAiChatOptions 外,你还可使用通过 ChatOptions#builder() 创建的可移植 ChatOptions 实例。

函数调用

Perplexity 不支持显式函数调用,而是将搜索结果直接集成到响应中。

多模态

当前 Perplexity API 不支持媒体内容处理。

示例 Controller

新建 Spring Boot 项目并在 pom(或 gradle)依赖中添加 spring-ai-starter-model-openai

src/main/resources 目录下添加 application.properties 文件以启用并配置 OpenAi 聊天模型:

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 类示例:

@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 优化的模型。详情请参阅 支持的模型 列表。