Perplexity Chat
Perplexity AI 提供独特的人工智能服务,将其语言模型与实时搜索功能集成。它提供各种模型,并支持用于对话式 AI 的流式响应。
Perplexity AI provides a unique AI service that integrates its language models with real-time search capabilities. It offers a variety of models and supports streaming responses for conversational AI.
Spring AI 通过重用现有的 OpenAI 客户端与 Perplexity AI 集成。要开始使用,您需要获取一个 Perplexity API Key ,配置基本 URL,并选择受支持的 models 之一。
Spring AI integrates with Perplexity AI by reusing the existing OpenAI client. To get started, you’ll need to obtain a Perplexity API Key, configure the base URL, and select one of the supported models. image::spring-ai-perplexity-integration.jpg[]
Perplexity API 与 OpenAI API 不完全兼容。Perplexity 将实时网络搜索结果与其语言模型响应结合在一起。与 OpenAI 不同,Perplexity 不公开 |
The Perplexity API is not fully compatible with the OpenAI API.
Perplexity combines realtime web search results with its language model responses.
Unlike OpenAI, Perplexity does not expose |
查看 PerplexityWithOpenAiChatModelIT.java 测试,了解如何将 Perplexity 与 Spring AI 结合使用的示例。
Check the PerplexityWithOpenAiChatModelIT.java tests for examples of using Perplexity with Spring AI.
Prerequisites
-
Create an API Key :访问 here 创建 API 密钥。在您的 Spring AI 项目中使用
spring.ai.openai.api-key
属性进行配置。 -
Create an API Key: Visit here to create an API Key. Configure it using the
spring.ai.openai.api-key
property in your Spring AI project. -
Set the Perplexity Base URL :将
spring.ai.openai.base-url
属性设置为https://api.perplexity.ai
。 -
Set the Perplexity Base URL: Set the
spring.ai.openai.base-url
property tohttps://api.perplexity.ai
. -
Select a Perplexity Model :使用
spring.ai.openai.chat.model=<model name>
属性指定模型。有关可用选项,请参阅 Supported Models 。 -
Select a Perplexity Model: Use the
spring.ai.openai.chat.model=<model name>
property to specify the model. Refer to Supported Models for available options. -
Set the chat completions path :将
spring.ai.openai.chat.completions-path
设置为/chat/completions
。有关更多详细信息,请参阅 chat completions api 。 -
Set the chat completions path: Set the
spring.ai.openai.chat.completions-path
to/chat/completions
. Refer to chat completions api for more details.
您可以在 application.properties
文件中设置这些配置属性:
You can set these configuration properties in your application.properties
file:
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) 来引用自定义环境变量:
For enhanced security when handling sensitive information like API keys, you can use Spring Expression Language (SpEL) to reference custom environment variables:
# 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");
Add Repositories and BOM
Spring AI 工件发布在 Maven Central 和 Spring Snapshot 存储库中。请参阅“添加 Spring AI 仓库”部分,将这些仓库添加到您的构建系统。
Spring AI artifacts are published in Maven Central and Spring Snapshot repositories. Refer to the Artifact Repositories section to add these repositories to your build system.
为了帮助进行依赖项管理,Spring AI 提供了一个 BOM(物料清单)以确保在整个项目中使用一致版本的 Spring AI。有关将 Spring AI BOM 添加到你的构建系统的说明,请参阅 Dependency Management 部分。
To help with dependency management, Spring AI provides a BOM (bill of materials) to ensure that a consistent version of Spring AI is used throughout the entire project. Refer to the Dependency Management section to add the Spring AI BOM to your build system.
Auto-configuration
Spring AI 自动配置、启动器模块的工件名称发生了重大变化。请参阅 upgrade notes 以获取更多信息。 There has been a significant change in the Spring AI auto-configuration, starter modules' artifact names. Please refer to the upgrade notes for more information. |
Spring AI 为 OpenAI Chat Client 提供 Spring Boot 自动配置。要启用它,请将以下依赖项添加到您项目的 Maven pom.xml
或 Gradle build.gradle
构建文件中:
Spring AI provides Spring Boot auto-configuration for the OpenAI Chat Client.
To enable it add the following dependency to your project’s Maven pom.xml
or Gradle build.gradle
build files:
-
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'
}
|
Refer to the Dependency Management section to add the Spring AI BOM to your build file. |
Chat Properties
Retry Properties
前缀 spring.ai.retry
用作属性前缀,允许您配置OpenAI聊天模型的重试机制。
The prefix spring.ai.retry
is used as the property prefix that lets you configure the retry mechanism for the OpenAI chat model.
Property | Description | Default |
---|---|---|
spring.ai.retry.max-attempts |
Maximum number of retry attempts. |
10 |
spring.ai.retry.backoff.initial-interval |
Initial sleep duration for the exponential backoff policy. |
2 sec. |
spring.ai.retry.backoff.multiplier |
Backoff interval multiplier. |
5 |
spring.ai.retry.backoff.max-interval |
Maximum backoff duration. |
3 min. |
spring.ai.retry.on-client-errors |
If false, throw a NonTransientAiException, and do not attempt retry for |
false |
spring.ai.retry.exclude-on-http-codes |
List of HTTP status codes that should not trigger a retry (e.g. to throw NonTransientAiException). |
empty |
spring.ai.retry.on-http-codes |
List of HTTP status codes that should trigger a retry (e.g. to throw TransientAiException). |
empty |
Connection Properties
spring.ai.openai
前缀用作可让你连接到 Open AI 的属性前缀。
The prefix spring.ai.openai
is used as the property prefix that lets you connect to OpenAI.
Property | Description | Default |
---|---|---|
spring.ai.openai.base-url |
The URL to connect to. Must be set to |
- |
spring.ai.openai.chat.api-key |
Your Perplexity API Key |
- |
Configuration Properties
聊天自动配置的启用和禁用现在通过前缀为 Enabling and disabling of the chat auto-configurations are now configured via top level properties with the prefix 要启用,spring.ai.model.chat=openai(默认启用) To enable, spring.ai.model.chat=openai (It is enabled by default) 要禁用,spring.ai.model.chat=none(或任何与 openai 不匹配的值) To disable, spring.ai.model.chat=none (or any value which doesn’t match openai) 此更改旨在允许配置多个模型。 This change is done to allow configuration of multiple models. |
前缀 spring.ai.openai.chat
是允许您为 OpenAI 配置聊天模型实现的属性前缀。
The prefix spring.ai.openai.chat
is the property prefix that lets you configure the chat model implementation for OpenAI.
Property | Description | Default |
---|---|---|
spring.ai.model.chat |
Enable OpenAI chat model. |
openai |
spring.ai.openai.chat.model |
One of the supported Perplexity models. Example: |
- |
spring.ai.openai.chat.base-url |
Optional overrides the spring.ai.openai.base-url to provide chat specific url. Must be set to |
- |
spring.ai.openai.chat.completions-path |
Must be set to |
|
spring.ai.openai.chat.options.temperature |
The amount of randomness in the response, valued between 0 inclusive and 2 exclusive. Higher values are more random, and lower values are more deterministic. Required range: |
0.2 |
spring.ai.openai.chat.options.frequencyPenalty |
A multiplicative penalty greater than 0. Values greater than 1.0 penalize new tokens based on their existing frequency in the text so far, decreasing the model’s likelihood to repeat the same line verbatim. A value of 1.0 means no penalty. Incompatible with presence_penalty. Required range: |
1 |
spring.ai.openai.chat.options.maxTokens |
The maximum number of completion tokens returned by the API. The total number of tokens requested in max_tokens plus the number of prompt tokens sent in messages must not exceed the context window token limit of model requested. If left unspecified, then the model will generate tokens until either it reaches its stop token or the end of its context window. |
- |
spring.ai.openai.chat.options.presencePenalty |
A value between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model’s likelihood to talk about new topics. Incompatible with |
0 |
spring.ai.openai.chat.options.topP |
The nucleus sampling threshold, valued between 0 and 1 inclusive. For each subsequent token, the model considers the results of the tokens with top_p probability mass. We recommend either altering top_k or top_p, but not both. Required range: |
0.9 |
spring.ai.openai.chat.options.stream-usage |
(For streaming only) Set to add an additional chunk with token usage statistics for the entire request. The |
false |
以 |
All properties prefixed with |
Runtime Options
OpenAiChatOptions.java 提供模型配置,如要使用的模型、温度、频率惩罚等。
The OpenAiChatOptions.java provides model configurations, such as the model to use, the temperature, the frequency penalty, etc.
启动时,可以使用 OpenAiChatModel(api, options)
构造函数或 spring.ai.openai.chat.options.*
属性配置默认选项。
On start-up, the default options can be configured with the OpenAiChatModel(api, options)
constructor or the spring.ai.openai.chat.options.*
properties.
在运行时,可以通过向 Prompt
调用中添加新的请求特定选项来覆盖默认选项。例如,覆盖特定请求的默认模型和温度:
At run-time you can override the default options by adding new, request specific, options to the Prompt
call.
For example to override the default model and temperature for a specific request:
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 实例。 |
In addition to the model specific OpenAiChatOptions you can use a portable ChatOptions instance, created with the ChatOptions#builder(). |
Function Calling
Perplexity 不支持显式函数调用。相反,它将搜索结果直接集成到响应中。 |
Perplexity does not support explicit function calling. Instead, it integrates search results directly into responses. |
Sample Controller
Create 一个新的 Spring Boot 项目,并将 spring-ai-starter-model-openai
添加到您的 pom(或 gradle)依赖项中。
Create a new Spring Boot project and add the spring-ai-starter-model-openai
to your pom (or gradle) dependencies.
在 src/main/resources
目录下添加一个 application.properties
文件,以启用和配置 OpenAI 聊天模型:
Add a application.properties
file, under the src/main/resources
directory, to enable and configure the OpenAi chat model:
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
用您的 Perplexity Api 密钥替换 |
replace the |
这将创建一个 OpenAiChatModel
实现,您可以将其注入到您的类中。这是一个简单的 @Controller
类示例,它使用聊天模型进行文本生成。
This will create a OpenAiChatModel
implementation that you can inject into your class.
Here is an example of a simple @Controller
class that uses the chat model for text generations.
@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);
}
}
Supported Models
Perplexity 支持多种针对搜索增强型对话式 AI 优化的模型。有关详细信息,请参阅 Supported Models 。
Perplexity supports several models optimized for search-enhanced conversational AI. Refer to Supported Models for details.