Azure OpenAI Chat

Azure 提供的基於 ChatGPT 的 OpenAI 服務超越了傳統的 OpenAI 功能,提供了增強的 AI 驅動文字生成能力。Azure 提供了額外的 AI 安全和負責任的 AI 功能,正如他們在 此處 的最新更新中強調的那樣。

Azure 為 Java 開發者提供了利用 AI 全部潛力的機會,透過將其與各種 Azure 服務整合,其中包括 Azure 上的向量儲存 (Vector Stores) 等 AI 相關資源。

先決條件

Azure OpenAI 客戶端提供了三種連線選項:使用 Azure API 金鑰、使用 OpenAI API 金鑰或使用 Microsoft Entra ID。

Azure API 金鑰與終結點

Azure 門戶 的 Azure OpenAI Service 部分獲取您的 Azure OpenAI endpointapi-key

Spring AI 定義了兩個配置屬性

  1. spring.ai.azure.openai.api-key: 將此屬性設定為從 Azure 獲取的 API Key 值。

  2. spring.ai.azure.openai.endpoint: 將此屬性設定為在 Azure 中預配模型時獲取的終結點 URL。

您可以透過匯出環境變數來設定這些配置屬性

export SPRING_AI_AZURE_OPENAI_API_KEY=<INSERT AZURE KEY HERE>
export SPRING_AI_AZURE_OPENAI_ENDPOINT=<INSERT ENDPOINT URL HERE>

OpenAI Key

要使用 OpenAI 服務(而非 Azure)進行身份驗證,請提供一個 OpenAI API 金鑰。這將自動將終結點設定為 api.openai.com/v1

使用此方法時,將 spring.ai.azure.openai.chat.options.deployment-name 屬性設定為您希望使用的 OpenAI 模型 的名稱。

export SPRING_AI_AZURE_OPENAI_OPENAI_API_KEY=<INSERT OPENAI KEY HERE>

Microsoft Entra ID

要使用 Microsoft Entra ID(以前稱為 Azure Active Directory)進行身份驗證,請在您的配置中建立一個 TokenCredential bean。如果此 bean 可用,將使用令牌憑據建立一個 OpenAIClient 例項。bd === 部署名稱

要使用 Azure AI 應用程式,您需要透過 Azure AI 門戶 建立一個 Azure AI 部署。在 Azure 中,每個客戶端都必須指定一個 Deployment Name 來連線到 Azure OpenAI 服務。請務必注意,Deployment Name 與您選擇部署的模型是不同的。例如,一個名為“MyAiDeployment”的部署可以配置為使用 GPT 3.5 Turbo 模型或 GPT 4.0 模型。

要開始使用,請按照以下步驟使用預設設定建立部署

Deployment Name: `gpt-4o`
Model Name: `gpt-4o`

此 Azure 配置與 Spring Boot Azure AI Starter 及其自動配置功能的預設配置一致。如果您使用不同的 Deployment Name,請務必相應地更新配置屬性

spring.ai.azure.openai.chat.options.deployment-name=<my deployment name>

Azure OpenAI 和 OpenAI 不同的部署結構導致 Azure OpenAI 客戶端庫中有一個名為 deploymentOrModelName 的屬性。這是因為在 OpenAI 中沒有 Deployment Name,只有 Model Name

屬性 spring.ai.azure.openai.chat.options.model 已重新命名為 spring.ai.azure.openai.chat.options.deployment-name
如果您決定連線到 OpenAI 而非 Azure OpenAI,透過設定 spring.ai.azure.openai.openai-api-key=<Your OpenAI Key> 屬性,則 spring.ai.azure.openai.chat.options.deployment-name 將被視為一個 OpenAI 模型 名稱。

訪問 OpenAI 模型

您可以將客戶端配置為直接使用 OpenAI,而不是 Azure OpenAI 部署的模型。為此,您需要設定 spring.ai.azure.openai.openai-api-key=<Your OpenAI Key>,而不是 spring.ai.azure.openai.api-key=<Your Azure OpenAi Key>

新增倉庫和 BOM

Spring AI 的製品釋出在 Maven Central 和 Spring Snapshot 倉庫。請參閱 倉庫 部分將這些倉庫新增到您的構建系統。

