OpenAI 聊天
Spring AI 支援 OpenAI 的各種 AI 語言模型。OpenAI 是 ChatGPT 背後的公司,它建立了業界領先的文字生成模型和嵌入,極大地激發了人們對 AI 驅動的文字生成的興趣。
先決條件
您需要使用 OpenAI 建立一個 API 來訪問 ChatGPT 模型。請在 OpenAI 註冊頁面 建立賬戶,並在 API Keys 頁面 生成令牌。Spring AI 專案定義了一個名為 spring.ai.openai.api-key
的配置屬性,您應該將其設定為從 openai.com 獲取的 API Key
的值。匯出環境變數是設定該配置屬性的一種方法。
export SPRING_AI_OPENAI_API_KEY=<INSERT KEY HERE>
自動配置
Spring AI 自動配置、Starter 模組的構件名稱發生了重大變化。有關更多資訊,請參閱升級注意事項。 |
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,並且不對 |
false |
spring.ai.retry.exclude-on-http-codes |
不應觸發重試的 HTTP 狀態程式碼列表(例如,丟擲 NonTransientAiException)。 |
空 |
spring.ai.retry.on-http-codes |
應觸發重試的 HTTP 狀態程式碼列表(例如,丟擲 TransientAiException)。 |
空 |
連線屬性
字首 spring.ai.openai
用作屬性字首,您可以透過它連線到 OpenAI。
屬性 | 描述 | 預設值 |
---|---|---|
spring.ai.openai.base-url |
要連線的 URL |
|
spring.ai.openai.api-key |
API Key |
- |
spring.ai.openai.organization-id |
可選地,您可以指定用於 API 請求的組織 ID。 |
- |
spring.ai.openai.project-id |
可選地,您可以指定用於 API 請求的專案 ID。 |
- |
對於屬於多個組織(或透過其舊使用者 API 金鑰訪問其專案)的使用者,您可以選擇指定用於 API 請求的組織和專案。這些 API 請求的使用量將計入指定的組織和專案的使用量中。 |
配置屬性
聊天自動配置的啟用和停用現在透過字首為 要啟用,設定 spring.ai.model.chat=openai(預設已啟用) 要停用,設定 spring.ai.model.chat=none(或任何不匹配 openai 的值) 進行此更改是為了支援配置多個模型。 |
字首 spring.ai.openai.chat
用作屬性字首,您可以透過它配置 OpenAI 的聊天模型實現。
屬性 | 描述 | 預設值 |
---|---|---|
spring.ai.openai.chat.enabled (已移除且不再有效) |
啟用 OpenAI 聊天模型。 |
true |
spring.ai.model.chat |
啟用 OpenAI 聊天模型。 |
openai |
spring.ai.openai.chat.base-url |
可選地,覆蓋 |
- |
spring.ai.openai.chat.completions-path |
附加到基本 URL 的路徑。 |
|
spring.ai.openai.chat.api-key |
可選地,覆蓋 |
- |
spring.ai.openai.chat.organization-id |
可選地,您可以指定用於 API 請求的組織 ID。 |
- |
spring.ai.openai.chat.project-id |
可選地,您可以指定用於 API 請求的專案 ID。 |
- |
spring.ai.openai.chat.options.model |
要使用的 OpenAI 聊天模型的名稱。您可以選擇的模型包括: |
|
spring.ai.openai.chat.options.temperature |
用於控制生成完成結果的顯式創造性的取樣溫度。值越高會使輸出更隨機,而值越低會使結果更集中和確定。不建議在同一個完成請求中同時修改 |
0.8 |
spring.ai.openai.chat.options.frequencyPenalty |
介於 -2.0 和 2.0 之間的數值。正值會根據文字中迄今為止現有頻率來懲罰新令牌,從而降低模型逐字重複同一行的可能性。 |
0.0f |
spring.ai.openai.chat.options.logitBias |
修改指定令牌出現在完成結果中的可能性。 |
- |
spring.ai.openai.chat.options.maxTokens |
(已棄用,推薦使用 |
- |
spring.ai.openai.chat.options.maxCompletionTokens |
完成結果可生成的令牌數的上限,包括可見輸出令牌和推理令牌。 |
- |
spring.ai.openai.chat.options.n |
為每個輸入訊息生成多少個聊天完成選項。請注意,您將根據所有選項中生成的令牌總數進行計費。將 |
1 |
spring.ai.openai.chat.options.store |
是否儲存此聊天完成請求的輸出,供我們的模型使用 |
false |
spring.ai.openai.chat.options.metadata |
開發者定義的標籤和值,用於在聊天完成儀表板中過濾完成結果 |
空 map |
spring.ai.openai.chat.options.output-modalities |
您希望模型為此請求生成的輸出型別。大多數模型能夠生成文字,這是預設型別。 |
- |
spring.ai.openai.chat.options.output-audio |
音訊生成的音訊引數。當透過 |
- |
spring.ai.openai.chat.options.presencePenalty |
介於 -2.0 和 2.0 之間的數值。正值會根據新令牌是否迄今為止出現在文字中來懲罰新令牌,從而增加模型討論新主題的可能性。 |
- |
spring.ai.openai.chat.options.responseFormat.type |
相容 |
- |
spring.ai.openai.chat.options.responseFormat.name |
響應格式 schema 名稱。僅適用於 |
custom_schema |
spring.ai.openai.chat.options.responseFormat.schema |
響應格式 JSON schema。僅適用於 |
- |
spring.ai.openai.chat.options.responseFormat.strict |
響應格式 JSON schema 遵從嚴格性。僅適用於 |
- |
spring.ai.openai.chat.options.seed |
此功能處於 Beta 階段。如果指定,我們的系統將盡最大努力確定性地進行取樣,以便使用相同的 seed 和引數重複請求應返回相同的結果。 |
- |
spring.ai.openai.chat.options.stop |
API 將停止生成更多令牌的序列列表,最多 4 個。 |
- |
spring.ai.openai.chat.options.topP |
取樣溫度的替代方法,稱為核取樣 (nucleus sampling),模型考慮機率質量為 |
- |
spring.ai.openai.chat.options.tools |
模型可以呼叫的工具列表。目前,僅函式作為工具受支援。使用此引數提供模型可能生成 JSON 輸入的函式列表。 |
- |
spring.ai.openai.chat.options.toolChoice |
控制模型呼叫哪個(如果有)函式。 |
- |
spring.ai.openai.chat.options.user |
表示您的終端使用者的唯一識別符號,可以幫助 OpenAI 監控和檢測濫用行為。 |
- |
spring.ai.openai.chat.options.functions |
函式列表,按其名稱標識,用於在單個 Prompt 請求中啟用函式呼叫。具有這些名稱的函式必須存在於 |
- |
spring.ai.openai.chat.options.stream-usage |
(僅用於流式傳輸) 設定後將新增一個額外的 chunk,其中包含整個請求的 token 使用統計資訊。此 chunk 的 |
false |
spring.ai.openai.chat.options.parallel-tool-calls |
在使用工具時是否啟用並行函式呼叫。 |
true |
spring.ai.openai.chat.options.http-headers |
要新增到聊天完成請求的可選 HTTP header。要覆蓋 |
- |
spring.ai.openai.chat.options.proxy-tool-calls |
如果為 true,Spring AI 將不會在內部處理函式呼叫,而是將其代理給客戶端。然後由客戶端負責處理函式呼叫,將其分派給適當的函式,並返回結果。如果為 false(預設值),Spring AI 將在內部處理函式呼叫。僅適用於支援函式呼叫的聊天模型。 |
false |
您可以為 ChatModel 和 EmbeddingModel 實現覆蓋通用的 spring.ai.openai.base-url 和 spring.ai.openai.api-key 。如果設定了 spring.ai.openai.chat.base-url 和 spring.ai.openai.chat.api-key 屬性,它們將優先於通用屬性。如果您想為不同的模型和不同的模型端點使用不同的 OpenAI 賬戶,這將非常有用。 |
所有以 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("gpt-4o")
.temperature(0.4)
.build()
));
除了模型特定的 OpenAiChatOptions 外,您還可以使用一個可移植的 ChatOptions 例項,透過 ChatOptionsBuilder#builder() 建立。 |
函式呼叫
您可以向 OpenAiChatModel
註冊自定義 Java 函式,並讓 OpenAI 模型智慧地選擇輸出一個包含呼叫一個或多個已註冊函式所需引數的 JSON 物件。這是一種將大型語言模型能力與外部工具和 API 連線起來的強大技術。閱讀更多關於OpenAI 函式呼叫的資訊。
多模態
多模態指模型同時理解和處理來自各種來源資訊的能力,包括文字、影像、音訊和其他資料格式。OpenAI 支援文字、視覺和音訊輸入模態。
視覺
支援視覺多模態的 OpenAI 模型包括 gpt-4
、gpt-4o
和 gpt-4o-mini
。有關更多資訊,請參閱視覺指南。
OpenAI 使用者訊息 API 可以在訊息中包含 base64 編碼的影像列表或影像 URL。Spring AI 的 Message 介面透過引入 Media 型別來促進多模態 AI 模型。此型別包含訊息中媒體附件的資料和詳細資訊,利用 Spring 的 org.springframework.util.MimeType
和 org.springframework.core.io.Resource
來表示原始媒體資料。
下面是摘自 OpenAiChatModelIT.java 的程式碼示例,演示了使用 gpt-4o
模型將使用者文字與影像融合。
var imageResource = new ClassPathResource("/multimodal.test.png");
var userMessage = new UserMessage("Explain what do you see on this picture?",
new Media(MimeTypeUtils.IMAGE_PNG, this.imageResource));
ChatResponse response = chatModel.call(new Prompt(this.userMessage,
OpenAiChatOptions.builder().model(OpenAiApi.ChatModel.GPT_4_O.getValue()).build()));
GPT_4_VISION_PREVIEW 模型將從 2024 年 6 月 17 日起僅對現有使用者開放。如果您不是現有使用者,請使用 GPT_4_O 或 GPT_4_TURBO 模型。更多詳情請參閱此處。 |
或者使用 gpt-4o
模型的影像 URL 等效示例
var userMessage = new UserMessage("Explain what do you see on this picture?",
new Media(MimeTypeUtils.IMAGE_PNG,
URI.create("https://docs.springframework.tw/spring-ai/reference/_images/multimodal.test.png")));
ChatResponse response = chatModel.call(new Prompt(this.userMessage,
OpenAiChatOptions.builder().model(OpenAiApi.ChatModel.GPT_4_O.getValue()).build()));
您也可以傳遞多個影像。 |
該示例展示了模型以 multimodal.test.png
影像作為輸入

