openai/openai-dotnet

Public

mirrored from https://github.com/openai/openai-dotnetAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
copilot/modify-responsesclient-default-model

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/Custom/Audio/AudioClient.cs

469lines · modecode

1using Microsoft.TypeSpec.Generator.Customizations;
2using System;
3using System.ClientModel;
4using System.ClientModel.Primitives;
5using System.Diagnostics.CodeAnalysis;
6using System.IO;
7using System.Threading;
8using System.Threading.Tasks;
9
10namespace OpenAI.Audio;
11
12// CUSTOM:
13// - Renamed.
14// - Suppressed constructor that takes endpoint parameter; endpoint is now a property in the options class.
15// - Suppressed methods that only take the options parameter.
16/// <summary> The service client for OpenAI audio operations. </summary>
17[CodeGenType("Audio")]
18[CodeGenSuppress("AudioClient", typeof(ClientPipeline), typeof(Uri))]
19[CodeGenSuppress("GenerateSpeechAsync", typeof(SpeechGenerationOptions), typeof(CancellationToken))]
20[CodeGenSuppress("GenerateSpeech", typeof(SpeechGenerationOptions), typeof(CancellationToken))]
21public partial class AudioClient
22{
23 private readonly string _model;
24
25 // CUSTOM: Added as a convenience.
26 /// <summary> Initializes a new instance of <see cref="AudioClient"/>. </summary>
27 /// <param name="model"> The name of the model to use in requests sent to the service. To learn more about the available models, see <see href="https://platform.openai.com/docs/models"/>. </param>
28 /// <param name="apiKey"> The API key to authenticate with the service. </param>
29 /// <exception cref="ArgumentNullException"> <paramref name="model"/> or <paramref name="apiKey"/> is null. </exception>
30 /// <exception cref="ArgumentException"> <paramref name="model"/> is an empty string, and was expected to be non-empty. </exception>
31 public AudioClient(string model, string apiKey) : this(model, new ApiKeyCredential(apiKey), new OpenAIClientOptions())
32 {
33 }
34
35 // CUSTOM:
36 // - Added `model` parameter.
37 // - Used a custom pipeline.
38 // - Demoted the endpoint parameter to be a property in the options class.
39 /// <summary> Initializes a new instance of <see cref="AudioClient"/>. </summary>
40 /// <param name="model"> The name of the model to use in requests sent to the service. To learn more about the available models, see <see href="https://platform.openai.com/docs/models"/>. </param>
41 /// <param name="credential"> The <see cref="ApiKeyCredential"/> to authenticate with the service. </param>
42 /// <exception cref="ArgumentNullException"> <paramref name="model"/> or <paramref name="credential"/> is null. </exception>
43 /// <exception cref="ArgumentException"> <paramref name="model"/> is an empty string, and was expected to be non-empty. </exception>
44 public AudioClient(string model, ApiKeyCredential credential) : this(model, credential, new OpenAIClientOptions())
45 {
46 }
47
48 // CUSTOM:
49 // - Added `model` parameter.
50 // - Used a custom pipeline.
51 // - Demoted the endpoint parameter to be a property in the options class.
52 /// <summary> Initializes a new instance of <see cref="AudioClient"/>. </summary>
53 /// <param name="model"> The name of the model to use in requests sent to the service. To learn more about the available models, see <see href="https://platform.openai.com/docs/models"/>. </param>
54 /// <param name="credential"> The <see cref="ApiKeyCredential"/> to authenticate with the service. </param>
55 /// <param name="options"> The options to configure the client. </param>
56 /// <exception cref="ArgumentNullException"> <paramref name="model"/> or <paramref name="credential"/> is null. </exception>
57 /// <exception cref="ArgumentException"> <paramref name="model"/> is an empty string, and was expected to be non-empty. </exception>
58 public AudioClient(string model, ApiKeyCredential credential, OpenAIClientOptions options) : this(model, OpenAIClient.CreateApiKeyAuthenticationPolicy(credential), options)
59 {
60 }
61
62 // CUSTOM: Added as a convenience.
63 /// <summary> Initializes a new instance of <see cref="AudioClient"/>. </summary>
64 /// <param name="model"> The name of the model to use in requests sent to the service. To learn more about the available models, see <see href="https://platform.openai.com/docs/models"/>. </param>
65 /// <param name="authenticationPolicy"> The authentication policy used to authenticate with the service. </param>
66 /// <exception cref="ArgumentNullException"> <paramref name="model"/> or <paramref name="authenticationPolicy"/> is null. </exception>
67 /// <exception cref="ArgumentException"> <paramref name="model"/> is an empty string, and was expected to be non-empty. </exception>
68 [Experimental("OPENAI001")]
69 public AudioClient(string model, AuthenticationPolicy authenticationPolicy) : this(model, authenticationPolicy, new OpenAIClientOptions())
70 {
71 }
72
73 // CUSTOM: Added as a convenience.
74 /// <summary> Initializes a new instance of <see cref="AudioClient"/>. </summary>
75 /// <param name="model"> The name of the model to use in requests sent to the service. To learn more about the available models, see <see href="https://platform.openai.com/docs/models"/>. </param>
76 /// <param name="authenticationPolicy"> The authentication policy used to authenticate with the service. </param>
77 /// <param name="options"> The options to configure the client. </param>
78 /// <exception cref="ArgumentNullException"> <paramref name="model"/> or <paramref name="authenticationPolicy"/> is null. </exception>
79 /// <exception cref="ArgumentException"> <paramref name="model"/> is an empty string, and was expected to be non-empty. </exception>
80 [Experimental("OPENAI001")]
81 public AudioClient(string model, AuthenticationPolicy authenticationPolicy, OpenAIClientOptions options)
82 {
83 Argument.AssertNotNullOrEmpty(model, nameof(model));
84 Argument.AssertNotNull(authenticationPolicy, nameof(authenticationPolicy));
85 options ??= new OpenAIClientOptions();
86
87 _model = model;
88 Pipeline = OpenAIClient.CreatePipeline(authenticationPolicy, options);
89 _endpoint = OpenAIClient.GetEndpoint(options);
90 }
91
92 // CUSTOM:
93 // - Added `model` parameter.
94 // - Used a custom pipeline.
95 // - Demoted the endpoint parameter to be a property in the options class.
96 // - Made protected.
97 /// <summary> Initializes a new instance of <see cref="AudioClient"/>. </summary>
98 /// <param name="pipeline"> The HTTP pipeline to send and receive REST requests and responses. </param>
99 /// <param name="model"> The name of the model to use in requests sent to the service. To learn more about the available models, see <see href="https://platform.openai.com/docs/models"/>. </param>
100 /// <param name="options"> The options to configure the client. </param>
101 /// <exception cref="ArgumentNullException"> <paramref name="pipeline"/> or <paramref name="model"/> is null. </exception>
102 /// <exception cref="ArgumentException"> <paramref name="model"/> is an empty string, and was expected to be non-empty. </exception>
103 protected internal AudioClient(ClientPipeline pipeline, string model, OpenAIClientOptions options)
104 {
105 Argument.AssertNotNull(pipeline, nameof(pipeline));
106 Argument.AssertNotNullOrEmpty(model, nameof(model));
107 options ??= new OpenAIClientOptions();
108
109 _model = model;
110 Pipeline = pipeline;
111 _endpoint = OpenAIClient.GetEndpoint(options);
112 }
113
114 /// <summary>
115 /// Gets the name of the model used in requests sent to the service.
116 /// </summary>
117 [Experimental("OPENAI001")]
118 public string Model => _model;
119
120 /// <summary>
121 /// Gets the endpoint URI for the service.
122 /// </summary>
123 [Experimental("OPENAI001")]
124 public Uri Endpoint => _endpoint;
125
126 #region GenerateSpeech
127
128 /// <summary> Generates a life-like, spoken audio recording of the input text. </summary>
129 /// <remarks>
130 /// The default format of the generated audio is <see cref="GeneratedSpeechFormat.Mp3"/> unless otherwise specified
131 /// via <see cref="SpeechGenerationOptions.ResponseFormat"/>.
132 /// </remarks>
133 /// <param name="text"> The text to generate audio for. </param>
134 /// <param name="voice"> The voice to use in the generated audio. </param>
135 /// <param name="options"> The options to configure the audio generation. </param>
136 /// <param name="cancellationToken"> A token that can be used to cancel this method call. </param>
137 /// <exception cref="ArgumentNullException"> <paramref name="text"/> is null. </exception>
138 /// <returns> The generated audio in the specified output format. </returns>
139 public virtual async Task<ClientResult<BinaryData>> GenerateSpeechAsync(string text, GeneratedSpeechVoice voice, SpeechGenerationOptions options = null, CancellationToken cancellationToken = default)
140 {
141 Argument.AssertNotNull(text, nameof(text));
142
143 options ??= new();
144 CreateSpeechGenerationOptions(text, voice, ref options);
145
146 using BinaryContent content = options.ToBinaryContent();
147 ClientResult result = await GenerateSpeechAsync(content, cancellationToken.ToRequestOptions()).ConfigureAwait(false);
148 return ClientResult.FromValue(result.GetRawResponse().Content, result.GetRawResponse());
149 }
150
151 /// <summary> Generates a life-like, spoken audio recording of the input text. </summary>
152 /// <remarks>
153 /// The default format of the generated audio is <see cref="GeneratedSpeechFormat.Mp3"/> unless otherwise specified
154 /// via <see cref="SpeechGenerationOptions.ResponseFormat"/>.
155 /// </remarks>
156 /// <param name="text"> The text to generate audio for. </param>
157 /// <param name="voice"> The voice to use in the generated audio. </param>
158 /// <param name="options"> The options to configure the audio generation. </param>
159 /// <param name="cancellationToken"> A token that can be used to cancel this method call. </param>
160 /// <exception cref="ArgumentNullException"> <paramref name="text"/> is null. </exception>
161 /// <returns> The generated audio in the specified output format. </returns>
162 public virtual ClientResult<BinaryData> GenerateSpeech(string text, GeneratedSpeechVoice voice, SpeechGenerationOptions options = null, CancellationToken cancellationToken = default)
163 {
164 Argument.AssertNotNull(text, nameof(text));
165
166 options ??= new();
167 CreateSpeechGenerationOptions(text, voice, ref options);
168
169 using BinaryContent content = options.ToBinaryContent();
170 ClientResult result = GenerateSpeech(content, cancellationToken.ToRequestOptions()); ;
171 return ClientResult.FromValue(result.GetRawResponse().Content, result.GetRawResponse());
172 }
173
174 #endregion
175
176 #region TranscribeAudio
177
178 /// <summary> Transcribes the input audio. </summary>
179 /// <param name="audio"> The audio stream to transcribe. </param>
180 /// <param name="audioFilename">
181 /// The filename associated with the audio stream. The filename's extension (for example: .mp3) will be used to
182 /// validate the format of the input audio. The request may fail if the filename's extension and the actual
183 /// format of the input audio do not match.
184 /// </param>
185 /// <param name="options"> The options to configure the audio transcription. </param>
186 /// <param name="cancellationToken"> A token that can be used to cancel this method call. </param>
187 /// <exception cref="ArgumentNullException"> <paramref name="audio"/> or <paramref name="audioFilename"/> is null. </exception>
188 /// <exception cref="ArgumentException"> <paramref name="audioFilename"/> is an empty string, and was expected to be non-empty. </exception>
189 public virtual async Task<ClientResult<AudioTranscription>> TranscribeAudioAsync(Stream audio, string audioFilename, AudioTranscriptionOptions options = null, CancellationToken cancellationToken = default)
190 {
191 Argument.AssertNotNull(audio, nameof(audio));
192 Argument.AssertNotNullOrEmpty(audioFilename, nameof(audioFilename));
193
194 using MultiPartFormDataBinaryContent content
195 = CreatePerCallTranscriptionOptions(options)
196 .ToMultipartContent(audio, audioFilename);
197
198 ClientResult result = await TranscribeAudioAsync(content, content.ContentType, cancellationToken.ToRequestOptions()).ConfigureAwait(false);
199 return ClientResult.FromValue(AudioTranscription.FromResponse(result.GetRawResponse()), result.GetRawResponse());
200 }
201
202 /// <summary> Transcribes the input audio. </summary>
203 /// <param name="audio"> The audio stream to transcribe. </param>
204 /// <param name="audioFilename">
205 /// The filename associated with the audio stream. The filename's extension (for example: .mp3) will be used to
206 /// validate the format of the input audio. The request may fail if the filename's extension and the actual
207 /// format of the input audio do not match.
208 /// </param>
209 /// <param name="options"> The options to configure the audio transcription. </param>
210 /// <param name="cancellationToken"> A token that can be used to cancel this method call. </param>
211 /// <exception cref="ArgumentNullException"> <paramref name="audio"/> or <paramref name="audioFilename"/> is null. </exception>
212 /// <exception cref="ArgumentException"> <paramref name="audioFilename"/> is an empty string, and was expected to be non-empty. </exception>
213 public virtual ClientResult<AudioTranscription> TranscribeAudio(Stream audio, string audioFilename, AudioTranscriptionOptions options = null, CancellationToken cancellationToken = default)
214 {
215 Argument.AssertNotNull(audio, nameof(audio));
216 Argument.AssertNotNullOrEmpty(audioFilename, nameof(audioFilename));
217
218 using MultiPartFormDataBinaryContent content
219 = CreatePerCallTranscriptionOptions(options)
220 .ToMultipartContent(audio, audioFilename);
221
222 ClientResult result = TranscribeAudio(content, content.ContentType, cancellationToken.ToRequestOptions());
223 return ClientResult.FromValue(AudioTranscription.FromResponse(result.GetRawResponse()), result.GetRawResponse());
224 }
225
226 /// <summary> Transcribes the input audio. </summary>
227 /// <param name="audioFilePath">
228 /// The path of the audio file to transcribe. The provided file path's extension (for example: .mp3) will be
229 /// used to validate the format of the input audio. The request may fail if the file path's extension and the
230 /// actual format of the input audio do not match.
231 /// </param>
232 /// <param name="options"> The options to configure the audio transcription. </param>
233 /// <exception cref="ArgumentNullException"> <paramref name="audioFilePath"/> is null. </exception>
234 /// <exception cref="ArgumentException"> <paramref name="audioFilePath"/> is an empty string, and was expected to be non-empty. </exception>
235 public virtual async Task<ClientResult<AudioTranscription>> TranscribeAudioAsync(string audioFilePath, AudioTranscriptionOptions options = null)
236 {
237 Argument.AssertNotNullOrEmpty(audioFilePath, nameof(audioFilePath));
238
239 using FileStream audioStream = File.OpenRead(audioFilePath);
240 return await TranscribeAudioAsync(audioStream, audioFilePath, options).ConfigureAwait(false);
241 }
242
243 /// <summary> Transcribes the input audio. </summary>
244 /// <param name="audioFilePath">
245 /// The path of the audio file to transcribe. The provided file path's extension (for example: .mp3) will be
246 /// used to validate the format of the input audio. The request may fail if the file path's extension and the
247 /// actual format of the input audio do not match.
248 /// </param>
249 /// <param name="options"> The options to configure the audio transcription. </param>
250 /// <exception cref="ArgumentNullException"> <paramref name="audioFilePath"/> is null. </exception>
251 /// <exception cref="ArgumentException"> <paramref name="audioFilePath"/> is an empty string, and was expected to be non-empty. </exception>
252 public virtual ClientResult<AudioTranscription> TranscribeAudio(string audioFilePath, AudioTranscriptionOptions options = null)
253 {
254 Argument.AssertNotNullOrEmpty(audioFilePath, nameof(audioFilePath));
255
256 using FileStream audioStream = File.OpenRead(audioFilePath);
257 return TranscribeAudio(audioStream, audioFilePath, options);
258 }
259
260 // CUSTOM: Added Experimental attribute.
261 [Experimental("OPENAI001")]
262 public virtual AsyncCollectionResult<StreamingAudioTranscriptionUpdate> TranscribeAudioStreamingAsync(Stream audio, string audioFilename, AudioTranscriptionOptions options = null, CancellationToken cancellationToken = default)
263 {
264 Argument.AssertNotNull(audio, nameof(audio));
265 Argument.AssertNotNullOrEmpty(audioFilename, nameof(audioFilename));
266
267 EnsureModelSupportsStreaming();
268
269 MultiPartFormDataBinaryContent content
270 = CreatePerCallTranscriptionOptions(options, stream: true)
271 .ToMultipartContent(audio, audioFilename);
272
273 return new AsyncSseUpdateCollection<StreamingAudioTranscriptionUpdate>(
274 async () => await TranscribeAudioAsync(content, content.ContentType, cancellationToken.ToRequestOptions(streaming: true)).ConfigureAwait(false),
275 StreamingAudioTranscriptionUpdate.DeserializeStreamingAudioTranscriptionUpdate,
276 cancellationToken);
277 }
278
279 // CUSTOM: Added Experimental attribute.
280 [Experimental("OPENAI001")]
281 public virtual AsyncCollectionResult<StreamingAudioTranscriptionUpdate> TranscribeAudioStreamingAsync(string audioFilePath, AudioTranscriptionOptions options = null, CancellationToken cancellationToken = default)
282 {
283 Argument.AssertNotNullOrEmpty(audioFilePath, nameof(audioFilePath));
284
285 EnsureModelSupportsStreaming();
286
287 FileStream inputStream = File.OpenRead(audioFilePath);
288
289 MultiPartFormDataBinaryContent content
290 = CreatePerCallTranscriptionOptions(options, stream: true)
291 .ToMultipartContent(inputStream, audioFilePath);
292
293 AsyncSseUpdateCollection<StreamingAudioTranscriptionUpdate> result = new(
294 async () => await TranscribeAudioAsync(content, content.ContentType, cancellationToken.ToRequestOptions(streaming: true)).ConfigureAwait(false),
295 StreamingAudioTranscriptionUpdate.DeserializeStreamingAudioTranscriptionUpdate,
296 cancellationToken);
297 result.AdditionalDisposalActions.Add(() => inputStream?.Dispose());
298 return result;
299 }
300
301 // CUSTOM: Added Experimental attribute.
302 [Experimental("OPENAI001")]
303 public virtual CollectionResult<StreamingAudioTranscriptionUpdate> TranscribeAudioStreaming(Stream audio, string audioFilename, AudioTranscriptionOptions options = null, CancellationToken cancellationToken = default)
304 {
305 Argument.AssertNotNull(audio, nameof(audio));
306 Argument.AssertNotNullOrEmpty(audioFilename, nameof(audioFilename));
307
308 EnsureModelSupportsStreaming();
309
310 MultiPartFormDataBinaryContent content
311 = CreatePerCallTranscriptionOptions(options, stream: true)
312 .ToMultipartContent(audio, audioFilename);
313
314 return new SseUpdateCollection<StreamingAudioTranscriptionUpdate>(
315 () => TranscribeAudio(content, content.ContentType, cancellationToken.ToRequestOptions(streaming: true)),
316 StreamingAudioTranscriptionUpdate.DeserializeStreamingAudioTranscriptionUpdate,
317 cancellationToken);
318 }
319
320 // CUSTOM: Added Experimental attribute.
321 [Experimental("OPENAI001")]
322 public virtual CollectionResult<StreamingAudioTranscriptionUpdate> TranscribeAudioStreaming(string audioFilePath, AudioTranscriptionOptions options = null, CancellationToken cancellationToken = default)
323 {
324 Argument.AssertNotNullOrEmpty(audioFilePath, nameof(audioFilePath));
325
326 EnsureModelSupportsStreaming();
327
328 FileStream inputStream = File.OpenRead(audioFilePath);
329
330 MultiPartFormDataBinaryContent content
331 = CreatePerCallTranscriptionOptions(options, stream: true)
332 .ToMultipartContent(inputStream, audioFilePath);
333
334 SseUpdateCollection<StreamingAudioTranscriptionUpdate> result = new(
335 () => TranscribeAudio(content, content.ContentType, cancellationToken.ToRequestOptions(streaming: true)),
336 StreamingAudioTranscriptionUpdate.DeserializeStreamingAudioTranscriptionUpdate,
337 cancellationToken);
338 result.AdditionalDisposalActions.Add(() => inputStream?.Dispose());
339 return result;
340 }
341
342 private void EnsureModelSupportsStreaming()
343 {
344 if (string.Equals(_model, "whisper-1", StringComparison.OrdinalIgnoreCase))
345 {
346 string isEnabled = Environment.GetEnvironmentVariable("OPENAI_ENABLE_WHISPER_1_STREAMING");
347 if (!string.Equals(isEnabled, "true", StringComparison.OrdinalIgnoreCase))
348 {
349 throw new NotSupportedException(
350 "The selected model 'whisper-1' does not support streaming transcription. " +
351 "Please use a compatible model or set the environment variable 'OPENAI_ENABLE_WHISPER_1_STREAMING=true' to bypass this check.");
352 }
353 }
354 }
355
356 #endregion
357
358 #region TranslateAudio
359
360 /// <summary> Translates the input audio into English. </summary>
361 /// <param name="audio"> The audio stream to translate. </param>
362 /// <param name="audioFilename">
363 /// The filename associated with the audio stream. The filename's extension (for example: .mp3) will be used to
364 /// validate the format of the input audio. The request may fail if the filename's extension and the actual
365 /// format of the input audio do not match.
366 /// </param>
367 /// <param name="options"> The options to configure the audio translation. </param>
368 /// <param name="cancellationToken"> A token that can be used to cancel this method call. </param>
369 /// <exception cref="ArgumentNullException"> <paramref name="audio"/> or <paramref name="audioFilename"/> is null. </exception>
370 /// <exception cref="ArgumentException"> <paramref name="audioFilename"/> is an empty string, and was expected to be non-empty. </exception>
371 public virtual async Task<ClientResult<AudioTranslation>> TranslateAudioAsync(Stream audio, string audioFilename, AudioTranslationOptions options = null, CancellationToken cancellationToken = default)
372 {
373 Argument.AssertNotNull(audio, nameof(audio));
374 Argument.AssertNotNullOrEmpty(audioFilename, nameof(audioFilename));
375
376 options ??= new();
377 CreateAudioTranslationOptions(audio, audioFilename, ref options);
378
379 using MultiPartFormDataBinaryContent content = options.ToMultipartContent(audio, audioFilename);
380 ClientResult result = await TranslateAudioAsync(content, content.ContentType, cancellationToken.ToRequestOptions()).ConfigureAwait(false);
381 return ClientResult.FromValue(AudioTranslation.FromResponse(result.GetRawResponse()), result.GetRawResponse());
382 }
383
384 /// <summary> Translates the input audio into English. </summary>
385 /// <param name="audio"> The audio stream to translate. </param>
386 /// <param name="audioFilename">
387 /// The filename associated with the audio stream. The filename's extension (for example: .mp3) will be used to
388 /// validate the format of the input audio. The request may fail if the filename's extension and the actual
389 /// format of the input audio do not match.
390 /// </param>
391 /// <param name="options"> The options to configure the audio translation. </param>
392 /// <param name="cancellationToken"> A token that can be used to cancel this method call. </param>
393 /// <exception cref="ArgumentNullException"> <paramref name="audio"/> or <paramref name="audioFilename"/> is null. </exception>
394 /// <exception cref="ArgumentException"> <paramref name="audioFilename"/> is an empty string, and was expected to be non-empty. </exception>
395 public virtual ClientResult<AudioTranslation> TranslateAudio(Stream audio, string audioFilename, AudioTranslationOptions options = null, CancellationToken cancellationToken = default)
396 {
397 Argument.AssertNotNull(audio, nameof(audio));
398 Argument.AssertNotNullOrEmpty(audioFilename, nameof(audioFilename));
399
400 options ??= new();
401 CreateAudioTranslationOptions(audio, audioFilename, ref options);
402
403 using MultiPartFormDataBinaryContent content = options.ToMultipartContent(audio, audioFilename);
404 ClientResult result = TranslateAudio(content, content.ContentType, cancellationToken.ToRequestOptions());
405 return ClientResult.FromValue(AudioTranslation.FromResponse(result.GetRawResponse()), result.GetRawResponse());
406 }
407
408 /// <summary> Translates the input audio into English. </summary>
409 /// <param name="audioFilePath">
410 /// The path of the audio file to translate. The provided file path's extension (for example: .mp3) will be
411 /// used to validate the format of the input audio. The request may fail if the file path's extension and the
412 /// actual format of the input audio do not match.
413 /// </param>
414 /// <param name="options"> The options to configure the audio translation. </param>
415 /// <exception cref="ArgumentNullException"> <paramref name="audioFilePath"/> was null. </exception>
416 /// <exception cref="ArgumentException"> <paramref name="audioFilePath"/> is an empty string, and was expected to be non-empty. </exception>
417 public virtual ClientResult<AudioTranslation> TranslateAudio(string audioFilePath, AudioTranslationOptions options = null)
418 {
419 Argument.AssertNotNullOrEmpty(audioFilePath, nameof(audioFilePath));
420
421 using FileStream audioStream = File.OpenRead(audioFilePath);
422 return TranslateAudio(audioStream, audioFilePath, options);
423 }
424
425 /// <summary> Translates the input audio into English. </summary>
426 /// <param name="audioFilePath">
427 /// The path of the audio file to translate. The provided file path's extension (for example: .mp3) will be
428 /// used to validate the format of the input audio. The request may fail if the file path's extension and the
429 /// actual format of the input audio do not match.
430 /// </param>
431 /// <param name="options"> The options to configure the audio translation. </param>
432 /// <exception cref="ArgumentNullException"> <paramref name="audioFilePath"/> was null. </exception>
433 /// <exception cref="ArgumentException"> <paramref name="audioFilePath"/> is an empty string, and was expected to be non-empty. </exception>
434 public virtual async Task<ClientResult<AudioTranslation>> TranslateAudioAsync(string audioFilePath, AudioTranslationOptions options = null)
435 {
436 Argument.AssertNotNull(audioFilePath, nameof(audioFilePath));
437
438 using FileStream audioStream = File.OpenRead(audioFilePath);
439 return await TranslateAudioAsync(audioStream, audioFilePath, options);
440 }
441
442 #endregion
443
444 private void CreateSpeechGenerationOptions(string text, GeneratedSpeechVoice voice, ref SpeechGenerationOptions options)
445 {
446 options.Input = text;
447 options.Voice = voice;
448 options.Model = _model;
449 }
450
451 internal virtual AudioTranscriptionOptions CreatePerCallTranscriptionOptions(AudioTranscriptionOptions userOptions, bool stream = false)
452 {
453 AudioTranscriptionOptions copiedOptions = userOptions is null ? new() : userOptions.GetClone();
454
455 copiedOptions.Model = _model;
456
457 if (stream)
458 {
459 copiedOptions.Stream = true;
460 }
461
462 return copiedOptions;
463 }
464
465 private void CreateAudioTranslationOptions(Stream audio, string audioFilename, ref AudioTranslationOptions options)
466 {
467 options.Model = _model;
468 }
469}
470