侧边栏壁纸
博主头像
AI中文站

开拓MCP洪荒时代

  • 累计撰写 31 篇文章
  • 累计创建 3 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

SpringAI-Azure OpenAI Chat

Azure 的 OpenAI 服务(由 ChatGPT 驱动)超越传统 OpenAI 能力,提供增强功能的 AI 驱动文本生成。Azure 提供额外的 AI 安全和负责任 AI 功能,如其最近更新所述。

Azure 为 Java 开发者提供利用 AI 全部潜力的机会,通过与一系列 Azure 服务集成,包括 AI 相关资源(如 Azure 上的向量存储)。


先决条件

Azure OpenAI 客户端提供三种连接选项:使用 Azure API 密钥、OpenAI API 密钥或 Microsoft Entra ID。

Azure API 密钥和端点

要使用 API 密钥访问模型,请从 Azure 门户的 Azure OpenAI 服务部分获取 Azure OpenAI 端点和 api-key。

Spring AI 定义两个配置属性:

  • spring.ai.azure.openai.api-key:设置为从 Azure 获取的 API 密钥值。

  • spring.ai.azure.openai.endpoint:设置为在 Azure 中配置模型时获取的端点 URL。

您可在 application.properties 或 application.yml 文件中设置这些配置属性:

spring.ai.azure.openai.api-key=<您的-azure-api密钥>
spring.ai.azure.openai.endpoint=<您的-azure-端点-url>

为增强处理敏感信息(如 API 密钥)时的安全性,可使用 Spring 表达式语言(SpEL)引用自定义环境变量:

# In application.yml
spring:
  ai:
    azure:
      openai:
        api-key: ${AZURE_OPENAI_API_KEY}
        endpoint: ${AZURE_OPENAI_ENDPOINT}
# In your environment or .env file
export AZURE_OPENAI_API_KEY=<your-azure-openai-api-key>
export AZURE_OPENAI_ENDPOINT=<your-azure-openai-endpoint-url>


OpenAI 密钥

要验证 OpenAI 服务(非 Azure),请提供 OpenAI API 密钥。这将自动将端点设置为 api.openai.com/v1。

使用此方法时,设置 spring.ai.azure.openai.chat.options.deployment-name 属性为您希望使用的 OpenAI 模型名称。

在应用程序配置中:

spring.ai.azure.openai.openai-api-key=<您的-azure-openai密钥>
spring.ai.azure.openai.chat.options.deployment-name=<openai-模型名称>


使用带 SpEL 的环境变量:

# In application.yml
spring:
  ai:
    azure:
      openai:
        openai-api-key: ${AZURE_OPENAI_API_KEY}
        chat:
          options:
            deployment-name: ${AZURE_OPENAI_MODEL_NAME}
# In your environment or .env file
export AZURE_OPENAI_API_KEY=<your-openai-key>
export AZURE_OPENAI_MODEL_NAME=<openai-model-name>


Microsoft Entra ID

对于使用 Microsoft Entra ID(原 Azure Active Directory)的无密钥验证,仅设置 spring.ai.azure.openai.endpoint 配置属性,不设置上述 api-key 属性。

仅找到端点属性时,您的应用程序将评估多种检索凭证的选项,并将使用令牌凭证创建 OpenAIClient 实例。

不再需要创建 TokenCredential bean;它会自动为您配置。


部署名称

要使用 Azure AI 应用程序,您需要通过 Azure AI 门户创建 Azure AI 部署。在 Azure 中,每个客户端必须指定部署名称以连接到 Azure OpenAI 服务。请注意,部署名称与您选择部署的模型不同。例如,名为 "MyAiDeployment" 的部署可配置为使用 GPT 3.5 Turbo 模型或 GPT 4.0 模型。

要开始使用,请按照以下步骤使用默认设置创建部署:

部署名称:gpt-4o
模型名称:gpt-4o

此 Azure 配置与 Spring Boot Azure AI Starter 及其自动配置功能的默认配置一致。如果使用不同的部署名称,请确保相应地更新配置属性:

