|
| 1 | +package org.springframework.ai.openai;/* |
| 2 | + * Copyright 2023-2023 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 | +import org.slf4j.Logger; |
| 18 | +import org.slf4j.LoggerFactory; |
| 19 | +import org.springframework.ai.chat.ChatOptions; |
| 20 | +import org.springframework.ai.chat.metadata.RateLimit; |
| 21 | +import org.springframework.ai.model.ModelOptionsUtils; |
| 22 | +import org.springframework.ai.openai.api.OpenAiApi; |
| 23 | +import org.springframework.ai.openai.api.OpenAiApi.OpenAiApiException; |
| 24 | +import org.springframework.ai.openai.metadata.OpenAiTranscriptionResponseMetadata; |
| 25 | +import org.springframework.ai.openai.metadata.support.OpenAiResponseHeaderExtractor; |
| 26 | +import org.springframework.ai.transcription.*; |
| 27 | +import org.springframework.core.io.Resource; |
| 28 | +import org.springframework.http.ResponseEntity; |
| 29 | +import org.springframework.retry.support.RetryTemplate; |
| 30 | +import org.springframework.util.Assert; |
| 31 | +import org.springframework.util.LinkedMultiValueMap; |
| 32 | +import org.springframework.util.MultiValueMap; |
| 33 | + |
| 34 | +import java.time.Duration; |
| 35 | +import java.util.List; |
| 36 | + |
| 37 | +/** |
| 38 | + * {@link TranscriptionClient} implementation for {@literal OpenAI} backed by |
| 39 | + * {@link OpenAiApi}. |
| 40 | + * |
| 41 | + * @author Michael Lavelle |
| 42 | + * @see TranscriptionClient |
| 43 | + * @see OpenAiApi |
| 44 | + */ |
| 45 | +public class OpenAiTranscriptionClient implements TranscriptionClient { |
| 46 | + |
| 47 | + private final Logger logger = LoggerFactory.getLogger(getClass()); |
| 48 | + |
| 49 | + private OpenAiTranscriptionOptions defaultOptions = OpenAiTranscriptionOptions.builder() |
| 50 | + .withModel("whisper-1") |
| 51 | + .withTemperature(0.7f) |
| 52 | + .build(); |
| 53 | + |
| 54 | + public final RetryTemplate retryTemplate = RetryTemplate.builder() |
| 55 | + .maxAttempts(10) |
| 56 | + .retryOn(OpenAiApiException.class) |
| 57 | + .exponentialBackoff(Duration.ofMillis(2000), 5, Duration.ofMillis(3 * 60000)) |
| 58 | + .build(); |
| 59 | + |
| 60 | + private final OpenAiApi openAiApi; |
| 61 | + |
| 62 | + public OpenAiTranscriptionClient(OpenAiApi openAiApi) { |
| 63 | + Assert.notNull(openAiApi, "OpenAiApi must not be null"); |
| 64 | + this.openAiApi = openAiApi; |
| 65 | + } |
| 66 | + |
| 67 | + public OpenAiTranscriptionClient withDefaultOptions(OpenAiTranscriptionOptions options) { |
| 68 | + this.defaultOptions = options; |
| 69 | + return this; |
| 70 | + } |
| 71 | + |
| 72 | + @Override |
| 73 | + public TranscriptionResponse call(TranscriptionRequest request) { |
| 74 | + |
| 75 | + return this.retryTemplate.execute(ctx -> { |
| 76 | + Resource audioResource = request.getInstructions(); |
| 77 | + |
| 78 | + MultiValueMap<String, Object> requestBody = createRequestBody(request); |
| 79 | + |
| 80 | + boolean jsonResponse = !requestBody.containsKey("response_format") |
| 81 | + || requestBody.get("response_format").contains("json"); |
| 82 | + |
| 83 | + if (jsonResponse) { |
| 84 | + |
| 85 | + ResponseEntity<OpenAiApi.Transcription> transcriptionEntity = this.openAiApi |
| 86 | + .transcriptionEntityJson(requestBody); |
| 87 | + |
| 88 | + var transcription = transcriptionEntity.getBody(); |
| 89 | + |
| 90 | + if (transcription == null) { |
| 91 | + logger.warn("No transcription returned for request: {}", audioResource); |
| 92 | + return new TranscriptionResponse(null); |
| 93 | + } |
| 94 | + |
| 95 | + Transcript transcript = new Transcript(transcription.text()); |
| 96 | + |
| 97 | + RateLimit rateLimits = OpenAiResponseHeaderExtractor.extractAiResponseHeaders(transcriptionEntity); |
| 98 | + |
| 99 | + return new TranscriptionResponse(transcript, |
| 100 | + OpenAiTranscriptionResponseMetadata.from(transcriptionEntity.getBody()) |
| 101 | + .withRateLimit(rateLimits)); |
| 102 | + |
| 103 | + } |
| 104 | + else { |
| 105 | + ResponseEntity<String> transcriptionEntity = this.openAiApi.transcriptionEntityText(requestBody); |
| 106 | + |
| 107 | + var transcription = transcriptionEntity.getBody(); |
| 108 | + |
| 109 | + if (transcription == null) { |
| 110 | + logger.warn("No transcription returned for request: {}", audioResource); |
| 111 | + return new TranscriptionResponse(null); |
| 112 | + } |
| 113 | + |
| 114 | + Transcript transcript = new Transcript(transcription); |
| 115 | + |
| 116 | + RateLimit rateLimits = OpenAiResponseHeaderExtractor.extractAiResponseHeaders(transcriptionEntity); |
| 117 | + |
| 118 | + return new TranscriptionResponse(transcript, |
| 119 | + OpenAiTranscriptionResponseMetadata.from(transcriptionEntity.getBody()) |
| 120 | + .withRateLimit(rateLimits)); |
| 121 | + |
| 122 | + } |
| 123 | + |
| 124 | + }); |
| 125 | + } |
| 126 | + |
| 127 | + private MultiValueMap<String, Object> createRequestBody(TranscriptionRequest transcriptionRequest) { |
| 128 | + |
| 129 | + OpenAiApi.TranscriptionRequest request = new OpenAiApi.TranscriptionRequest(); |
| 130 | + |
| 131 | + if (this.defaultOptions != null) { |
| 132 | + request = ModelOptionsUtils.merge(request, this.defaultOptions, OpenAiApi.TranscriptionRequest.class); |
| 133 | + } |
| 134 | + |
| 135 | + if (transcriptionRequest.getOptions() != null) { |
| 136 | + if (transcriptionRequest.getOptions() instanceof TranscriptionOptions runtimeOptions) { |
| 137 | + OpenAiTranscriptionOptions updatedRuntimeOptions = ModelOptionsUtils.copyToTarget(runtimeOptions, |
| 138 | + TranscriptionOptions.class, OpenAiTranscriptionOptions.class); |
| 139 | + request = ModelOptionsUtils.merge(updatedRuntimeOptions, request, OpenAiApi.TranscriptionRequest.class); |
| 140 | + } |
| 141 | + else { |
| 142 | + throw new IllegalArgumentException("Prompt options are not of type TranscriptionOptions: " |
| 143 | + + transcriptionRequest.getOptions().getClass().getSimpleName()); |
| 144 | + } |
| 145 | + } |
| 146 | + MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>(); |
| 147 | + if (request.responseFormat() != null) { |
| 148 | + requestBody.add("response_format", request.responseFormat().type()); |
| 149 | + } |
| 150 | + if (request.prompt() != null) { |
| 151 | + requestBody.add("prompt", request.prompt()); |
| 152 | + } |
| 153 | + if (request.temperature() != null) { |
| 154 | + requestBody.add("temperature", request.temperature()); |
| 155 | + } |
| 156 | + if (request.language() != null) { |
| 157 | + requestBody.add("language", request.language()); |
| 158 | + } |
| 159 | + if (request.model() != null) { |
| 160 | + requestBody.add("model", request.model()); |
| 161 | + } |
| 162 | + if (transcriptionRequest.getInstructions() != null) { |
| 163 | + requestBody.add("file", transcriptionRequest.getInstructions()); |
| 164 | + } |
| 165 | + return requestBody; |
| 166 | + } |
| 167 | + |
| 168 | +} |
0 commit comments