為了幫助管理依賴,Spring AI 提供了一個 BOM(物料清單),以確保在整個專案中使用一致版本的 Spring AI。請參閱 依賴管理 部分將 Spring AI BOM 新增到您的構建系統。

自動配置

Spring AI 自動配置、starter 模組的 artifact 名稱發生了重大變化。有關更多資訊,請參閱升級說明

Spring AI 為 Azure OpenAI Chat Client 提供了 Spring Boot 自動配置。要啟用它,請將以下依賴新增到您的專案 Maven pom.xml 或 Gradle build.gradle 構建檔案中

  • Maven

  • Gradle

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-azure-openai</artifactId>
</dependency>
dependencies {
    implementation 'spring-ai-starter-model-azure-openai'
}
請參閱 依賴管理 部分將 Spring AI BOM 新增到您的構建檔案。

Azure OpenAI Chat Client 是使用 Azure SDK 提供的 OpenAIClientBuilder 建立的。Spring AI 允許透過提供 AzureOpenAIClientBuilderCustomizer bean 來定製構建器。

例如,定製器可用於更改預設響應超時

@Configuration
public class AzureOpenAiConfig {

	@Bean
	public AzureOpenAIClientBuilderCustomizer responseTimeoutCustomizer() {
		return openAiClientBuilder -> {
			HttpClientOptions clientOptions = new HttpClientOptions()
					.setResponseTimeout(Duration.ofMinutes(5));
			openAiClientBuilder.httpClient(HttpClient.createDefault(clientOptions));
		};
	}

}

聊天屬性

字首 spring.ai.azure.openai 是配置與 Azure OpenAI 連線的屬性字首。

屬性 描述 預設值

spring.ai.azure.openai.api-key

從 Azure AI OpenAI 的“資源管理”下的“金鑰和終結點”部分獲取的 Key

-

spring.ai.azure.openai.endpoint

從 Azure AI OpenAI 的“資源管理”下的“金鑰和終結點”部分獲取的終結點

-

spring.ai.azure.openai.openai-api-key

(非 Azure) OpenAI API 金鑰。用於向 OpenAI 服務進行身份驗證,而不是 Azure OpenAI。這將自動將終結點設定為 api.openai.com/v1。使用 api-keyopenai-api-key 屬性中的一個。在此配置下,spring.ai.azure.openai.chat.options.deployment-name 被視為一個 OpenAI 模型 名稱。

-

spring.ai.azure.openai.custom-headers

包含在 API 請求中的自定義請求頭對映。對映中的每個條目代表一個請求頭,其中鍵是請求頭名稱,值是請求頭值。

空對映

聊天自動配置的啟用和停用現在透過字首為 spring.ai.model.chat 的頂級屬性進行配置。

要啟用,設定 spring.ai.model.chat=azure-openai(預設已啟用)

要停用,設定 spring.ai.model.chat=none(或任何與 azure-openai 不匹配的值)

進行此更改是為了允許配置多個模型。

字首 spring.ai.azure.openai.chat 是配置 Azure OpenAI 的 ChatModel 實現的屬性字首。

屬性 描述 預設值

spring.ai.azure.openai.chat.enabled (已移除且不再有效)

啟用 Azure OpenAI 聊天模型。

true

spring.ai.model.chat

啟用 Azure OpenAI 聊天模型。

azure-openai

spring.ai.azure.openai.chat.options.deployment-name

在 Azure 中使用時,這指的是您的模型的“部署名稱”,您可以在 oai.azure.com/portal 找到它。請務必注意,在 Azure OpenAI 部署中,“部署名稱”與模型本身是不同的。關於這些術語的混淆源於使 Azure OpenAI 客戶端庫與原始 OpenAI 終結點相容的意圖。Azure OpenAI 和 Sam Altman 的 OpenAI 提供的部署結構差異很大。作為此補全請求一部分提供的部署模型名稱。

gpt-4o

spring.ai.azure.openai.chat.options.maxTokens

要生成的最大 token 數。

-

spring.ai.azure.openai.chat.options.temperature

用於控制生成補全內容明顯創造性的取樣溫度。值越高,輸出越隨機;值越低,結果越集中和確定。不建議在同一個補全請求中同時修改 temperature 和 top_p,因為這兩個設定的相互作用難以預測。