以及文字訊息“解釋一下你在這張圖片上看到了什麼?”,並生成如下響應
This is an image of a fruit bowl with a simple design. The bowl is made of metal with curved wire edges that create an open structure, allowing the fruit to be visible from all angles. Inside the bowl, there are two yellow bananas resting on top of what appears to be a red apple. The bananas are slightly overripe, as indicated by the brown spots on their peels. The bowl has a metal ring at the top, likely to serve as a handle for carrying. The bowl is placed on a flat surface with a neutral-colored background that provides a clear view of the fruit inside.
音訊
支援輸入音訊多模態的 OpenAI 模型包括 gpt-4o-audio-preview
。有關更多資訊,請參閱音訊指南。
OpenAI 使用者訊息 API 可以在訊息中包含 base64 編碼的音訊檔案列表。Spring AI 的 Message 介面透過引入 Media 型別來促進多模態 AI 模型。此型別包含訊息中媒體附件的資料和詳細資訊,利用 Spring 的 org.springframework.util.MimeType
和 org.springframework.core.io.Resource
來表示原始媒體資料。目前,OpenAI 僅支援以下媒體型別:audio/mp3
和 audio/wav
。
下面是摘自 OpenAiChatModelIT.java 的程式碼示例,演示了使用 gpt-4o-audio-preview
模型將使用者文字與音訊檔案融合。
var audioResource = new ClassPathResource("speech1.mp3");
var userMessage = new UserMessage("What is this recording about?",
List.of(new Media(MimeTypeUtils.parseMimeType("audio/mp3"), audioResource)));
ChatResponse response = chatModel.call(new Prompt(List.of(userMessage),
OpenAiChatOptions.builder().model(OpenAiApi.ChatModel.GPT_4_O_AUDIO_PREVIEW).build()));
您也可以傳遞多個音訊檔案。 |
輸出音訊
支援輸入音訊多模態的 OpenAI 模型包括 gpt-4o-audio-preview
。有關更多資訊,請參閱音訊指南。
OpenAI 助手訊息 API 可以在訊息中包含 base64 編碼的音訊檔案列表。Spring AI 的 Message 介面透過引入 Media 型別來促進多模態 AI 模型。此型別包含訊息中媒體附件的資料和詳細資訊,利用 Spring 的 org.springframework.util.MimeType
和 org.springframework.core.io.Resource
來表示原始媒體資料。目前,OpenAI 僅支援以下音訊型別:audio/mp3
和 audio/wav
。
下面是一個程式碼示例,演示了使用 gpt-4o-audio-preview
模型,將使用者文字響應連同音訊位元組陣列一起返回
var userMessage = new UserMessage("Tell me joke about Spring Framework");
ChatResponse response = chatModel.call(new Prompt(List.of(userMessage),
OpenAiChatOptions.builder()
.model(OpenAiApi.ChatModel.GPT_4_O_AUDIO_PREVIEW)
.outputModalities(List.of("text", "audio"))
.outputAudio(new AudioParameters(Voice.ALLOY, AudioResponseFormat.WAV))
.build()));
String text = response.getResult().getOutput().getContent(); // audio transcript
byte[] waveAudio = response.getResult().getOutput().getMedia().get(0).getDataAsByteArray(); // audio data
您必須在 OpenAiChatOptions
中指定 audio
模態才能生成音訊輸出。AudioParameters
類提供音訊輸出的語音和音訊格式。
結構化輸出
OpenAI 提供自定義的結構化輸出 API,確保您的模型生成嚴格符合您提供的 JSON Schema
的響應。除了現有的與 Spring AI 模型無關的結構化輸出轉換器之外,這些 API 還提供了增強的控制和精度。
目前,OpenAI 支援 JSON Schema 語言格式的子集。 |
配置
Spring AI 允許您使用 OpenAiChatOptions
構建器以程式設計方式配置響應格式,或透過應用程式屬性進行配置。
使用 Chat Options 構建器
您可以使用 OpenAiChatOptions
構建器以程式設計方式設定響應格式,如下所示
String jsonSchema = """
{
"type": "object",
"properties": {
"steps": {
"type": "array",
"items": {
"type": "object",
"properties": {
"explanation": { "type": "string" },
"output": { "type": "string" }
},
"required": ["explanation", "output"],
"additionalProperties": false
}
},
"final_answer": { "type": "string" }
},
"required": ["steps", "final_answer"],
"additionalProperties": false
}
""";
Prompt prompt = new Prompt("how can I solve 8x + 7 = -23",
OpenAiChatOptions.builder()
.model(ChatModel.GPT_4_O_MINI)
.responseFormat(new ResponseFormat(ResponseFormat.Type.JSON_SCHEMA, this.jsonSchema))
.build());
ChatResponse response = this.openAiChatModel.call(this.prompt);
請遵守 OpenAI JSON Schema 語言格式的子集。 |
與 BeanOutputConverter 工具整合
您可以利用現有的BeanOutputConverter工具,自動從您的領域物件生成 JSON Schema,然後將結構化響應轉換為領域特定的例項。
-
Java
-
Kotlin
record MathReasoning(
@JsonProperty(required = true, value = "steps") Steps steps,
@JsonProperty(required = true, value = "final_answer") String finalAnswer) {
record Steps(
@JsonProperty(required = true, value = "items") Items[] items) {
record Items(
@JsonProperty(required = true, value = "explanation") String explanation,
@JsonProperty(required = true, value = "output") String output) {
}
}
}
var outputConverter = new BeanOutputConverter<>(MathReasoning.class);
var jsonSchema = this.outputConverter.getJsonSchema();
Prompt prompt = new Prompt("how can I solve 8x + 7 = -23",
OpenAiChatOptions.builder()
.model(ChatModel.GPT_4_O_MINI)
.responseFormat(new ResponseFormat(ResponseFormat.Type.JSON_SCHEMA, this.jsonSchema))
.build());
ChatResponse response = this.openAiChatModel.call(this.prompt);
String content = this.response.getResult().getOutput().getContent();
MathReasoning mathReasoning = this.outputConverter.convert(this.content);
data class MathReasoning(
val steps: Steps,
@get:JsonProperty(value = "final_answer") val finalAnswer: String) {
data class Steps(val items: Array<Items>) {
data class Items(
val explanation: String,
val output: String)
}
}
val outputConverter = BeanOutputConverter(MathReasoning::class.java)
val jsonSchema = outputConverter.jsonSchema;
val prompt = Prompt("how can I solve 8x + 7 = -23",
OpenAiChatOptions.builder()
.model(ChatModel.GPT_4_O_MINI)
.responseFormat(ResponseFormat(ResponseFormat.Type.JSON_SCHEMA, jsonSchema))
.build())
val response = openAiChatModel.call(prompt)
val content = response.getResult().getOutput().getContent()
val mathReasoning = outputConverter.convert(content)
雖然這對於 JSON Schema 是可選的,但 OpenAI 要求結構化響應必須包含必需欄位才能正常工作。Kotlin 反射用於根據型別的可空性和引數的預設值來推斷哪些屬性是必需的或不是,因此對於大多數用例來說,不需要 @get:JsonProperty(required = true) 。@get:JsonProperty(value = "custom_name") 可以用於自定義屬性名稱。請確保使用此 @get: 語法在相關的 getter 上生成註解,請參閱相關文件。 |
透過應用程式屬性進行配置
或者,當使用 OpenAI 自動配置時,您可以透過以下應用程式屬性配置所需的響應格式
spring.ai.openai.api-key=YOUR_API_KEY
spring.ai.openai.chat.options.model=gpt-4o-mini
spring.ai.openai.chat.options.response-format.type=JSON_SCHEMA
spring.ai.openai.chat.options.response-format.name=MySchemaName
spring.ai.openai.chat.options.response-format.schema={"type":"object","properties":{"steps":{"type":"array","items":{"type":"object","properties":{"explanation":{"type":"string"},"output":{"type":"string"}},"required":["explanation","output"],"additionalProperties":false}},"final_answer":{"type":"string"}},"required":["steps","final_answer"],"additionalProperties":false}
spring.ai.openai.chat.options.response-format.strict=true
示例控制器
建立一個新的 Spring Boot 專案,並將 spring-ai-starter-model-openai
新增到您的 pom(或 gradle)依賴中。
在 src/main/resources
目錄下新增一個 application.properties
檔案,以啟用和配置 OpenAi 聊天模型
spring.ai.openai.api-key=YOUR_API_KEY
spring.ai.openai.chat.options.model=gpt-4o
spring.ai.openai.chat.options.temperature=0.7
將 api-key 替換為您自己的 OpenAI 憑據。 |
這將建立一個 OpenAiChatModel
實現,您可以將其注入到您的類中。這是一個簡單的 @RestController
類示例,它使用聊天模型進行文字生成。
@RestController
public class ChatController {
private final OpenAiChatModel chatModel;
@Autowired
public ChatController(OpenAiChatModel chatModel) {
this.chatModel = chatModel;
}
@GetMapping("/ai/generate")
public Map<String,String> 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);
}
}
手動配置
OpenAiChatModel 實現了 ChatModel
和 StreamingChatModel
介面,並使用底層 OpenAiApi 客戶端連線到 OpenAI 服務。
將 spring-ai-openai
依賴新增到您專案的 Maven pom.xml
檔案中
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai</artifactId>
</dependency>
或新增到您的 Gradle build.gradle
構建檔案中。
dependencies {
implementation 'org.springframework.ai:spring-ai-openai'
}
請參閱依賴管理部分,將 Spring AI BOM 新增到您的構建檔案中。 |
接下來,建立 OpenAiChatModel
並將其用於文字生成
var openAiApi = OpenAiApi.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.build();
var openAiChatOptions = OpenAiChatOptions.builder()
.model("gpt-3.5-turbo")
.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."));
OpenAiChatOptions
提供了聊天請求的配置資訊。OpenAiApi.Builder
和 OpenAiChatOptions.Builder
分別是用於 API 客戶端和聊天配置的流暢選項構建器。
底層 OpenAiApi 客戶端
OpenAiApi 提供了一個輕量級的 Java 客戶端,用於呼叫 OpenAI 聊天 API。
下圖展示了 OpenAiApi
聊天介面和構建塊的類圖

