Introduce AzureOpenAI transcription support

- Breaking changes: Classes from the org.springframework.ai.openai.metadata.audio.transcription package have been moved to the org.springframework.ai.audio.transcription package.
 - The AzureOpenAiAudioTranscriptionModel has been added to the auto-configuration.
 - The spring.ai.azure.openai.audio.transcription prefix was introduced for properties.
 - Introduces options properties which cover all of them (see: AzureOpenAiAudioTranscriptionOptions).
 - fix missing MutableResponseMetadata
 - add docs
 - adjust code to updated ResponseMetadata design
 - add test to AzureOpenAiAutoConfiguration
 - add missing AzureOpenAiAudioTranscriptionModel tests
This commit is contained in:
Piotr Olaszewski
2024-06-19 17:12:55 +02:00
committed by Christian Tzolov
parent 92ec519142
commit 0e97f9c579
31 changed files with 1094 additions and 124 deletions

View File

@@ -0,0 +1,201 @@
/*
* Copyright 2023 - 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.ai.azure.openai;
import com.azure.ai.openai.OpenAIClient;
import com.azure.ai.openai.models.AudioTranscriptionFormat;
import com.azure.ai.openai.models.AudioTranscriptionOptions;
import com.azure.ai.openai.models.AudioTranscriptionTimestampGranularity;
import com.azure.core.http.rest.Response;
import org.springframework.ai.audio.transcription.AudioTranscription;
import org.springframework.ai.audio.transcription.AudioTranscriptionPrompt;
import org.springframework.ai.audio.transcription.AudioTranscriptionResponse;
import org.springframework.ai.azure.openai.AzureOpenAiAudioTranscriptionOptions.GranularityType;
import org.springframework.ai.azure.openai.AzureOpenAiAudioTranscriptionOptions.StructuredResponse;
import org.springframework.ai.azure.openai.AzureOpenAiAudioTranscriptionOptions.StructuredResponse.Segment;
import org.springframework.ai.azure.openai.AzureOpenAiAudioTranscriptionOptions.StructuredResponse.Word;
import org.springframework.ai.azure.openai.AzureOpenAiAudioTranscriptionOptions.TranscriptResponseFormat;
import org.springframework.ai.azure.openai.metadata.AzureOpenAiAudioTranscriptionResponseMetadata;
import org.springframework.ai.model.Model;
import org.springframework.ai.model.ModelOptionsUtils;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.util.List;
/**
* AzureOpenAI audio transcription client implementation for backed by
* {@link OpenAIClient}. You provide as input the audio file you want to transcribe and
* the desired output file format of the transcription of the audio.
*
* @author Piotr Olaszewski
*/
public class AzureOpenAiAudioTranscriptionModel implements Model<AudioTranscriptionPrompt, AudioTranscriptionResponse> {
private static final List<AudioTranscriptionFormat> JSON_FORMATS = List.of(AudioTranscriptionFormat.JSON,
AudioTranscriptionFormat.VERBOSE_JSON);
private static final String FILENAME_MARKER = "filename.wav";
private final OpenAIClient openAIClient;
private final AzureOpenAiAudioTranscriptionOptions defaultOptions;
public AzureOpenAiAudioTranscriptionModel(OpenAIClient openAIClient, AzureOpenAiAudioTranscriptionOptions options) {
this.openAIClient = openAIClient;
this.defaultOptions = options;
}
public String call(Resource audioResource) {
AudioTranscriptionPrompt transcriptionRequest = new AudioTranscriptionPrompt(audioResource);
return call(transcriptionRequest).getResult().getOutput();
}
@Override
public AudioTranscriptionResponse call(AudioTranscriptionPrompt audioTranscriptionPrompt) {
String deploymentOrModelName = getDeploymentName(audioTranscriptionPrompt);
AudioTranscriptionOptions audioTranscriptionOptions = toAudioTranscriptionOptions(audioTranscriptionPrompt);
AudioTranscriptionFormat responseFormat = audioTranscriptionOptions.getResponseFormat();
if (JSON_FORMATS.contains(responseFormat)) {
var audioTranscription = openAIClient.getAudioTranscription(deploymentOrModelName, FILENAME_MARKER,
audioTranscriptionOptions);
List<Word> words = null;
if (audioTranscription.getWords() != null) {
words = audioTranscription.getWords().stream().map(w -> {
float start = (float) w.getStart().toSeconds();
float end = (float) w.getEnd().toSeconds();
return new Word(w.getWord(), start, end);
}).toList();
}
List<Segment> segments = null;
if (audioTranscription.getSegments() != null) {
segments = audioTranscription.getSegments().stream().map(s -> {
float start = (float) s.getStart().toSeconds();
float end = (float) s.getEnd().toSeconds();
return new Segment(s.getId(), s.getSeek(), start, end, s.getText(), s.getTokens(),
(float) s.getTemperature(), (float) s.getAvgLogprob(), (float) s.getCompressionRatio(),
(float) s.getNoSpeechProb());
}).toList();
}
Float duration = audioTranscription.getDuration() == null ? null
: (float) audioTranscription.getDuration().toSeconds();
StructuredResponse structuredResponse = new StructuredResponse(audioTranscription.getLanguage(), duration,
audioTranscription.getText(), words, segments);
AudioTranscription transcript = new AudioTranscription(structuredResponse.text());
AzureOpenAiAudioTranscriptionResponseMetadata metadata = AzureOpenAiAudioTranscriptionResponseMetadata
.from(structuredResponse);
return new AudioTranscriptionResponse(transcript, metadata);
}
else {
Response<String> audioTranscription = openAIClient.getAudioTranscriptionTextWithResponse(
deploymentOrModelName, FILENAME_MARKER, audioTranscriptionOptions, null);
String text = audioTranscription.getValue();
AudioTranscription transcript = new AudioTranscription(text);
return new AudioTranscriptionResponse(transcript, AzureOpenAiAudioTranscriptionResponseMetadata.from(text));
}
}
private String getDeploymentName(AudioTranscriptionPrompt audioTranscriptionPrompt) {
var runtimeOptions = audioTranscriptionPrompt.getOptions();
if (defaultOptions != null) {
runtimeOptions = ModelOptionsUtils.merge(runtimeOptions, this.defaultOptions,
AzureOpenAiAudioTranscriptionOptions.class);
}
if (runtimeOptions instanceof AzureOpenAiAudioTranscriptionOptions azureOpenAiAudioTranscriptionOptions) {
String deploymentName = azureOpenAiAudioTranscriptionOptions.getDeploymentName();
if (StringUtils.hasText(deploymentName)) {
return deploymentName;
}
}
return runtimeOptions.getModel();
}
private AudioTranscriptionOptions toAudioTranscriptionOptions(AudioTranscriptionPrompt audioTranscriptionPrompt) {
var runtimeOptions = audioTranscriptionPrompt.getOptions();
if (this.defaultOptions != null) {
runtimeOptions = ModelOptionsUtils.merge(runtimeOptions, this.defaultOptions,
AzureOpenAiAudioTranscriptionOptions.class);
}
byte[] bytes = toBytes(audioTranscriptionPrompt.getInstructions());
AudioTranscriptionOptions audioTranscriptionOptions = new AudioTranscriptionOptions(bytes);
if (runtimeOptions instanceof AzureOpenAiAudioTranscriptionOptions azureOpenAiAudioTranscriptionOptions) {
String model = azureOpenAiAudioTranscriptionOptions.getModel();
if (StringUtils.hasText(model)) {
audioTranscriptionOptions.setModel(model);
}
String language = azureOpenAiAudioTranscriptionOptions.getLanguage();
if (StringUtils.hasText(language)) {
audioTranscriptionOptions.setLanguage(language);
}
String prompt = azureOpenAiAudioTranscriptionOptions.getPrompt();
if (StringUtils.hasText(prompt)) {
audioTranscriptionOptions.setPrompt(prompt);
}
Float temperature = azureOpenAiAudioTranscriptionOptions.getTemperature();
if (temperature != null) {
audioTranscriptionOptions.setTemperature(temperature.doubleValue());
}
TranscriptResponseFormat responseFormat = azureOpenAiAudioTranscriptionOptions.getResponseFormat();
List<GranularityType> granularityType = azureOpenAiAudioTranscriptionOptions.getGranularityType();
if (responseFormat != null) {
audioTranscriptionOptions.setResponseFormat(responseFormat.getValue());
if (responseFormat == TranscriptResponseFormat.VERBOSE_JSON && granularityType == null) {
granularityType = List.of(GranularityType.SEGMENT);
}
}
if (granularityType != null) {
Assert.isTrue(responseFormat == TranscriptResponseFormat.VERBOSE_JSON,
"response_format must be set to verbose_json to use timestamp granularities.");
List<AudioTranscriptionTimestampGranularity> granularity = granularityType.stream()
.map(GranularityType::getValue)
.toList();
audioTranscriptionOptions.setTimestampGranularities(granularity);
}
}
return audioTranscriptionOptions;
}
private static byte[] toBytes(Resource resource) {
try {
return resource.getInputStream().readAllBytes();
}
catch (IOException e) {
throw new IllegalArgumentException("Failed to read resource: " + resource, e);
}
}
}

