|
| 1 | +/* |
| 2 | + * Copyright 2023 - 2024 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package org.springframework.ai.openai; |
| 18 | + |
| 19 | +import org.apache.commons.lang3.StringUtils; |
| 20 | +import org.slf4j.Logger; |
| 21 | +import org.slf4j.LoggerFactory; |
| 22 | +import org.springframework.ai.chat.metadata.RateLimit; |
| 23 | +import org.springframework.ai.openai.api.OpenAiAudioApi; |
| 24 | +import org.springframework.ai.openai.api.OpenAiAudioApi.SpeechRequest.AudioResponseFormat; |
| 25 | +import org.springframework.ai.openai.api.common.OpenAiApiException; |
| 26 | +import org.springframework.ai.openai.audio.speech.*; |
| 27 | +import org.springframework.ai.openai.metadata.audio.OpenAiAudioSpeechResponseMetadata; |
| 28 | +import org.springframework.ai.openai.metadata.support.OpenAiResponseHeaderExtractor; |
| 29 | +import org.springframework.http.ResponseEntity; |
| 30 | +import org.springframework.retry.support.RetryTemplate; |
| 31 | +import org.springframework.util.Assert; |
| 32 | +import reactor.core.publisher.Flux; |
| 33 | + |
| 34 | +import java.time.Duration; |
| 35 | + |
| 36 | +/** |
| 37 | + * OpenAI audio speech client implementation for backed by {@link OpenAiAudioApi}. |
| 38 | + * |
| 39 | + * @author Ahmed Yousri |
| 40 | + * @see OpenAiAudioApi |
| 41 | + */ |
| 42 | +public class OpenAiAudioSpeechClient implements SpeechClient, StreamingSpeechClient { |
| 43 | + |
| 44 | + private final Logger logger = LoggerFactory.getLogger(getClass()); |
| 45 | + |
| 46 | + private final OpenAiAudioSpeechOptions defaultOptions; |
| 47 | + |
| 48 | + private static final Float SPEED = 1.0f; |
| 49 | + |
| 50 | + public final RetryTemplate retryTemplate = RetryTemplate.builder() |
| 51 | + .maxAttempts(10) |
| 52 | + .retryOn(OpenAiApiException.class) |
| 53 | + .exponentialBackoff(Duration.ofMillis(2000), 5, Duration.ofMillis(3 * 60000)) |
| 54 | + .build(); |
| 55 | + |
| 56 | + private final OpenAiAudioApi audioApi; |
| 57 | + |
| 58 | + public OpenAiAudioSpeechClient(OpenAiAudioApi audioApi) { |
| 59 | + this(audioApi, |
| 60 | + OpenAiAudioSpeechOptions.builder() |
| 61 | + .withModel(OpenAiAudioApi.TtsModel.TTS_1.getValue()) |
| 62 | + .withResponseFormat(AudioResponseFormat.MP3) |
| 63 | + .withVoice(OpenAiAudioApi.SpeechRequest.Voice.ALLOY) |
| 64 | + .withSpeed(SPEED) |
| 65 | + .build()); |
| 66 | + } |
| 67 | + |
| 68 | + public OpenAiAudioSpeechClient(OpenAiAudioApi audioApi, OpenAiAudioSpeechOptions options) { |
| 69 | + Assert.notNull(audioApi, "OpenAiAudioApi must not be null"); |
| 70 | + Assert.notNull(options, "OpenAiSpeechOptions must not be null"); |
| 71 | + this.audioApi = audioApi; |
| 72 | + this.defaultOptions = options; |
| 73 | + } |
| 74 | + |
| 75 | + @Override |
| 76 | + public byte[] call(String text) { |
| 77 | + SpeechPrompt speechRequest = new SpeechPrompt(text); |
| 78 | + return call(speechRequest).getResult().getOutput(); |
| 79 | + } |
| 80 | + |
| 81 | + @Override |
| 82 | + public SpeechResponse call(SpeechPrompt speechPrompt) { |
| 83 | + |
| 84 | + return this.retryTemplate.execute(ctx -> { |
| 85 | + |
| 86 | + OpenAiAudioApi.SpeechRequest speechRequest = createRequestBody(speechPrompt); |
| 87 | + |
| 88 | + ResponseEntity<byte[]> speechEntity = this.audioApi.createSpeech(speechRequest); |
| 89 | + var speech = speechEntity.getBody(); |
| 90 | + |
| 91 | + if (speech == null) { |
| 92 | + logger.warn("No speech response returned for speechRequest: {}", speechRequest); |
| 93 | + return new SpeechResponse(new Speech(new byte[0])); |
| 94 | + } |
| 95 | + |
| 96 | + RateLimit rateLimits = OpenAiResponseHeaderExtractor.extractAiResponseHeaders(speechEntity); |
| 97 | + |
| 98 | + return new SpeechResponse(new Speech(speech), new OpenAiAudioSpeechResponseMetadata(rateLimits)); |
| 99 | + |
| 100 | + }); |
| 101 | + } |
| 102 | + |
| 103 | + /** |
| 104 | + * Streams the audio response for the given speech prompt. |
| 105 | + * @param prompt The speech prompt containing the text and options for speech |
| 106 | + * synthesis. |
| 107 | + * @return A Flux of SpeechResponse objects containing the streamed audio and |
| 108 | + * metadata. |
| 109 | + */ |
| 110 | + |
| 111 | + @Override |
| 112 | + public Flux<SpeechResponse> stream(SpeechPrompt prompt) { |
| 113 | + return this.audioApi.stream(this.createRequestBody(prompt)) |
| 114 | + .map(entity -> new SpeechResponse(new Speech(entity.getBody()), new OpenAiAudioSpeechResponseMetadata( |
| 115 | + OpenAiResponseHeaderExtractor.extractAiResponseHeaders(entity)))); |
| 116 | + } |
| 117 | + |
| 118 | + private OpenAiAudioApi.SpeechRequest createRequestBody(SpeechPrompt request) { |
| 119 | + OpenAiAudioSpeechOptions options = this.defaultOptions; |
| 120 | + |
| 121 | + if (request.getOptions() != null) { |
| 122 | + if (request.getOptions() instanceof OpenAiAudioSpeechOptions runtimeOptions) { |
| 123 | + options = this.merge(options, runtimeOptions); |
| 124 | + } |
| 125 | + else { |
| 126 | + throw new IllegalArgumentException("Prompt options are not of type SpeechOptions: " |
| 127 | + + request.getOptions().getClass().getSimpleName()); |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + String input = StringUtils.isNotBlank(options.getInput()) ? options.getInput() |
| 132 | + : request.getInstructions().get(0).getText(); |
| 133 | + |
| 134 | + OpenAiAudioApi.SpeechRequest.Builder requestBuilder = OpenAiAudioApi.SpeechRequest.builder() |
| 135 | + .withModel(options.getModel()) |
| 136 | + .withInput(input) |
| 137 | + .withVoice(options.getVoice()) |
| 138 | + .withResponseFormat(options.getResponseFormat()) |
| 139 | + .withSpeed(options.getSpeed()); |
| 140 | + |
| 141 | + return requestBuilder.build(); |
| 142 | + } |
| 143 | + |
| 144 | + private OpenAiAudioSpeechOptions merge(OpenAiAudioSpeechOptions source, OpenAiAudioSpeechOptions target) { |
| 145 | + OpenAiAudioSpeechOptions.Builder mergedBuilder = OpenAiAudioSpeechOptions.builder(); |
| 146 | + |
| 147 | + mergedBuilder.withModel(source.getModel() != null ? source.getModel() : target.getModel()); |
| 148 | + mergedBuilder.withInput(source.getInput() != null ? source.getInput() : target.getInput()); |
| 149 | + mergedBuilder.withVoice(source.getVoice() != null ? source.getVoice() : target.getVoice()); |
| 150 | + mergedBuilder.withResponseFormat( |
| 151 | + source.getResponseFormat() != null ? source.getResponseFormat() : target.getResponseFormat()); |
| 152 | + mergedBuilder.withSpeed(source.getSpeed() != null ? source.getSpeed() : target.getSpeed()); |
| 153 | + |
| 154 | + return mergedBuilder.build(); |
| 155 | + } |
| 156 | + |
| 157 | +} |
0 commit comments