Perplexity Chat
Perplexity AI 提供了一项独特的 AI 服务,该服务将其语言模型与实时搜索功能相结合。它提供多种模型,并支持流式响应以用于对话式 AI。
Spring AI 通过复用现有的 OpenAI 客户端与 Perplexity AI 进行集成。要开始使用,你需要获取一个 Perplexity API 密钥,配置基础 URL,并选择一个受支持的模型。

Perplexity API 与 OpenAI API 并非完全兼容。Perplexity 将实时网络搜索结果与其语言模型响应相结合。与 OpenAI 不同,Perplexity 不暴露 toolCalls - function call 机制。此外,目前 Perplexity 不支持多模态消息。
请查看 PerplexityWithOpenAiChatModelIT.java 测试以获取在 Spring AI 中使用 Perplexity 的示例。
先决条件
-
创建 API 密钥:请访问此处创建 API 密钥。然后在你的 Spring AI 项目中,通过
spring.ai.openai.api-key属性进行配置。 -
设置 Perplexity 基础 URL:将
spring.ai.openai.base-url属性设置为https://api.perplexity.ai。 -
选择 Perplexity 模型:使用
spring.ai.openai.chat.model=<model name>属性来指定模型。可用的选项请参考支持的模型。 -
设置聊天补全路径:将
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 密钥)时,为了增强安全性,您可以使用 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
您也可以在应用程序代码中以编程方式设置这些配置:
// 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 Chat Client 提供 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 秒 |
| spring.ai.retry.backoff.multiplier | 退避间隔乘数。 | 5 |
| spring.ai.retry.backoff.max-interval | 最大退避持续时间。 | 3 分钟 |
| spring.ai.retry.on-client-errors | 如果为 false,则抛出 NonTransientAiException,并且不对 4xx 客户端错误代码尝试重试。 | false |
| spring.ai.retry.exclude-on-http-codes | 不应触发重试(例如,抛出 NonTransientAiException)的 HTTP 状态码列表。 | empty |
| spring.ai.retry.on-http-codes | 应触发重试(例如,抛出 TransientAiException)的 HTTP 状态码列表。 | empty |
连接属性
spring.ai.openai 被用作属性前缀,允许您连接到 OpenAI。
| 属性 | 描述 | 默认值 |
|---|---|---|
| spring.ai.openai.base-url | 要连接的 URL。必须设置为 https://api.perplexity.ai | - |
| spring.ai.openai.chat.api-key | 你的 Perplexity API 密钥 | - |
配置属性
现在通过前缀为 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。必须设置为 https://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 的值会根据新 token 在现有文本中的出现频率对其进行惩罚,从而降低模型逐字重复同一行的可能性。值为 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_k 或 top_p 之一,但不要同时更改两者。必需范围:0 < x < 1 | 0.9 |
| spring.ai.openai.chat.options.stream-usage | (仅适用于流式处理)设置为 true 可为整个请求添加一个包含 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 实例,该实例可通过 ChatOptions#builder() 创建。
函数调用
Perplexity 不支持显式函数调用。相反,它直接将搜索结果集成到响应中。
多模态
目前,Perplexity API 暂不支持媒体内容。
示例控制器
创建一个新的 Spring Boot 项目,并将 spring-ai-starter-model-openai 添加到你的 pom(或 gradle)依赖中。
在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优化的模型。详细信息请参阅支持的模型。