View File

@@ -0,0 +1,359 @@
/*
* Copyright 2023 - 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.ai.azure.openai;
import com.azure.ai.openai.models.AudioTranscriptionFormat;
import com.azure.ai.openai.models.AudioTranscriptionTimestampGranularity;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.ai.audio.transcription.AudioTranscriptionOptions;
import org.springframework.util.Assert;
import java.util.List;
/**
* @author Piotr Olaszewski
*/
@JsonInclude(Include.NON_NULL)
public class AzureOpenAiAudioTranscriptionOptions implements AudioTranscriptionOptions {
public static final String DEFAULT_AUDIO_TRANSCRIPTION_MODEL = WhisperModel.WHISPER.getValue();
// @formatter:off
/**
* ID of the model to use.
*/
private @JsonProperty("model") String model = DEFAULT_AUDIO_TRANSCRIPTION_MODEL;
/**
* The deployment name as defined in Azure Open AI Studio when creating a deployment
* backed by an Azure OpenAI base model.
*/
private @JsonProperty(value = "deployment_name") String deploymentName;
/**
* The format of the transcript output, in one of these options: json, text, srt, verbose_json, or vtt.
*/
private @JsonProperty("response_format") TranscriptResponseFormat responseFormat = TranscriptResponseFormat.JSON;
private @JsonProperty("prompt") String prompt;
private @JsonProperty("language") String language;
/**
* What sampling temperature to use, between 0 and 1. Higher values like 0.8 will make the output
* more random, while lower values like 0.2 will make it more focused and deterministic.
*/
private @JsonProperty("temperature") Float temperature = 0F;
private @JsonProperty("timestamp_granularities") List<GranularityType> granularityType;
public static Builder builder() {
return new Builder();
}
public static class Builder {
protected AzureOpenAiAudioTranscriptionOptions options;
public Builder() {
this.options = new AzureOpenAiAudioTranscriptionOptions();
}
public Builder(AzureOpenAiAudioTranscriptionOptions options) {
this.options = options;
}
public Builder withModel(String model) {
this.options.model = model;
return this;
}
public Builder withDeploymentName(String deploymentName) {
this.options.setDeploymentName(deploymentName);
return this;
}
public Builder withLanguage(String language) {
this.options.language = language;
return this;
}
public Builder withPrompt(String prompt) {
this.options.prompt = prompt;
return this;
}
public Builder withResponseFormat(TranscriptResponseFormat responseFormat) {
this.options.responseFormat = responseFormat;
return this;
}
public Builder withTemperature(Float temperature) {
this.options.temperature = temperature;
return this;
}
public Builder withGranularityType(List<GranularityType> granularityType) {
this.options.granularityType = granularityType;
return this;
}
public AzureOpenAiAudioTranscriptionOptions build() {
Assert.hasText(options.model, "model must not be empty");
Assert.notNull(options.responseFormat, "response_format must not be null");
return this.options;
}
}
@Override
public String getModel() {
return this.model;
}
public void setModel(String model) {
this.model = model;
}
public String getDeploymentName() {
return deploymentName;
}
public void setDeploymentName(String deploymentName) {
this.deploymentName = deploymentName;
}
public String getLanguage() {
return this.language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getPrompt() {
return this.prompt;
}
public void setPrompt(String prompt) {
this.prompt = prompt;
}
public Float getTemperature() {
return this.temperature;
}
public void setTemperature(Float temperature) {
this.temperature = temperature;
}
public TranscriptResponseFormat getResponseFormat() {
return this.responseFormat;
}
public void setResponseFormat(TranscriptResponseFormat responseFormat) {
this.responseFormat = responseFormat;
}
public List<GranularityType> getGranularityType() {
return this.granularityType;
}
public void setGranularityType(List<GranularityType> granularityType) {
this.granularityType = granularityType;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((model == null) ? 0 : model.hashCode());
result = prime * result + ((prompt == null) ? 0 : prompt.hashCode());
result = prime * result + ((language == null) ? 0 : language.hashCode());
result = prime * result + ((responseFormat == null) ? 0 : responseFormat.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AzureOpenAiAudioTranscriptionOptions other = (AzureOpenAiAudioTranscriptionOptions) obj;
if (this.model == null) {
if (other.model != null)
return false;
}
else if (!model.equals(other.model))
return false;
if (this.prompt == null) {
if (other.prompt != null)
return false;
}
else if (!this.prompt.equals(other.prompt))
return false;
if (this.language == null) {
if (other.language != null)
return false;
}
else if (!this.language.equals(other.language))
return false;
if (this.responseFormat == null) {
return other.responseFormat==null;
}
else return this.responseFormat.equals(other.responseFormat);
}
public enum WhisperModel {
// @formatter:off
@JsonProperty("whisper") WHISPER("whisper");
// @formatter:on
public final String value;
WhisperModel(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
/**
* @param language The language of the transcribed text.
* @param duration The duration of the audio in seconds.
* @param text The transcribed text.
* @param words The extracted words and their timestamps.
* @param segments The segments of the transcribed text and their corresponding
* details.
*/
@JsonInclude(Include.NON_NULL)
public record StructuredResponse(
// @formatter:off
@JsonProperty("language") String language,
@JsonProperty("duration") Float duration,
@JsonProperty("text") String text,
@JsonProperty("words") List<Word> words,
@JsonProperty("segments") List<Segment> segments) {
// @formatter:on
/**
* Extracted word and it's corresponding timestamps.
*
* @param word The text content of the word.
* @param start The start time of the word in seconds.
* @param end The end time of the word in seconds.
*/
@JsonInclude(Include.NON_NULL)
public record Word(
// @formatter:off
@JsonProperty("word") String word,
@JsonProperty("start") Float start,
@JsonProperty("end") Float end) {
// @formatter:on
}
/**
* Segment of the transcribed text and its corresponding details.
*
* @param id Unique identifier of the segment.
* @param seek Seek offset of the segment.
* @param start Start time of the segment in seconds.
* @param end End time of the segment in seconds.
* @param text The text content of the segment.
* @param tokens Array of token IDs for the text content.
* @param temperature Temperature parameter used for generating the segment.
* @param avgLogprob Average logprob of the segment. If the value is lower than
* -1, consider the logprobs failed.
* @param compressionRatio Compression ratio of the segment. If the value is
* greater than 2.4, consider the compression failed.
* @param noSpeechProb Probability of no speech in the segment. If the value is
* higher than 1.0 and the avg_logprob is below -1, consider this segment silent.
*/
@JsonInclude(Include.NON_NULL)
public record Segment(
// @formatter:off
@JsonProperty("id") Integer id,
@JsonProperty("seek") Integer seek,
@JsonProperty("start") Float start,
@JsonProperty("end") Float end,
@JsonProperty("text") String text,
@JsonProperty("tokens") List<Integer> tokens,
@JsonProperty("temperature") Float temperature,
@JsonProperty("avg_logprob") Float avgLogprob,
@JsonProperty("compression_ratio") Float compressionRatio,
@JsonProperty("no_speech_prob") Float noSpeechProb) {
// @formatter:on
}
}
public enum TranscriptResponseFormat {
// @formatter:off
@JsonProperty("json") JSON(AudioTranscriptionFormat.JSON, StructuredResponse.class),
@JsonProperty("text") TEXT(AudioTranscriptionFormat.TEXT, String.class),
@JsonProperty("srt") SRT(AudioTranscriptionFormat.SRT, String.class),
@JsonProperty("verbose_json") VERBOSE_JSON(AudioTranscriptionFormat.VERBOSE_JSON, StructuredResponse.class),
@JsonProperty("vtt") VTT(AudioTranscriptionFormat.VTT, String.class);
public final AudioTranscriptionFormat value;
public final Class<?> responseType;
TranscriptResponseFormat(AudioTranscriptionFormat value, Class<?> responseType) {
this.value = value;
this.responseType = responseType;
}
public AudioTranscriptionFormat getValue() {
return this.value;
}
public Class<?> getResponseType() {
return this.responseType;
}
}
public enum GranularityType {
// @formatter:off
@JsonProperty("word") WORD(AudioTranscriptionTimestampGranularity.WORD),
@JsonProperty("segment") SEGMENT(AudioTranscriptionTimestampGranularity.SEGMENT);
// @formatter:on
public final AudioTranscriptionTimestampGranularity value;
GranularityType(AudioTranscriptionTimestampGranularity value) {
this.value = value;
}
public AudioTranscriptionTimestampGranularity getValue() {
return this.value;
}
}
}

View File

@@ -89,7 +89,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
*/
public class AzureOpenAiChatModel extends AbstractToolCallSupport implements ChatModel {
private static final String DEFAULT_DEPLOYMENT_NAME = "gpt-35-turbo";
private static final String DEFAULT_DEPLOYMENT_NAME = "gpt-4o";
private static final Float DEFAULT_TEMPERATURE = 0.7f;

View File

@@ -15,8 +15,6 @@
*/
package org.springframework.ai.azure.openai;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import org.springframework.ai.embedding.EmbeddingOptions;

View File

@@ -0,0 +1,53 @@
/*
* Copyright 2023 - 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.ai.azure.openai.metadata;
import org.springframework.ai.audio.transcription.AudioTranscriptionResponseMetadata;
import org.springframework.ai.azure.openai.AzureOpenAiAudioTranscriptionOptions;
import org.springframework.util.Assert;
/**
* Audio transcription metadata implementation for {@literal AzureOpenAI}.
*
* @author Piotr Olaszewski
*/
public class AzureOpenAiAudioTranscriptionResponseMetadata extends AudioTranscriptionResponseMetadata {
protected static final String AI_METADATA_STRING = "{ @type: %1$s }";
public static final AzureOpenAiAudioTranscriptionResponseMetadata NULL = new AzureOpenAiAudioTranscriptionResponseMetadata() {
};
public static AzureOpenAiAudioTranscriptionResponseMetadata from(
AzureOpenAiAudioTranscriptionOptions.StructuredResponse result) {
Assert.notNull(result, "AzureOpenAI Transcription must not be null");
return new AzureOpenAiAudioTranscriptionResponseMetadata();
}
public static AzureOpenAiAudioTranscriptionResponseMetadata from(String result) {
Assert.notNull(result, "AzureOpenAI Transcription must not be null");
return new AzureOpenAiAudioTranscriptionResponseMetadata();
}
protected AzureOpenAiAudioTranscriptionResponseMetadata() {
}
@Override
public String toString() {
return AI_METADATA_STRING.formatted(getClass().getName());
}
}

View File

@@ -0,0 +1,84 @@
package org.springframework.ai.azure.openai;
import com.azure.ai.openai.OpenAIClient;
import com.azure.ai.openai.OpenAIClientBuilder;
import com.azure.ai.openai.OpenAIServiceVersion;
import com.azure.core.credential.AzureKeyCredential;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.ai.audio.transcription.AudioTranscriptionPrompt;
import org.springframework.ai.audio.transcription.AudioTranscriptionResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.Resource;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Piotr Olaszewski
*/
@SpringBootTest(classes = AzureOpenAiAudioTranscriptionModelIT.TestConfiguration.class)
@EnabledIfEnvironmentVariable(named = "AZURE_OPENAI_API_KEY", matches = ".+")
@EnabledIfEnvironmentVariable(named = "AZURE_OPENAI_ENDPOINT", matches = ".+")
@EnabledIfEnvironmentVariable(named = "AZURE_OPENAI_TRANSCRIPTION_DEPLOYMENT_NAME", matches = ".+")
class AzureOpenAiAudioTranscriptionModelIT {
@Value("classpath:/speech/jfk.flac")
private Resource audioFile;
@Autowired
private AzureOpenAiAudioTranscriptionModel transcriptionModel;
@Test
void transcriptionTest() {
AzureOpenAiAudioTranscriptionOptions transcriptionOptions = AzureOpenAiAudioTranscriptionOptions.builder()
.withResponseFormat(AzureOpenAiAudioTranscriptionOptions.TranscriptResponseFormat.TEXT)
.withTemperature(0f)
.build();
AudioTranscriptionPrompt transcriptionRequest = new AudioTranscriptionPrompt(audioFile, transcriptionOptions);
AudioTranscriptionResponse response = transcriptionModel.call(transcriptionRequest);
assertThat(response.getResults()).hasSize(1);
assertThat(response.getResults().get(0).getOutput().toLowerCase().contains("fellow")).isTrue();
}
@Test
void transcriptionTestWithOptions() {
AzureOpenAiAudioTranscriptionOptions.TranscriptResponseFormat responseFormat = AzureOpenAiAudioTranscriptionOptions.TranscriptResponseFormat.VTT;
AzureOpenAiAudioTranscriptionOptions transcriptionOptions = AzureOpenAiAudioTranscriptionOptions.builder()
.withLanguage("en")
.withPrompt("Ask not this, but ask that")
.withTemperature(0f)
.withResponseFormat(responseFormat)
.build();
AudioTranscriptionPrompt transcriptionRequest = new AudioTranscriptionPrompt(audioFile, transcriptionOptions);
AudioTranscriptionResponse response = transcriptionModel.call(transcriptionRequest);
assertThat(response.getResults()).hasSize(1);
assertThat(response.getResults().get(0).getOutput().toLowerCase().contains("fellow")).isTrue();
}
@SpringBootConfiguration
public static class TestConfiguration {
@Bean
public OpenAIClient openAIClient() {
return new OpenAIClientBuilder().credential(new AzureKeyCredential(System.getenv("AZURE_OPENAI_API_KEY")))
.endpoint(System.getenv("AZURE_OPENAI_ENDPOINT"))
.serviceVersion(OpenAIServiceVersion.V2024_02_15_PREVIEW)
.buildClient();
}
@Bean
public AzureOpenAiAudioTranscriptionModel azureOpenAiChatModel(OpenAIClient openAIClient) {
return new AzureOpenAiAudioTranscriptionModel(openAIClient,
AzureOpenAiAudioTranscriptionOptions.builder()
.withDeploymentName(System.getenv("AZURE_OPENAI_TRANSCRIPTION_DEPLOYMENT_NAME"))
.build());
}
}
}

View File

@@ -15,16 +15,11 @@
*/
package org.springframework.ai.azure.openai;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import com.azure.ai.openai.OpenAIClient;
import com.azure.ai.openai.OpenAIClientBuilder;
import com.azure.ai.openai.OpenAIServiceVersion;
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.http.policy.HttpLogOptions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.slf4j.Logger;
@@ -48,9 +43,16 @@ import org.springframework.context.annotation.Bean;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.util.MimeTypeUtils;
import com.azure.ai.openai.OpenAIClient;
import com.azure.ai.openai.OpenAIClientBuilder;
import com.azure.core.credential.AzureKeyCredential;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import static com.azure.core.http.policy.HttpLogDetailLevel.BODY_AND_HEADERS;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(classes = AzureOpenAiChatModelIT.TestConfiguration.class)
@EnabledIfEnvironmentVariable(named = "AZURE_OPENAI_API_KEY", matches = ".+")
@@ -217,13 +219,15 @@ class AzureOpenAiChatModelIT {
public OpenAIClient openAIClient() {
return new OpenAIClientBuilder().credential(new AzureKeyCredential(System.getenv("AZURE_OPENAI_API_KEY")))
.endpoint(System.getenv("AZURE_OPENAI_ENDPOINT"))
.serviceVersion(OpenAIServiceVersion.V2024_02_15_PREVIEW)
.httpLogOptions(new HttpLogOptions().setLogLevel(BODY_AND_HEADERS))
.buildClient();
}
@Bean
public AzureOpenAiChatModel azureOpenAiChatModel(OpenAIClient openAIClient) {
return new AzureOpenAiChatModel(openAIClient,
AzureOpenAiChatOptions.builder().withDeploymentName("gpt-35-turbo").withMaxTokens(1000).build());
AzureOpenAiChatOptions.builder().withDeploymentName("gpt-4o").withMaxTokens(1000).build());
}

View File

@@ -22,7 +22,7 @@ import com.azure.ai.openai.OpenAIClientBuilder;
import com.azure.core.credential.AzureKeyCredential;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.ai.document.MetadataMode;
import org.springframework.ai.embedding.EmbeddingResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
@@ -75,7 +75,8 @@ class AzureOpenAiEmbeddingModelIT {
@Bean
public AzureOpenAiEmbeddingModel azureEmbeddingModel(OpenAIClient openAIClient) {
return new AzureOpenAiEmbeddingModel(openAIClient);
return new AzureOpenAiEmbeddingModel(openAIClient, MetadataMode.EMBED,
AzureOpenAiEmbeddingOptions.builder().withDeploymentName("text-embedding-ada-002").build());
}
}

View File

@@ -240,7 +240,7 @@ class AzureOpenAiChatModelMetadataTests {
"completion_tokens":68,
"total_tokens":126
},
"prompt_annotations" : [{
"prompt_filter_results" : [{
"prompt_index" : 0,
"content_filter_results" : {
"error" : null,

View File

@@ -38,9 +38,9 @@ import org.springframework.ai.chat.metadata.RateLimit;
import org.springframework.ai.model.Model;
import org.springframework.ai.openai.api.OpenAiAudioApi;
import org.springframework.ai.openai.api.OpenAiAudioApi.StructuredResponse;
import org.springframework.ai.openai.audio.transcription.AudioTranscription;
import org.springframework.ai.openai.audio.transcription.AudioTranscriptionPrompt;
import org.springframework.ai.openai.audio.transcription.AudioTranscriptionResponse;
import org.springframework.ai.audio.transcription.AudioTranscription;
import org.springframework.ai.audio.transcription.AudioTranscriptionPrompt;
import org.springframework.ai.audio.transcription.AudioTranscriptionResponse;
import org.springframework.ai.openai.metadata.audio.OpenAiAudioTranscriptionResponseMetadata;
import org.springframework.ai.openai.metadata.support.OpenAiResponseHeaderExtractor;
import org.springframework.ai.retry.RetryUtils;
@@ -185,7 +185,7 @@ public class OpenAiAudioTranscriptionModel implements Model<AudioTranscriptionPr
}
}
OpenAiAudioApi.TranscriptionRequest audioTranscriptionRequest = OpenAiAudioApi.TranscriptionRequest.builder()
return OpenAiAudioApi.TranscriptionRequest.builder()
.withFile(toBytes(request.getInstructions()))
.withResponseFormat(options.getResponseFormat())
.withPrompt(options.getPrompt())
@@ -194,8 +194,6 @@ public class OpenAiAudioTranscriptionModel implements Model<AudioTranscriptionPr
.withModel(options.getModel())
.withGranularityType(options.getGranularityType())
.build();
return audioTranscriptionRequest;
}
private byte[] toBytes(Resource resource) {

View File

@@ -18,18 +18,18 @@ package org.springframework.ai.openai;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.ai.model.ModelOptions;
import org.springframework.ai.audio.transcription.AudioTranscriptionOptions;
import org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptResponseFormat;
import org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptionRequest.GranularityType;
/**
* @author Michael Lavelle
* @author Christian Tzolov
* @author Piotr Olaszewski
* @since 0.8.1
*/
@JsonInclude(Include.NON_NULL)
public class OpenAiAudioTranscriptionOptions implements ModelOptions {
public class OpenAiAudioTranscriptionOptions implements AudioTranscriptionOptions {
// @formatter:off
/**
@@ -106,6 +106,7 @@ public class OpenAiAudioTranscriptionOptions implements ModelOptions {
}
@Override
public String getModel() {
return this.model;
}

View File

@@ -15,6 +15,7 @@
*/
package org.springframework.ai.openai.metadata.audio;
import org.springframework.ai.audio.transcription.AudioTranscriptionResponseMetadata;
import org.springframework.ai.chat.metadata.EmptyRateLimit;
import org.springframework.ai.chat.metadata.RateLimit;
import org.springframework.ai.model.MutableResponseMetadata;
@@ -27,10 +28,11 @@ import org.springframework.util.Assert;
* Audio transcription metadata implementation for {@literal OpenAI}.
*
* @author Michael Lavelle
* @since 0.8.1
* @author Piotr Olaszewski
* @see RateLimit
* @since 0.8.1
*/
public class OpenAiAudioTranscriptionResponseMetadata extends MutableResponseMetadata {
public class OpenAiAudioTranscriptionResponseMetadata extends AudioTranscriptionResponseMetadata {
protected static final String AI_METADATA_STRING = "{ @type: %1$s, rateLimit: %4$s }";
@@ -39,14 +41,12 @@ public class OpenAiAudioTranscriptionResponseMetadata extends MutableResponseMet
public static OpenAiAudioTranscriptionResponseMetadata from(OpenAiAudioApi.StructuredResponse result) {
Assert.notNull(result, "OpenAI Transcription must not be null");
OpenAiAudioTranscriptionResponseMetadata transcriptionResponseMetadata = new OpenAiAudioTranscriptionResponseMetadata();
return transcriptionResponseMetadata;
return new OpenAiAudioTranscriptionResponseMetadata();
}
public static OpenAiAudioTranscriptionResponseMetadata from(String result) {
Assert.notNull(result, "OpenAI Transcription must not be null");
OpenAiAudioTranscriptionResponseMetadata transcriptionResponseMetadata = new OpenAiAudioTranscriptionResponseMetadata();
return transcriptionResponseMetadata;
return new OpenAiAudioTranscriptionResponseMetadata();
}
@Nullable

View File

@@ -20,7 +20,7 @@ import org.junit.jupiter.api.Test;
import org.springframework.ai.openai.api.OpenAiAudioApi;
import org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptResponseFormat;
import org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptionRequest.GranularityType;
import org.springframework.ai.openai.audio.transcription.AudioTranscriptionPrompt;
import org.springframework.ai.audio.transcription.AudioTranscriptionPrompt;
import org.springframework.core.io.DefaultResourceLoader;
import static org.assertj.core.api.Assertions.assertThat;

View File

@@ -18,6 +18,8 @@ package org.springframework.ai.openai.audio.transcription;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.ai.audio.transcription.AudioTranscriptionPrompt;
import org.springframework.ai.audio.transcription.AudioTranscriptionResponse;
import org.springframework.ai.openai.OpenAiAudioTranscriptionOptions;
import org.springframework.ai.openai.OpenAiTestConfiguration;
import org.springframework.ai.openai.api.OpenAiAudioApi;

View File

@@ -15,15 +15,14 @@
*/
package org.springframework.ai.openai.audio.transcription;
import java.time.Duration;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.ai.audio.transcription.AudioTranscriptionMetadata;
import org.springframework.ai.audio.transcription.AudioTranscriptionPrompt;
import org.springframework.ai.audio.transcription.AudioTranscriptionResponse;
import org.springframework.ai.chat.metadata.RateLimit;
import org.springframework.ai.openai.OpenAiAudioTranscriptionModel;
import org.springframework.ai.openai.api.OpenAiAudioApi;
import org.springframework.ai.openai.metadata.audio.OpenAiAudioTranscriptionMetadata;
import org.springframework.ai.openai.metadata.audio.OpenAiAudioTranscriptionResponseMetadata;
import org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders;
import org.springframework.ai.retry.RetryUtils;
@@ -39,10 +38,10 @@ import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestClient;
import java.time.Duration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.header;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.*;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
/**
@@ -77,7 +76,8 @@ public class OpenAiTranscriptionModelWithTranscriptionResponseMetadataTests {
assertThat(response).isNotNull();
OpenAiAudioTranscriptionResponseMetadata transcriptionResponseMetadata = response.getMetadata();
OpenAiAudioTranscriptionResponseMetadata transcriptionResponseMetadata = (OpenAiAudioTranscriptionResponseMetadata) response
.getMetadata();
assertThat(transcriptionResponseMetadata).isNotNull();
@@ -101,7 +101,7 @@ public class OpenAiTranscriptionModelWithTranscriptionResponseMetadataTests {
assertThat(rateLimit.getTokensReset()).isEqualTo(expectedTokensReset);
response.getResults().forEach(transcript -> {
OpenAiAudioTranscriptionMetadata transcriptionMetadata = transcript.getMetadata();
AudioTranscriptionMetadata transcriptionMetadata = transcript.getMetadata();
assertThat(transcriptionMetadata).isNotNull();
});
}

View File

@@ -18,6 +18,9 @@ package org.springframework.ai.openai.audio.transcription;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.ai.audio.transcription.AudioTranscription;
import org.springframework.ai.audio.transcription.AudioTranscriptionPrompt;
import org.springframework.ai.audio.transcription.AudioTranscriptionResponse;
import org.springframework.ai.openai.OpenAiAudioTranscriptionModel;
import org.springframework.core.io.Resource;

View File

@@ -55,8 +55,8 @@ import org.springframework.ai.openai.api.OpenAiImageApi;
import org.springframework.ai.openai.api.OpenAiImageApi.Data;
import org.springframework.ai.openai.api.OpenAiImageApi.OpenAiImageRequest;
import org.springframework.ai.openai.api.OpenAiImageApi.OpenAiImageResponse;
import org.springframework.ai.openai.audio.transcription.AudioTranscriptionPrompt;
import org.springframework.ai.openai.audio.transcription.AudioTranscriptionResponse;
import org.springframework.ai.audio.transcription.AudioTranscriptionPrompt;
import org.springframework.ai.audio.transcription.AudioTranscriptionResponse;
import org.springframework.ai.retry.RetryUtils;
import org.springframework.ai.retry.TransientAiException;
import org.springframework.core.io.ClassPathResource;

View File

@@ -150,7 +150,7 @@
<azure-open-ai-client.version>1.0.0-beta.10</azure-open-ai-client.version>
<jtokkit.version>1.1.0</jtokkit.version>
<victools.version>4.31.1</victools.version>
<!-- NOTE: keep them align -->
<bedrockruntime.version>2.26.7</bedrockruntime.version>
<awssdk.version>2.26.7</awssdk.version>
@@ -186,7 +186,6 @@
<qdrant.version>1.9.1</qdrant.version>
<typesense.version>0.5.0</typesense.version>
<opensearch-client.version>2.10.1</opensearch-client.version>
<!-- testing dependencies -->
<httpclient5.version>5.3.1</httpclient5.version>

View File

@@ -13,10 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.ai.openai.audio.transcription;
package org.springframework.ai.audio.transcription;
import org.springframework.ai.model.ModelResult;
import org.springframework.ai.openai.metadata.audio.OpenAiAudioTranscriptionMetadata;
import org.springframework.lang.Nullable;
import java.util.Objects;
@@ -25,13 +24,14 @@ import java.util.Objects;
* Represents a response returned by the AI.
*
* @author Michael Lavelle
* @author Piotr Olaszewski
* @since 0.8.1
*/
public class AudioTranscription implements ModelResult<String> {
private String text;
private final String text;
private OpenAiAudioTranscriptionMetadata transcriptionMetadata;
private AudioTranscriptionMetadata transcriptionMetadata;
public AudioTranscription(String text) {
this.text = text;
@@ -43,12 +43,11 @@ public class AudioTranscription implements ModelResult<String> {
}
@Override
public OpenAiAudioTranscriptionMetadata getMetadata() {
return transcriptionMetadata != null ? transcriptionMetadata : OpenAiAudioTranscriptionMetadata.NULL;
public AudioTranscriptionMetadata getMetadata() {
return transcriptionMetadata != null ? transcriptionMetadata : AudioTranscriptionMetadata.NULL;
}
public AudioTranscription withTranscriptionMetadata(
@Nullable OpenAiAudioTranscriptionMetadata transcriptionMetadata) {
public AudioTranscription withTranscriptionMetadata(@Nullable AudioTranscriptionMetadata transcriptionMetadata) {
this.transcriptionMetadata = transcriptionMetadata;
return this;
}

View File

@@ -13,24 +13,25 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Michael Lavelle
* @since 0.8.1
*/
package org.springframework.ai.openai.metadata.audio;
package org.springframework.ai.audio.transcription;
import org.springframework.ai.model.ResultMetadata;
public interface OpenAiAudioTranscriptionMetadata extends ResultMetadata {
/**
* @author Michael Lavelle
* @author Piotr Olaszewski
* @since 0.8.1
*/
public interface AudioTranscriptionMetadata extends ResultMetadata {
OpenAiAudioTranscriptionMetadata NULL = OpenAiAudioTranscriptionMetadata.create();
AudioTranscriptionMetadata NULL = AudioTranscriptionMetadata.create();
/**
* Factory method used to construct a new {@link OpenAiAudioTranscriptionMetadata}
* @return a new {@link OpenAiAudioTranscriptionMetadata}
* Factory method used to construct a new {@link AudioTranscriptionMetadata}
* @return a new {@link AudioTranscriptionMetadata}
*/
static OpenAiAudioTranscriptionMetadata create() {
return new OpenAiAudioTranscriptionMetadata() {
static AudioTranscriptionMetadata create() {
return new AudioTranscriptionMetadata() {
};
}

View File

@@ -0,0 +1,27 @@
/*
* Copyright 2023 - 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.ai.audio.transcription;
import org.springframework.ai.model.ModelOptions;
/**
* @author Piotr Olaszewski
*/
public interface AudioTranscriptionOptions extends ModelOptions {
String getModel();
}

View File

@@ -13,9 +13,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.ai.openai.audio.transcription;
package org.springframework.ai.audio.transcription;
import org.springframework.ai.model.ModelOptions;
import org.springframework.ai.model.ModelRequest;
import org.springframework.core.io.Resource;
@@ -25,13 +24,14 @@ import org.springframework.core.io.Resource;
* interact with an AI model, including the audio resource and model options.
*
* @author Michael Lavelle
* @author Piotr Olaszewski
* @since 0.8.1
*/
public class AudioTranscriptionPrompt implements ModelRequest<Resource> {
private Resource audioResource;
private final Resource audioResource;
private ModelOptions modelOptions;
private AudioTranscriptionOptions modelOptions;
/**
* Construct a new AudioTranscriptionPrompt given the resource representing the audio
@@ -50,7 +50,7 @@ public class AudioTranscriptionPrompt implements ModelRequest<Resource> {
* @param audioResource resource of the audio file.
* @param modelOptions
*/
public AudioTranscriptionPrompt(Resource audioResource, ModelOptions modelOptions) {
public AudioTranscriptionPrompt(Resource audioResource, AudioTranscriptionOptions modelOptions) {
this.audioResource = audioResource;
this.modelOptions = modelOptions;
}
@@ -61,7 +61,7 @@ public class AudioTranscriptionPrompt implements ModelRequest<Resource> {
}
@Override
public ModelOptions getOptions() {
public AudioTranscriptionOptions getOptions() {
return modelOptions;
}

View File

@@ -13,30 +13,29 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.ai.openai.audio.transcription;
package org.springframework.ai.audio.transcription;
import org.springframework.ai.model.ModelResponse;
import org.springframework.ai.openai.metadata.audio.OpenAiAudioTranscriptionResponseMetadata;
import java.util.Arrays;
import java.util.List;
/**
* @author Michael Lavelle
* @author Piotr Olaszewski
* @since 0.8.1
*/
public class AudioTranscriptionResponse implements ModelResponse<AudioTranscription> {
private AudioTranscription transcript;
private final AudioTranscription transcript;
private OpenAiAudioTranscriptionResponseMetadata transcriptionResponseMetadata;
private final AudioTranscriptionResponseMetadata transcriptionResponseMetadata;
public AudioTranscriptionResponse(AudioTranscription transcript) {
this(transcript, OpenAiAudioTranscriptionResponseMetadata.NULL);
this(transcript, new AudioTranscriptionResponseMetadata());
}
public AudioTranscriptionResponse(AudioTranscription transcript,
OpenAiAudioTranscriptionResponseMetadata transcriptionResponseMetadata) {
AudioTranscriptionResponseMetadata transcriptionResponseMetadata) {
this.transcript = transcript;
this.transcriptionResponseMetadata = transcriptionResponseMetadata;
}
@@ -48,11 +47,11 @@ public class AudioTranscriptionResponse implements ModelResponse<AudioTranscript
@Override
public List<AudioTranscription> getResults() {
return Arrays.asList(transcript);
return List.of(transcript);
}
@Override
public OpenAiAudioTranscriptionResponseMetadata getMetadata() {
public AudioTranscriptionResponseMetadata getMetadata() {
return transcriptionResponseMetadata;
}

View File

@@ -0,0 +1,25 @@
/*
* Copyright 2023 - 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.ai.audio.transcription;
import org.springframework.ai.model.MutableResponseMetadata;
/**
* @author Piotr Olaszewski
*/
public class AudioTranscriptionResponseMetadata extends MutableResponseMetadata {
}

View File

@@ -60,6 +60,7 @@
*** xref:api/image/qianfan-image.adoc[QianFan]
** xref:api/audio[Audio Model API]
*** xref:api/audio/transcriptions.adoc[]
**** xref:api/audio/transcriptions/azure-openai-transcriptions.adoc[Azure OpenAI]
**** xref:api/audio/transcriptions/openai-transcriptions.adoc[OpenAI]
*** xref:api/audio/speech.adoc[]
**** xref:api/audio/speech/openai-speech.adoc[OpenAI]

View File

@@ -0,0 +1,118 @@
= Azure OpenAI Transcriptions
Spring AI supports https://learn.microsoft.com/en-us/azure/ai-services/openai/whisper-quickstart?tabs=command-line%2Cpython-new&pivots=rest-api[Azure Whisper model].
== Prerequisites
Obtain your Azure OpenAI `endpoint` and `api-key` from the Azure OpenAI Service section on the link:https://portal.azure.com[Azure Portal].
Spring AI defines a configuration property named `spring.ai.azure.openai.api-key` that you should set to the value of the `API Key` obtained from Azure.
There is also a configuration property named `spring.ai.azure.openai.endpoint` that you should set to the endpoint URL obtained when provisioning your model in Azure.
Exporting an environment variable is one way to set that configuration property:
== Auto-configuration
Spring AI provides Spring Boot auto-configuration for the Azure OpenAI Transcription Generation Client.
To enable it, add the following dependency to your project's Maven `pom.xml` file:
[source,xml]
----
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-azure-openai-spring-boot-starter</artifactId>
</dependency>
----
or to your Gradle `build.gradle` build file.
[source,groovy]
----
dependencies {
implementation 'org.springframework.ai:spring-ai-azure-openai-spring-boot-starter'
}
----
TIP: Refer to the xref:getting-started.adoc#dependency-management[Dependency Management] section to add the Spring AI BOM to your build file.
=== Transcription Properties
The prefix `spring.ai.openai.audio.transcription` is used as the property prefix that lets you configure the retry mechanism for the OpenAI image model.
[cols="3,5,2"]
|====
| Property | Description | Default
| spring.ai.azure.openai.audio.transcription.enabled | Enable Azure OpenAI transcription model. | true
| spring.ai.azure.openai.audio.transcription.options.model | ID of the model to use. Only whisper is currently available. | whisper
| spring.ai.azure.openai.audio.transcription.options.deployment-name | The deployment name under which the model is deployed. |
| spring.ai.azure.openai.audio.transcription.options.response-format | The format of the transcript output, in one of these options: json, text, srt, verbose_json, or vtt. | json
| spring.ai.azure.openai.audio.transcription.options.prompt | An optional text to guide the model's style or continue a previous audio segment. The prompt should match the audio language. |
| spring.ai.azure.openai.audio.transcription.options.language | The language of the input audio. Supplying the input language in ISO-639-1 format will improve accuracy and latency. |
| spring.ai.azure.openai.audio.transcription.options.temperature | The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit. | 0
| spring.ai.azure.openai.audio.transcription.options.timestamp-granularities | The timestamp granularities to populate for this transcription. response_format must be set verbose_json to use timestamp granularities. Either or both of these options are supported: word, or segment. Note: There is no additional latency for segment timestamps, but generating word timestamps incurs additional latency. | segment
|====
== Runtime Options
The `AzureOpenAiAudioTranscriptionOptions` class provides the options to use when making a transcription.
On start-up, the options specified by `spring.ai.azure.openai.audio.transcription` are used, but you can override these at runtime.
For example:
[source,java]
----
AzureOpenAiAudioTranscriptionOptions.TranscriptResponseFormat responseFormat = AzureOpenAiAudioTranscriptionOptions.TranscriptResponseFormat.VTT;
AzureOpenAiAudioTranscriptionOptions transcriptionOptions = AzureOpenAiAudioTranscriptionOptions.builder()
.withLanguage("en")
.withPrompt("Ask not this, but ask that")
.withTemperature(0f)
.withResponseFormat(responseFormat)
.build();
AudioTranscriptionPrompt transcriptionRequest = new AudioTranscriptionPrompt(audioFile, transcriptionOptions);
AudioTranscriptionResponse response = azureOpenAiTranscriptionModel.call(transcriptionRequest);
----
== Manual Configuration
Add the `spring-ai-openai` dependency to your project's Maven `pom.xml` file:
[source,xml]
----
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-azure-openai</artifactId>
</dependency>
----
or to your Gradle `build.gradle` build file.
[source,groovy]
----
dependencies {
implementation 'org.springframework.ai:spring-ai-azure-openai'
}
----
TIP: Refer to the xref:getting-started.adoc#dependency-management[Dependency Management] section to add the Spring AI BOM to your build file.
Next, create a `AzureOpenAiAudioTranscriptionModel`
[source,java]
----
var openAIClient = new OpenAIClientBuilder()
.credential(new AzureKeyCredential(System.getenv("AZURE_OPENAI_API_KEY")))
.endpoint(System.getenv("AZURE_OPENAI_ENDPOINT"))
.buildClient();
var azureOpenAiAudioTranscriptionModel = new AzureOpenAiAudioTranscriptionModel(openAIClient, null);
var transcriptionOptions = AzureOpenAiAudioTranscriptionOptions.builder()
.withResponseFormat(TranscriptResponseFormat.TEXT)
.withTemperature(0f)
.build();
var audioFile = new FileSystemResource("/path/to/your/resource/speech/jfk.flac");
AudioTranscriptionPrompt transcriptionRequest = new AudioTranscriptionPrompt(audioFile, transcriptionOptions);
AudioTranscriptionResponse response = azureOpenAiAudioTranscriptionModel.call(transcriptionRequest);
----

View File

@@ -1,22 +1,20 @@
== OpenAI Transcriptions
= OpenAI Transcriptions
Spring AI supports https://platform.openai.com/docs/api-reference/audio/createTranscription[OpenAI's Transcription model].
== Prerequisites
You will need to create an API key with OpenAI to access ChatGPT models.
Create an account at https://platform.openai.com/signup[OpenAI signup page] and generate the token on the https://platform.openai.com/account/api-keys[API Keys page].
The Spring AI project defines a configuration property named `spring.ai.openai.api-key` that you should set to the value of the `API Key` obtained from openai.com.
Exporting an environment variable is one way to set that configuration property:
== Auto-configuration
Spring AI provides Spring Boot auto-configuration for the OpenAI Image Generation Client.
To enable it add the following dependency to your project's Maven `pom.xml` file:
To enable it, add the following dependency to your project's Maven `pom.xml` file:
[source, xml]
[source,xml]
----
<dependency>
<groupId>org.springframework.ai</groupId>
@@ -54,7 +52,7 @@ The prefix `spring.ai.openai.audio.transcription` is used as the property prefix
== Runtime Options [[image-options]]
The `OpenAiAudioTranscriptionOptions` class provides the options to use when making a transcription.
On start-up, the options specified by `spring.ai.openai.audio.transcription` are used but you can override these at runtime.
On start-up, the options specified by `spring.ai.openai.audio.transcription` are used, but you can override these at runtime.
For example:
@@ -76,7 +74,7 @@ AudioTranscriptionResponse response = openAiTranscriptionModel.call(transcriptio
Add the `spring-ai-openai` dependency to your project's Maven `pom.xml` file:
[source, xml]
[source,xml]
----
<dependency>
<groupId>org.springframework.ai</groupId>
@@ -115,4 +113,5 @@ AudioTranscriptionResponse response = openAiTranscriptionModel.call(transcriptio
----
== Example Code
* The link:https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-openai/src/test/java/org/springframework/ai/openai/audio/transcription/OpenAiTranscriptionModelIT.java[OpenAiTranscriptionModelIT.java] test provides some general examples how to use the library.
* The link:https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-openai/src/test/java/org/springframework/ai/openai/audio/transcription/OpenAiTranscriptionModelIT.java[OpenAiTranscriptionModelIT.java] test provides some general examples how to use the library.

View File

@@ -0,0 +1,54 @@
/*
* Copyright 2023 - 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.ai.autoconfigure.azure.openai;
import org.springframework.ai.azure.openai.AzureOpenAiAudioTranscriptionOptions;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
/**
* @author Piotr Olaszewski
*/
@ConfigurationProperties(AzureOpenAiAudioTranscriptionProperties.CONFIG_PREFIX)
public class AzureOpenAiAudioTranscriptionProperties {
public static final String CONFIG_PREFIX = "spring.ai.azure.openai.audio.transcription";
/**
* Enable AzureOpenAI audio transcription model.
*/
private boolean enabled = true;
@NestedConfigurationProperty
private AzureOpenAiAudioTranscriptionOptions options = AzureOpenAiAudioTranscriptionOptions.builder().build();
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public AzureOpenAiAudioTranscriptionOptions getOptions() {
return options;
}
public void setOptions(AzureOpenAiAudioTranscriptionOptions options) {
this.options = options;
}
}

View File

@@ -15,14 +15,18 @@
*/
package org.springframework.ai.autoconfigure.azure.openai;
import java.util.List;
import com.azure.ai.openai.OpenAIClient;
import com.azure.ai.openai.OpenAIClientBuilder;
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.credential.KeyCredential;
import com.azure.core.credential.TokenCredential;
import com.azure.core.util.ClientOptions;
import org.springframework.ai.azure.openai.AzureOpenAiAudioTranscriptionModel;
import org.springframework.ai.azure.openai.AzureOpenAiChatModel;
import org.springframework.ai.azure.openai.AzureOpenAiEmbeddingModel;
import org.springframework.ai.azure.openai.AzureOpenAiImageModel;
import org.springframework.ai.model.function.FunctionCallback;
import org.springframework.ai.model.function.FunctionCallbackContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
@@ -35,17 +39,16 @@ import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import com.azure.ai.openai.OpenAIClient;
import com.azure.ai.openai.OpenAIClientBuilder;
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.credential.KeyCredential;
import com.azure.core.credential.TokenCredential;
import com.azure.core.util.ClientOptions;
import java.util.List;
/**
* @author Piotr Olaszewski
*/
@AutoConfiguration
@ConditionalOnClass({ OpenAIClientBuilder.class, AzureOpenAiChatModel.class })
@EnableConfigurationProperties({ AzureOpenAiChatProperties.class, AzureOpenAiEmbeddingProperties.class,
AzureOpenAiConnectionProperties.class, AzureOpenAiImageOptionsProperties.class })
AzureOpenAiConnectionProperties.class, AzureOpenAiImageOptionsProperties.class,
AzureOpenAiAudioTranscriptionProperties.class })
public class AzureOpenAiAutoConfiguration {
private final static String APPLICATION_ID = "spring-ai";
@@ -102,10 +105,7 @@ public class AzureOpenAiAutoConfiguration {
chatProperties.getOptions().getFunctionCallbacks().addAll(toolFunctionCallbacks);
}
AzureOpenAiChatModel azureOpenAiChatModel = new AzureOpenAiChatModel(openAIClient, chatProperties.getOptions(),
functionCallbackContext);
return azureOpenAiChatModel;
return new AzureOpenAiChatModel(openAIClient, chatProperties.getOptions(), functionCallbackContext);
}
@Bean
@@ -134,4 +134,12 @@ public class AzureOpenAiAutoConfiguration {
return new AzureOpenAiImageModel(openAIClient, imageProperties.getOptions());
}
@Bean
@ConditionalOnProperty(prefix = AzureOpenAiAudioTranscriptionProperties.CONFIG_PREFIX, name = "enabled",
havingValue = "true", matchIfMissing = true)
public AzureOpenAiAudioTranscriptionModel azureOpenAiAudioTranscriptionModel(OpenAIClient openAIClient,
AzureOpenAiAudioTranscriptionProperties audioProperties) {
return new AzureOpenAiAudioTranscriptionModel(openAIClient, audioProperties.getOptions());
}
}

View File

@@ -15,32 +15,35 @@
*/
package org.springframework.ai.autoconfigure.azure;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.ai.autoconfigure.azure.openai.AzureOpenAiAutoConfiguration;
import org.springframework.ai.azure.openai.AzureOpenAiAudioTranscriptionModel;
import org.springframework.ai.azure.openai.AzureOpenAiChatModel;
import org.springframework.ai.azure.openai.AzureOpenAiEmbeddingModel;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.model.Generation;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.ai.embedding.EmbeddingResponse;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import reactor.core.publisher.Flux;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.ai.azure.openai.AzureOpenAiChatModel;
import org.springframework.ai.chat.messages.AssistantMessage;
import reactor.core.publisher.Flux;
import org.springframework.ai.autoconfigure.azure.openai.AzureOpenAiAutoConfiguration;
import org.springframework.ai.azure.openai.AzureOpenAiEmbeddingModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.model.Generation;
import org.springframework.ai.embedding.EmbeddingResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Christian Tzolov
* @author Piotr Olaszewski
* @since 0.8.0
*/
@EnabledIfEnvironmentVariable(named = "AZURE_OPENAI_API_KEY", matches = ".+")
@@ -60,7 +63,8 @@ public class AzureOpenAiAutoConfigurationIT {
"spring.ai.azure.openai.chat.options.temperature=0.8",
"spring.ai.azure.openai.chat.options.maxTokens=123",
"spring.ai.azure.openai.embedding.options.deployment-name=" + EMBEDDING_MODEL_NAME
"spring.ai.azure.openai.embedding.options.deployment-name=" + EMBEDDING_MODEL_NAME,
"spring.ai.azure.openai.audio.transcription.options.deployment-name=" + System.getenv("AZURE_OPENAI_TRANSCRIPTION_DEPLOYMENT_NAME")
// @formatter:on
).withConfiguration(AutoConfigurations.of(AzureOpenAiAutoConfiguration.class));
@@ -122,6 +126,19 @@ public class AzureOpenAiAutoConfigurationIT {
});
}
@Test
@EnabledIfEnvironmentVariable(named = "AZURE_OPENAI_TRANSCRIPTION_DEPLOYMENT_NAME", matches = ".+")
void transcribe() {
contextRunner.run(context -> {
AzureOpenAiAudioTranscriptionModel transcriptionModel = context
.getBean(AzureOpenAiAudioTranscriptionModel.class);
Resource audioFile = new ClassPathResource("/speech/jfk.flac");
String response = transcriptionModel.call(audioFile);
assertThat(response).isEqualTo(
"And so my fellow Americans, ask not what your country can do for you, ask what you can do for your country.");
});
}
@Test
public void chatActivation() {
@@ -160,4 +177,23 @@ public class AzureOpenAiAutoConfigurationIT {
});
}
@Test
public void audioTranscriptionActivation() {
// Disable the transcription auto-configuration.
contextRunner.withPropertyValues("spring.ai.azure.openai.audio.transcription.enabled=false").run(context -> {
assertThat(context.getBeansOfType(AzureOpenAiAudioTranscriptionModel.class)).isEmpty();
});
// The transcription auto-configuration is enabled by default.
contextRunner.run(context -> {
assertThat(context.getBeansOfType(AzureOpenAiAudioTranscriptionModel.class)).isNotEmpty();
});
// Explicitly enable the transcription auto-configuration.
contextRunner.withPropertyValues("spring.ai.azure.openai.audio.transcription.enabled=true").run(context -> {
assertThat(context.getBeansOfType(AzureOpenAiAudioTranscriptionModel.class)).isNotEmpty();
});
}
}