spring.ai.azure.openai.chat.options.deployment-name=<我的部署名称>

Azure OpenAI 和 OpenAI 的不同部署结构导致 Azure OpenAI 客户端库中有一个名为 deploymentOrModelName 的属性。这是因为 OpenAI 中没有部署名称,只有模型名称。

属性 spring.ai.azure.openai.chat.options.model 已重命名为 spring.ai.azure.openai.chat.options.deployment-name。
如果决定通过设置 spring.ai.azure.openai.openai-api-key=<您的 OpenAI 密钥> 属性连接到 OpenAI 而非 Azure OpenAI,则 spring.ai.azure.openai.chat.options.deployment-name 将被视为 OpenAI 模型名称。


访问 OpenAI 模型
您可将客户端配置为直接使用 OpenAI,而非 Azure OpenAI 部署的模型。为此需设置 spring.ai.azure.openai.openai-api-key=<您的 OpenAI 密钥> 而非 spring.ai.azure.openai.api-key=<您的 Azure OpenAi 密钥>。

添加仓库和 BOM
Spring AI 构件发布在 Maven Central 和 Spring Snapshot 仓库。参考构件仓库部分将这些仓库添加到构建系统。

为帮助依赖管理,Spring AI 提供 BOM(材料清单)确保整个项目使用一致的 Spring AI 版本。参考依赖管理部分将 Spring AI BOM 添加到构建系统。

自动配置

Spring AI 自动配置和 starter 模块的构件名称已发生重大变更。请参考升级说明获取更多信息。

Spring AI 为 Azure OpenAI 聊天客户端提供 Spring Boot 自动配置。要启用它,请将以下依赖项添加到项目的 Maven pom.xml 或 Gradle build.gradle 构建文件:

Maven

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

Gradle

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-model-azure-openai'
}


参考依赖管理部分将 Spring AI BOM 添加到构建文件。
Azure OpenAI 聊天客户端使用 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 连接的属性前缀。

Property

Description

Default

spring.ai.azure.openai.api-key

The Key from Azure AI OpenAI Keys and Endpoint section under Resource Management

-

spring.ai.azure.openai.endpoint

The endpoint from the Azure AI OpenAI Keys and Endpoint section under Resource Management

-

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

(non Azure) OpenAI API key. Used to authenticate with the OpenAI service, instead of Azure OpenAI. This automatically sets the endpoint to api.openai.com/v1. Use either api-key or openai-api-key property. With this configuration the spring.ai.azure.openai.chat.options.deployment-name is threated as an OpenAi Model name.

-

spring.ai.azure.openai.custom-headers

A map of custom headers to be included in the API requests. Each entry in the map represents a header, where the key is the header name and the value is the header value.

Empty map

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

启用:spring.ai.model.chat=azure-openai(默认启用)

禁用:spring.ai.model.chat=none(或任何不匹配 azure-openai 的值)

此变更允许配置多个模型。

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

Property

Description

Default

spring.ai.azure.openai.chat.enabled (Removed and no longer valid)

Enable Azure OpenAI chat model.

true

spring.ai.model.chat

Enable Azure OpenAI chat model.

azure-openai

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

In use with Azure, this refers to the "Deployment Name" of your model, which you can find at oai.azure.com/portal. It’s important to note that within an Azure OpenAI deployment, the "Deployment Name" is distinct from the model itself. The confusion around these terms stems from the intention to make the Azure OpenAI client library compatible with the original OpenAI endpoint. The deployment structures offered by Azure OpenAI and Sam Altman’s OpenAI differ significantly. Deployments model name to provide as part of this completions request.

gpt-4o

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

The maximum number of tokens to generate.

-

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

The sampling temperature to use that controls the apparent creativity of generated completions. Higher values will make output more random while lower values will make results more focused and deterministic. It is not recommended to modify temperature and top_p for the same completions request as the interaction of these two settings is difficult to predict.

0.7

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

An alternative to sampling with temperature called nucleus sampling. This value causes the model to consider the results of tokens with the provided probability mass.

-

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