0.7

spring.ai.azure.openai.chat.options.topP

一種替代溫度取樣的核取樣方法。此值導致模型考慮具有給定機率質量的 token 的結果。

-

spring.ai.azure.openai.chat.options.logitBias

GPT token ID 和偏差分數之間的對映,影響特定 token 出現在補全響應中的機率。token ID 透過外部分詞工具計算,而偏差分數的範圍在 -100 到 100 之間,最小值和最大值分別對應於完全禁止或獨佔選擇一個 token。給定偏差分數的具體行為因模型而異。

-

spring.ai.azure.openai.chat.options.user

操作的呼叫方或終端使用者的識別符號。這可用於跟蹤或速率限制目的。

-

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

(僅用於流式傳輸) 設定此項可新增一個額外的塊,其中包含整個請求的 token 用量統計資訊。此塊的 choices 欄位為空陣列,所有其他塊也將包含一個 usage 欄位,但值為 null。

false

spring.ai.azure.openai.chat.options.n

應為聊天補全響應生成的聊天補全選項數量。

-

spring.ai.azure.openai.chat.options.stop

將結束補全生成的文字序列集合。

-

spring.ai.azure.openai.chat.options.presencePenalty

根據生成文字中現有 token 的出現頻率影響生成 token 機率的值。正值會降低 token 在已存在時再次出現的可能性,並增加模型輸出新主題的可能性。

-

spring.ai.azure.openai.chat.options.responseFormat

指定模型必須輸出的格式的物件。使用 AzureOpenAiResponseFormat.JSON 啟用 JSON 模式,這保證模型生成的訊息是有效的 JSON。使用 AzureOpenAiResponseFormat.TEXT 啟用 TEXT 模式。

-

spring.ai.azure.openai.chat.options.frequencyPenalty

根據生成文字中 token 的累積頻率影響生成 token 機率的值。正值會降低 token 隨著頻率增加而出現的可能性,並降低模型逐字重複相同語句的可能性。

-

spring.ai.azure.openai.chat.options.proxy-tool-calls

如果為 true,Spring AI 將不會在內部處理函式呼叫,而是將其代理給客戶端。然後由客戶端負責處理函式呼叫,將其分派給適當的函式,並返回結果。如果為 false(預設值),Spring AI 將在內部處理函式呼叫。僅適用於支援函式呼叫的聊天模型。

false

所有以 spring.ai.azure.openai.chat.options 為字首的屬性都可以在執行時透過向 Prompt 呼叫新增請求特定的執行時選項來覆蓋。

執行時選項

The AzureOpenAiChatOptions.java 提供了模型配置,例如要使用的模型、溫度、頻率懲罰等。

在啟動時,可以使用 AzureOpenAiChatModel(api, options) 建構函式或 spring.ai.azure.openai.chat.options.* 屬性配置預設選項。

在執行時,您可以透過向 Prompt 呼叫新增新的、請求特定的選項來覆蓋預設選項。例如,為特定請求覆蓋預設模型和溫度

ChatResponse response = chatModel.call(
    new Prompt(
        "Generate the names of 5 famous pirates.",
        AzureOpenAiChatOptions.builder()
            .deploymentName("gpt-4o")
            .temperature(0.4)
        .build()
    ));
除了模型特定的 AzureOpenAiChatOptions.java,您還可以使用透過 ChatOptionsBuilder#builder() 建立的可移植 ChatOptions 例項。

函式呼叫

您可以將自定義 Java 函式註冊到 AzureOpenAiChatModel 中,並讓模型智慧地選擇輸出一個包含引數的 JSON 物件,以呼叫一個或多個已註冊的函式。這是一種將 LLM 能力與外部工具和 API 連線起來的強大技術。閱讀更多關於Azure OpenAI 函式呼叫的資訊。

多模態

多模態是指模型同時理解和處理來自各種來源(包括文字、影像、音訊和其他資料格式)資訊的能力。目前,Azure OpenAI 的 gpt-4o 模型支援多模態。