這是一個簡單的程式碼片段,展示瞭如何以程式設計方式使用 API
OpenAiApi openAiApi = OpenAiApi.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.build();
ChatCompletionMessage chatCompletionMessage =
new ChatCompletionMessage("Hello world", Role.USER);
// Sync request
ResponseEntity<ChatCompletion> response = this.openAiApi.chatCompletionEntity(
new ChatCompletionRequest(List.of(this.chatCompletionMessage), "gpt-3.5-turbo", 0.8, false));
// Streaming request
Flux<ChatCompletionChunk> streamResponse = this.openAiApi.chatCompletionStream(
new ChatCompletionRequest(List.of(this.chatCompletionMessage), "gpt-3.5-turbo", 0.8, true));
請參閱 OpenAiApi.java 的 JavaDoc 獲取更多資訊。
底層 API 示例
-
OpenAiApiIT.java 測試提供了一些使用這個輕量級庫的通用示例。
-
OpenAiApiToolFunctionCallIT.java 測試展示瞭如何使用底層 API 呼叫工具函式。這基於 OpenAI 函式呼叫教程。
API Key 管理
Spring AI 透過 ApiKey
介面及其實現提供了靈活的 API Key 管理。預設實現 SimpleApiKey
適用於大多數用例,但您也可以建立自定義實現來應對更復雜的場景。
預設配置
預設情況下,Spring Boot 自動配置將使用 spring.ai.openai.api-key
屬性建立一個 API Key Bean
spring.ai.openai.api-key=your-api-key-here
自定義 API Key 配置
您可以使用構建器模式,透過您自己的 ApiKey
實現建立一個自定義的 OpenAiApi
例項
ApiKey customApiKey = new ApiKey() {
@Override
public String getValue() {
// Custom logic to retrieve API key
return "your-api-key-here";
}
};
OpenAiApi openAiApi = OpenAiApi.builder()
.apiKey(customApiKey)
.build();
// Create a chat client with the custom OpenAiApi instance
OpenAiChatClient chatClient = new OpenAiChatClient(openAiApi);
當您需要以下情況時,這很有用:
-
從安全金鑰庫中檢索 API Key
-
動態輪換 API Key
-
實現自定義 API Key 選擇邏輯