diff --git a/models/spring-ai-azure-openai/src/main/java/org/springframework/ai/azure/openai/AzureOpenAiAudioTranscriptionModel.java b/models/spring-ai-azure-openai/src/main/java/org/springframework/ai/azure/openai/AzureOpenAiAudioTranscriptionModel.java new file mode 100644 index 000000000..1d1e4afd9 --- /dev/null +++ b/models/spring-ai-azure-openai/src/main/java/org/springframework/ai/azure/openai/AzureOpenAiAudioTranscriptionModel.java @@ -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 { + + private static final List 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 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 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 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 = 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 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); + } + } + +} diff --git a/models/spring-ai-azure-openai/src/main/java/org/springframework/ai/azure/openai/AzureOpenAiAudioTranscriptionOptions.java b/models/spring-ai-azure-openai/src/main/java/org/springframework/ai/azure/openai/AzureOpenAiAudioTranscriptionOptions.java new file mode 100644 index 000000000..bd80aace9 --- /dev/null +++ b/models/spring-ai-azure-openai/src/main/java/org/springframework/ai/azure/openai/AzureOpenAiAudioTranscriptionOptions.java @@ -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; + + 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) { + 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 getGranularityType() { + return this.granularityType; + } + + public void setGranularityType(List 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 words, + @JsonProperty("segments") List 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 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; + } + + } + +} diff --git a/models/spring-ai-azure-openai/src/main/java/org/springframework/ai/azure/openai/AzureOpenAiChatModel.java b/models/spring-ai-azure-openai/src/main/java/org/springframework/ai/azure/openai/AzureOpenAiChatModel.java index d920b169e..d32e46877 100644 --- a/models/spring-ai-azure-openai/src/main/java/org/springframework/ai/azure/openai/AzureOpenAiChatModel.java +++ b/models/spring-ai-azure-openai/src/main/java/org/springframework/ai/azure/openai/AzureOpenAiChatModel.java @@ -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; diff --git a/models/spring-ai-azure-openai/src/main/java/org/springframework/ai/azure/openai/AzureOpenAiEmbeddingOptions.java b/models/spring-ai-azure-openai/src/main/java/org/springframework/ai/azure/openai/AzureOpenAiEmbeddingOptions.java index d928234f6..d0efd22cd 100644 --- a/models/spring-ai-azure-openai/src/main/java/org/springframework/ai/azure/openai/AzureOpenAiEmbeddingOptions.java +++ b/models/spring-ai-azure-openai/src/main/java/org/springframework/ai/azure/openai/AzureOpenAiEmbeddingOptions.java @@ -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; diff --git a/models/spring-ai-azure-openai/src/main/java/org/springframework/ai/azure/openai/metadata/AzureOpenAiAudioTranscriptionResponseMetadata.java b/models/spring-ai-azure-openai/src/main/java/org/springframework/ai/azure/openai/metadata/AzureOpenAiAudioTranscriptionResponseMetadata.java new file mode 100644 index 000000000..f64a805a1 --- /dev/null +++ b/models/spring-ai-azure-openai/src/main/java/org/springframework/ai/azure/openai/metadata/AzureOpenAiAudioTranscriptionResponseMetadata.java @@ -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()); + } + +} diff --git a/models/spring-ai-azure-openai/src/test/java/org/springframework/ai/azure/openai/AzureOpenAiAudioTranscriptionModelIT.java b/models/spring-ai-azure-openai/src/test/java/org/springframework/ai/azure/openai/AzureOpenAiAudioTranscriptionModelIT.java new file mode 100644 index 000000000..a8a7d44ae --- /dev/null +++ b/models/spring-ai-azure-openai/src/test/java/org/springframework/ai/azure/openai/AzureOpenAiAudioTranscriptionModelIT.java @@ -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()); + } + + } + +} diff --git a/models/spring-ai-azure-openai/src/test/java/org/springframework/ai/azure/openai/AzureOpenAiChatModelIT.java b/models/spring-ai-azure-openai/src/test/java/org/springframework/ai/azure/openai/AzureOpenAiChatModelIT.java index 38fe7f36e..cc0cba054 100644 --- a/models/spring-ai-azure-openai/src/test/java/org/springframework/ai/azure/openai/AzureOpenAiChatModelIT.java +++ b/models/spring-ai-azure-openai/src/test/java/org/springframework/ai/azure/openai/AzureOpenAiChatModelIT.java @@ -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()); } diff --git a/models/spring-ai-azure-openai/src/test/java/org/springframework/ai/azure/openai/AzureOpenAiEmbeddingModelIT.java b/models/spring-ai-azure-openai/src/test/java/org/springframework/ai/azure/openai/AzureOpenAiEmbeddingModelIT.java index 7c1710e06..0ee62a147 100644 --- a/models/spring-ai-azure-openai/src/test/java/org/springframework/ai/azure/openai/AzureOpenAiEmbeddingModelIT.java +++ b/models/spring-ai-azure-openai/src/test/java/org/springframework/ai/azure/openai/AzureOpenAiEmbeddingModelIT.java @@ -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()); } } diff --git a/models/spring-ai-azure-openai/src/test/java/org/springframework/ai/azure/openai/metadata/AzureOpenAiChatModelMetadataTests.java b/models/spring-ai-azure-openai/src/test/java/org/springframework/ai/azure/openai/metadata/AzureOpenAiChatModelMetadataTests.java index 9f3588419..63d231205 100644 --- a/models/spring-ai-azure-openai/src/test/java/org/springframework/ai/azure/openai/metadata/AzureOpenAiChatModelMetadataTests.java +++ b/models/spring-ai-azure-openai/src/test/java/org/springframework/ai/azure/openai/metadata/AzureOpenAiChatModelMetadataTests.java @@ -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, diff --git a/models/spring-ai-azure-openai/src/test/resources/speech/jfk.flac b/models/spring-ai-azure-openai/src/test/resources/speech/jfk.flac new file mode 100644 index 000000000..e44b7c138 Binary files /dev/null and b/models/spring-ai-azure-openai/src/test/resources/speech/jfk.flac differ diff --git a/models/spring-ai-openai/src/main/java/org/springframework/ai/openai/OpenAiAudioTranscriptionModel.java b/models/spring-ai-openai/src/main/java/org/springframework/ai/openai/OpenAiAudioTranscriptionModel.java index ed5d9709d..b9b4b19c1 100644 --- a/models/spring-ai-openai/src/main/java/org/springframework/ai/openai/OpenAiAudioTranscriptionModel.java +++ b/models/spring-ai-openai/src/main/java/org/springframework/ai/openai/OpenAiAudioTranscriptionModel.java @@ -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 { - OpenAiAudioTranscriptionMetadata transcriptionMetadata = transcript.getMetadata(); + AudioTranscriptionMetadata transcriptionMetadata = transcript.getMetadata(); assertThat(transcriptionMetadata).isNotNull(); }); } diff --git a/models/spring-ai-openai/src/test/java/org/springframework/ai/openai/audio/transcription/TranscriptionModelTests.java b/models/spring-ai-openai/src/test/java/org/springframework/ai/openai/audio/transcription/TranscriptionModelTests.java index 96431af0e..4e7010035 100644 --- a/models/spring-ai-openai/src/test/java/org/springframework/ai/openai/audio/transcription/TranscriptionModelTests.java +++ b/models/spring-ai-openai/src/test/java/org/springframework/ai/openai/audio/transcription/TranscriptionModelTests.java @@ -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; diff --git a/models/spring-ai-openai/src/test/java/org/springframework/ai/openai/chat/OpenAiRetryTests.java b/models/spring-ai-openai/src/test/java/org/springframework/ai/openai/chat/OpenAiRetryTests.java index ae17045e9..fa998f44e 100644 --- a/models/spring-ai-openai/src/test/java/org/springframework/ai/openai/chat/OpenAiRetryTests.java +++ b/models/spring-ai-openai/src/test/java/org/springframework/ai/openai/chat/OpenAiRetryTests.java @@ -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; diff --git a/pom.xml b/pom.xml index 7ea955a1d..d7f9e6b4c 100644 --- a/pom.xml +++ b/pom.xml @@ -150,7 +150,7 @@ 1.0.0-beta.10 1.1.0 4.31.1 - + 2.26.7 2.26.7 @@ -186,7 +186,6 @@ 1.9.1 0.5.0 2.10.1 - 5.3.1 diff --git a/models/spring-ai-openai/src/main/java/org/springframework/ai/openai/audio/transcription/AudioTranscription.java b/spring-ai-core/src/main/java/org/springframework/ai/audio/transcription/AudioTranscription.java similarity index 78% rename from models/spring-ai-openai/src/main/java/org/springframework/ai/openai/audio/transcription/AudioTranscription.java rename to spring-ai-core/src/main/java/org/springframework/ai/audio/transcription/AudioTranscription.java index d7a02b887..c6de0ed68 100644 --- a/models/spring-ai-openai/src/main/java/org/springframework/ai/openai/audio/transcription/AudioTranscription.java +++ b/spring-ai-core/src/main/java/org/springframework/ai/audio/transcription/AudioTranscription.java @@ -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 { - 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 { } @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; } diff --git a/models/spring-ai-openai/src/main/java/org/springframework/ai/openai/metadata/audio/OpenAiAudioTranscriptionMetadata.java b/spring-ai-core/src/main/java/org/springframework/ai/audio/transcription/AudioTranscriptionMetadata.java similarity index 58% rename from models/spring-ai-openai/src/main/java/org/springframework/ai/openai/metadata/audio/OpenAiAudioTranscriptionMetadata.java rename to spring-ai-core/src/main/java/org/springframework/ai/audio/transcription/AudioTranscriptionMetadata.java index c9868069f..bd064a659 100644 --- a/models/spring-ai-openai/src/main/java/org/springframework/ai/openai/metadata/audio/OpenAiAudioTranscriptionMetadata.java +++ b/spring-ai-core/src/main/java/org/springframework/ai/audio/transcription/AudioTranscriptionMetadata.java @@ -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() { }; } diff --git a/spring-ai-core/src/main/java/org/springframework/ai/audio/transcription/AudioTranscriptionOptions.java b/spring-ai-core/src/main/java/org/springframework/ai/audio/transcription/AudioTranscriptionOptions.java new file mode 100644 index 000000000..95bd877e7 --- /dev/null +++ b/spring-ai-core/src/main/java/org/springframework/ai/audio/transcription/AudioTranscriptionOptions.java @@ -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(); + +} diff --git a/models/spring-ai-openai/src/main/java/org/springframework/ai/openai/audio/transcription/AudioTranscriptionPrompt.java b/spring-ai-core/src/main/java/org/springframework/ai/audio/transcription/AudioTranscriptionPrompt.java similarity index 85% rename from models/spring-ai-openai/src/main/java/org/springframework/ai/openai/audio/transcription/AudioTranscriptionPrompt.java rename to spring-ai-core/src/main/java/org/springframework/ai/audio/transcription/AudioTranscriptionPrompt.java index aafb9915d..6f5208240 100644 --- a/models/spring-ai-openai/src/main/java/org/springframework/ai/openai/audio/transcription/AudioTranscriptionPrompt.java +++ b/spring-ai-core/src/main/java/org/springframework/ai/audio/transcription/AudioTranscriptionPrompt.java @@ -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 { - 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 { * @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 { } @Override - public ModelOptions getOptions() { + public AudioTranscriptionOptions getOptions() { return modelOptions; } diff --git a/models/spring-ai-openai/src/main/java/org/springframework/ai/openai/audio/transcription/AudioTranscriptionResponse.java b/spring-ai-core/src/main/java/org/springframework/ai/audio/transcription/AudioTranscriptionResponse.java similarity index 71% rename from models/spring-ai-openai/src/main/java/org/springframework/ai/openai/audio/transcription/AudioTranscriptionResponse.java rename to spring-ai-core/src/main/java/org/springframework/ai/audio/transcription/AudioTranscriptionResponse.java index ff4f07ed7..e1a652355 100644 --- a/models/spring-ai-openai/src/main/java/org/springframework/ai/openai/audio/transcription/AudioTranscriptionResponse.java +++ b/spring-ai-core/src/main/java/org/springframework/ai/audio/transcription/AudioTranscriptionResponse.java @@ -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 { - 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 getResults() { - return Arrays.asList(transcript); + return List.of(transcript); } @Override - public OpenAiAudioTranscriptionResponseMetadata getMetadata() { + public AudioTranscriptionResponseMetadata getMetadata() { return transcriptionResponseMetadata; } diff --git a/spring-ai-core/src/main/java/org/springframework/ai/audio/transcription/AudioTranscriptionResponseMetadata.java b/spring-ai-core/src/main/java/org/springframework/ai/audio/transcription/AudioTranscriptionResponseMetadata.java new file mode 100644 index 000000000..66c3fdf89 --- /dev/null +++ b/spring-ai-core/src/main/java/org/springframework/ai/audio/transcription/AudioTranscriptionResponseMetadata.java @@ -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 { + +} diff --git a/spring-ai-docs/src/main/antora/modules/ROOT/nav.adoc b/spring-ai-docs/src/main/antora/modules/ROOT/nav.adoc index 057bb62b3..644615f74 100644 --- a/spring-ai-docs/src/main/antora/modules/ROOT/nav.adoc +++ b/spring-ai-docs/src/main/antora/modules/ROOT/nav.adoc @@ -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] diff --git a/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/audio/transcriptions/azure-openai-transcriptions.adoc b/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/audio/transcriptions/azure-openai-transcriptions.adoc new file mode 100644 index 000000000..a0cc7d4d1 --- /dev/null +++ b/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/audio/transcriptions/azure-openai-transcriptions.adoc @@ -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] +---- + + org.springframework.ai + spring-ai-azure-openai-spring-boot-starter + +---- + +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] +---- + + org.springframework.ai + spring-ai-azure-openai + +---- + +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); +---- diff --git a/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/audio/transcriptions/openai-transcriptions.adoc b/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/audio/transcriptions/openai-transcriptions.adoc index 5f352f4f9..822426c55 100644 --- a/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/audio/transcriptions/openai-transcriptions.adoc +++ b/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/audio/transcriptions/openai-transcriptions.adoc @@ -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] ---- org.springframework.ai @@ -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] ---- org.springframework.ai @@ -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. \ No newline at end of file + +* 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. diff --git a/spring-ai-spring-boot-autoconfigure/src/main/java/org/springframework/ai/autoconfigure/azure/openai/AzureOpenAiAudioTranscriptionProperties.java b/spring-ai-spring-boot-autoconfigure/src/main/java/org/springframework/ai/autoconfigure/azure/openai/AzureOpenAiAudioTranscriptionProperties.java new file mode 100644 index 000000000..c223713e8 --- /dev/null +++ b/spring-ai-spring-boot-autoconfigure/src/main/java/org/springframework/ai/autoconfigure/azure/openai/AzureOpenAiAudioTranscriptionProperties.java @@ -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; + } + +} diff --git a/spring-ai-spring-boot-autoconfigure/src/main/java/org/springframework/ai/autoconfigure/azure/openai/AzureOpenAiAutoConfiguration.java b/spring-ai-spring-boot-autoconfigure/src/main/java/org/springframework/ai/autoconfigure/azure/openai/AzureOpenAiAutoConfiguration.java index 476cca5f6..e651115ed 100644 --- a/spring-ai-spring-boot-autoconfigure/src/main/java/org/springframework/ai/autoconfigure/azure/openai/AzureOpenAiAutoConfiguration.java +++ b/spring-ai-spring-boot-autoconfigure/src/main/java/org/springframework/ai/autoconfigure/azure/openai/AzureOpenAiAutoConfiguration.java @@ -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()); + } + } diff --git a/spring-ai-spring-boot-autoconfigure/src/test/java/org/springframework/ai/autoconfigure/azure/AzureOpenAiAutoConfigurationIT.java b/spring-ai-spring-boot-autoconfigure/src/test/java/org/springframework/ai/autoconfigure/azure/AzureOpenAiAutoConfigurationIT.java index 2bc258997..857d85f52 100644 --- a/spring-ai-spring-boot-autoconfigure/src/test/java/org/springframework/ai/autoconfigure/azure/AzureOpenAiAutoConfigurationIT.java +++ b/spring-ai-spring-boot-autoconfigure/src/test/java/org/springframework/ai/autoconfigure/azure/AzureOpenAiAutoConfigurationIT.java @@ -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(); + }); + } + }