Azure OpenAI 可以在訊息中包含 base64 編碼的影像列表或影像 URL。Spring AI 的 Message 介面透過引入 Media 型別來促進多模態 AI 模型。此型別包含關於訊息中媒體附件的資料和詳細資訊,利用 Spring 的 org.springframework.util.MimeType 和一個 java.lang.Object 來表示原始媒體資料。

下面是從 OpenAiChatModelIT.java 摘錄的程式碼示例,演示了使用 GPT_4_O 模型將使用者文字與影像融合。

URL url = new URL("https://docs.springframework.tw/spring-ai/reference/_images/multimodal.test.png");
String response = ChatClient.create(chatModel).prompt()
        .options(AzureOpenAiChatOptions.builder().deploymentName("gpt-4o").build())
        .user(u -> u.text("Explain what do you see on this picture?").media(MimeTypeUtils.IMAGE_PNG, this.url))
        .call()
        .content();
您也可以傳遞多張圖片。

它將 multimodal.test.png 影像作為輸入

Multimodal Test Image

以及文字訊息“Explain what do you see on this picture?”,並生成如下響應

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.

您也可以傳遞類路徑資源,而不是 URL,如下例所示

Resource resource = new ClassPathResource("multimodality/multimodal.test.png");

String response = ChatClient.create(chatModel).prompt()
    .options(AzureOpenAiChatOptions.builder()
    .deploymentName("gpt-4o").build())
    .user(u -> u.text("Explain what do you see on this picture?")
    .media(MimeTypeUtils.IMAGE_PNG, this.resource))
    .call()
    .content();

示例 Controller

建立一個新的 Spring Boot 專案,並將 spring-ai-starter-model-azure-openai 新增到您的 pom(或 gradle)依賴中。

src/main/resources 目錄下新增一個 application.properties 檔案,以啟用和配置 OpenAi 聊天模型

spring.ai.azure.openai.api-key=YOUR_API_KEY
spring.ai.azure.openai.endpoint=YOUR_ENDPOINT
spring.ai.azure.openai.chat.options.deployment-name=gpt-4o
spring.ai.azure.openai.chat.options.temperature=0.7
api-keyendpoint 替換為您的 Azure OpenAI 憑據。

這將建立一個您可以注入到類中的 AzureOpenAiChatModel 實現。這是一個簡單的 `@Controller` 類使用聊天模型進行文字生成的示例。

@RestController
public class ChatController {

    private final AzureOpenAiChatModel chatModel;

    @Autowired
    public ChatController(AzureOpenAiChatModel 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);
    }
}

手動配置

The AzureOpenAiChatModel 實現了 ChatModelStreamingChatModel 介面,並使用了 Azure OpenAI Java Client

要啟用它,請將 spring-ai-azure-openai 依賴新增到您的專案 Maven pom.xml 檔案中

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-azure-openai</artifactId>
</dependency>

或新增到您的 Gradle build.gradle 構建檔案中。

dependencies {
    implementation 'org.springframework.ai:spring-ai-azure-openai'
}
請參閱 依賴管理 部分將 Spring AI BOM 新增到您的構建檔案。
spring-ai-azure-openai 依賴也提供了訪問 AzureOpenAiChatModel 的能力。有關 AzureOpenAiChatModel 的更多資訊,請參閱Azure OpenAI Chat 部分。

接下來,建立一個 AzureOpenAiChatModel 例項並使用它來生成文字響應

var openAIClientBuilder = new OpenAIClientBuilder()
  .credential(new AzureKeyCredential(System.getenv("AZURE_OPENAI_API_KEY")))
  .endpoint(System.getenv("AZURE_OPENAI_ENDPOINT"));

var openAIChatOptions = AzureOpenAiChatOptions.builder()
  .deploymentName("gpt-4o")
  .temperature(0.4)
  .maxTokens(200)
  .build();

var chatModel = AzureOpenAiChatModel.builder()
				.openAIClientBuilder(openAIClientBuilder)
				.defaultOptions(openAIChatOptions)
				.build();

ChatResponse response = chatModel.call(
  new Prompt("Generate the names of 5 famous pirates."));

// Or with streaming responses
Flux<ChatResponse> streamingResponses = chatModel.stream(
  new Prompt("Generate the names of 5 famous pirates."));
gpt-4o 實際上是在 Azure AI 門戶中顯示的 Deployment Name