A map between GPT token IDs and bias scores that influences the probability of specific tokens appearing in a completions response. Token IDs are computed via external tokenizer tools, while bias scores reside in the range of -100 to 100 with minimum and maximum values corresponding to a full ban or exclusive selection of a token, respectively. The exact behavior of a given bias score varies by model.

-

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

An identifier for the caller or end user of the operation. This may be used for tracking or rate-limiting purposes.

-

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

(For streaming only) Set to add an additional chunk with token usage statistics for the entire request. The choices field for this chunk is an empty array and all other chunks will also include a usage field, but with a null value.

false

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

The number of chat completions choices that should be generated for a chat completions response.

-

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

A collection of textual sequences that will end completions generation.

-

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

A value that influences the probability of generated tokens appearing based on their existing presence in generated text. Positive values will make tokens less likely to appear when they already exist and increase the model’s likelihood to output new topics.

-

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

An object specifying the format that the model must output. Using AzureOpenAiResponseFormat.JSON enables JSON mode, which guarantees the message the model generates is valid JSON. Using AzureOpenAiResponseFormat.TEXT enables TEXT mode.

-

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

A value that influences the probability of generated tokens appearing based on their cumulative frequency in generated text. Positive values will make tokens less likely to appear as their frequency increases and decrease the likelihood of the model repeating the same statements verbatim.

-

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

If true, the Spring AI will not handle the function calls internally, but will proxy them to the client. Then is the client’s responsibility to handle the function calls, dispatch them to the appropriate function, and return the results. If false (the default), the Spring AI will handle the function calls internally. Applicable only for chat models with function calling support

false

所有以 spring.ai.azure.openai.chat.options 为前缀的属性可在运行时通过向 Prompt 调用添加请求特定的运行时选项来覆盖。


运行时选项

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 实例。

函数调用

您可向 AzureOpenAiChatModel 注册自定义 Java 函数,让模型智能选择输出包含参数的 JSON 对象来调用一个或多个注册函数。这是将 LLM 能力与外部工具和 API 连接的强大技术。阅读更多关于工具调用的信息。

多模态

多模态指模型同时理解和处理多种来源信息的能力,包括文本、图像、音频、数据格式。目前,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.spring.io/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 图像作为输入:

image-lrrt.png
附带文本消息"解释你在这张图片中看到了什么?",并生成类似响应:

这是一个设计简洁的水果碗图像。碗由金属制成,带有弯曲的金属丝边缘,
形成开放式结构,可以从各个角度看到水果。碗内有两根黄色香蕉覆盖在
一个红苹果上。香蕉皮上的棕色斑点表明它们略微过熟。碗顶部有一个
金属环,可能用作提手。碗放置在一个平面上,中性色背景清晰地展现了碗内的水果。


您也可以传入类路径资源而非 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();



Sample Controller

创建新的 Spring Boot 项目,并将 spring-ai-starter-model-azure-openai 添加到您的 pom(或 gradle)依赖项。

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

spring.ai.azure.openai.api-key=您的_API密钥
spring.ai.azure.openai.endpoint=您的_ENDPOINT
spring.ai.azure.openai.chat.options.deployment-name=gpt-4o
spring.ai.azure.openai.chat.options.temperature=0.7


将 api-key 和 endpoint 替换为您的 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);
    }
}


手动配置


AzureOpenAiChatModel 实现 ChatModel 和 StreamingChatModel,并使用 Azure OpenAI Java 客户端。

要启用它,请将 spring-ai-azure-openai 依赖项添加到项目的 Maven pom.xml 文件:

<dependency>

<groupId>org.springframework.ai</groupId>

<artifactId>spring-ai-azure-openai</artifactId>

</dependency>

Gradle

dependencies {

implementation 'org.springframework.ai:spring-ai-azure-openai'

}

参考依赖管理部分将 Spring AI BOM 添加到构建文件。
spring-ai-azure-openai 依赖项还提供对 AzureOpenAiChatModel 的访问。有关 AzureOpenAiChatModel 的更多信息,请参考 Azure OpenAI 聊天部分。
接下来,创建 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 门户中显示的部署名称。

0

评论区